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
To easily create your PWA presentation it is suggested you create your slides using the CLI and the starter kit as described in the previous chapter, so you can enjoy all the features. However, the DeckDeckGo core component could be installed in any project too. If you wish to do so, use it directly in your project via a CDN. Use a simple script and include, or install it from npm. Installing the core component as displayed below will "only" install the "engine" of DeckDeckGo respectively, its core doesn't contain any slides. Splitting the core and the templates allows you to minimize dependencies and the amount of external code required in your project. Doing this gives the best performance while running the presentation upfront. It's recommended to use unpkg as a CDN for the DeckDeckGo core. To do so, add the following include script in the main HTML file of your project: <script type="module" src=""></script> <script nomodule="" src=""></script> Install DeckDeckGo in your project from npm using the following command: npm install @deckdeckgo/core The Stencil documentation provides examples of framework integration for Angular, React, Vue and Ember. That being said, commonly, you might either import or load the component: import '@deckdeckgo/core'; import { defineCustomElements as deckDeckGoElements } from '@deckdeckgo/core/dist/loader'; deckDeckGoElements();
https://docs.deckdeckgo.com/docs/installation/
CC-MAIN-2020-40
refinedweb
217
50.46
Hi, I am currently doing some software interfacing with arduino. As there are no physical buttons/switches involved, how can I produce an interrupt to the program? My program is big, and it has lots of loops and, yes. delays. So interrupt is really needed. (but without pressing any physical switches) Here’s the code for the interrupt #include <avr/interrupt.h> //volatile int bumper; // have we hit something void setup(){ Serial.begin(9600); pinMode(2, INPUT); // Make digital 2 an input // attach our interrupt pin to it's ISR attachInterrupt(0, bumperISR, CHANGE); // we need to call this to enable interrupts interrupts(); } // The interrupt hardware calls this when we hit our left bumper void bumperISR(){ // bumper = 1; Serial.println("interrupt!"); } void loop(){ // if bumper triggered /*if(bumper > 0){ Serial.println("tadaaa"); delay(5000); bumper = 0; }*/ Serial.println(millis()); delay(10997); // we could do lots of other stuff here. } If using this physical interrupt (using switch), it’s a success. I’ve tried to hook the interrupt pin (digital pin 2 of Mega) to the RX pin. so that, when I print some text, it will blink and trigger the the attachInterrupt(0, bumperISR, CHANGE). (it will repeat the interrupt twice, as the status will be low> high > low. But as usual, all my serial input to the arduino will be corrupted. (I will be sending some string starting with ‘<’ and end with ‘>’. e.g so that the arduino will recognize this string, and turn on/off something. Any ideas? Thank you.
https://forum.arduino.cc/t/serial-interrupt-from-rx-pin/53966
CC-MAIN-2022-40
refinedweb
252
66.23
I’m very confused at the moment regarding inheritance. I have a class that inherits from Time as in: class RTDate < Time …my methods adding to the class end I have the initialize method inherit from the parent class. Here is where I get confused: irb(main):001:0> require ‘rtdate2.rb’ => true irb(main):002:0> r = RTDate.new => Mon May 14 09:12:06 PDT 2007 irb(main):003:0> r.class => RTDate irb(main):004:0> s = r.yesterday => Sun May 13 09:12:06 PDT 2007 irb(main):005:0> s.class => Time irb(main):006:0> Here is what I don’t understand - why does s become a Time object instead of an RTDate object. If I do s = r, then I can get all of my methods out because s becomes an RTDate object. I’m really confused because the yesterday method is specific to my RTDate class so how can the resulting object be a time? Below is an excerpt from my class thus far: class RTDate < Time def yesterday self - (606024) end end
https://www.ruby-forum.com/t/ruby-inheritance-question/104140
CC-MAIN-2021-31
refinedweb
181
74.49
Now, this is hardly the time to delve into the depths of servlet syntax. Don't worry, you'll get plenty of that throughout the book. But it is worthwhile to take a quick look at a simple servlet, just to get a feel for the basic level of complexity. Listing 1.1 shows a simple servlet that outputs a small HTML page to the client. Figure 1-2 shows the result. The code is explained in detail in Chapter 3 (Servlet Basics), but for now, just notice four points: It is regular Java code. There are new APIs, but no new syntax. It has unfamiliar import statements. The servlet and JSP APIs are not part of the Java 2 Platform, Standard Edition (J2SE); they are a separate specification (and are also part of the Java 2 Platform, Enterprise EditionJ2EE). It extends a standard class ( HttpServlet ). Servlets provide a rich infrastructure for dealing with HTTP. It overrides the doGet method. Servlets have different methods to respond to different types of HTTP commands. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloServlet"; out.println(docType + "<HTML>\n" + "<HEAD><TITLE>Hello</TITLE></HEAD>\n" + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1>Hello</H1>\n" + "</BODY></HTML>"); } }
https://flylib.com/books/en/1.94.1.17/1/
CC-MAIN-2021-17
refinedweb
206
67.45
. The and the Rule Interchange Format (RIF). defined to have an extensible system of typed literals, based on XML Schema datatypes [XSD], and also to have plain literals. In the RDF specification, plain literals differ from typed literals in that plain literals have no datatype and can optionally have a language tag, indicating the natural language of the content. (See Tags for Identifying Languages [BCP 47]). These options for expressing RDF literals complicate specifications which interact with RDF, such as RIF and OWL. Furthermore, RDF does not provide a name for the set of all plain literals, which, for example, prevents one from stating in RDFS or OWL that the range of some property must be a plain literal. In response, this specification introduces a datatype called rdf:PlainLiteral. The datatype is in the "rdf:" namespace because it refers to parts of the conceptual model of RDF. This extension, however, does not change that conceptual model, and thus does not affect specifications that depend on it, such as SPARQL [SPARQL]. The value space of rdf:PlainLiteral:PlainLiteral literals are written as RDF plain literals in RDF and SPARQL syntaxes. As with plain literals, this datatype can associate language tags with Unicode strings, but it does not provide its own facilities for representing natural language utterances. Unicode bidirectional control characters [BIDI] may be used within these literals, like all other Unicode characters. (Richer, XML-based representations such as XHTML [XHTML] and Ruby annotations [RUBY] can be expressed using the rdf:XMLLiteral datatype.) A character is an atomic unit of text. Each character has a Universal Character Set (UCS) code point [ISO/IEC 10646] (or, equivalently, a Unicode code point [UNICODE]) that MUST match the Char production from XML [XML] thus ensuring compatibility with XML Schema Datatypes [XML Schema Datatypes]. Code points are sometimes represented in this document as U+ followed by a four-digit hexadecimal value of the code point. A string is a finite sequence of zero or more characters. The length of a string is the number of characters in it. Strings are written in this specification by enclosing them in double quotes. Two strings are identical if and only if they contain exactly the same characters in exactly the same sequence. UCS [ISO/IEC 10646] and Unicode [UNICODE] provide for 1,114,112 different code points. The Char production from XML [XML], however, excludes the surrogate code points and the code points U+FFFE and U+FFFF. Thus, rdf:PlainLiteral provides a total of 1,112,033 different characters. This number is important, as it can affect the satisfiability of an OWL 2 ontology. Consider the following example: This OWL 2 axiom states that the individual a:i is connected by the property a:property to at least n different strings of length one. The number of such strings is limited to 1,112,033 by the above definitions, so this ontology is satisfiable if and only if n is smaller than or equal to 1,112,033. A language tag is a string matching the langtag production from BCP 47 [BCP 47]. Furthermore, note that this definition corresponds to the well-formed rather than the valid class of conformance in BCP 47. A language tag MAY contain subtags that are not registered in the IANA Language Subtag Registry, although an rdf:PlainLiteral implementation MAY also choose to reject such invalid language tags. The language tag "en-fubar" is not registered with the IANA Language Subtag Registry, so an rdf:PlainLiteral implementation is allowed to reject it. This string, however, matches the langtag production from BCP 47, so it is a perfectly valid language tag for the purpose of this specification. Consequently, the value space of rdf:PlainLiteral : Whether an expression of the form pr:ln denotes an abbreviated URI or a QName should be clear from the context: only the names of the built-in functions in Section 5 are QNames; all other such expressions denote abbreviated URIs. Datatypes are defined in this document along the lines of XML Schema Datatypes [XML Schema Datatypes]. Each datatype is identified by a URI and is described by the following components:" >. A typed literal consists of a string and a datatype URI [RDF] and can be written as "abc"^^datatypeURI. Given an RDF datatype identified by datatypeURI, an RDF datatyped-interpretation that includes the datatype interprets the typed literal as the data value that the datatype assigns to the lexical form "abc".:PlainLiteral) is defined as follows. Value Space. The value space of rdf:PlainLiteral consists of Lexical Space. An rdf:PlainLiteral lexical form is a string of the form "abc@langTag" where "abc" is an arbitrary (possibly empty) string, and "langTag" is either the empty string or a (not necessarily lowercase) language tag. Each such lexical form is mapped to a data value dv as follows: The following table shows several rdf:PlainLiteral lexical forms and their corresponding data values. The following table shows several of strings that are not rdf:PlainLiteral lexical forms. Facet Space. The facet space of rdf:PlainLiteral is defined as shown in Table 1. The facet xs:length can be used to refer to a subset of strings of a particular length regardless of whether they have a language tag or not. Thus, the subset of the value space of rdf:PlainLiteral corresponding to the facet pair ( xs:length 3 ) contains the string "abc", as well as the pairs < "abc" , "en" > and < "abc" , "de" >. The facet rdf:langRange can be used to refer to a subset of strings containing the language tag. Note that the language range need not be in lowercase, and that the matching algorithm is case-insensitive. Thus, the subset of the value space of rdf:PlainLiteral corresponding to the facet pair ( rdf:langRange "de-DE" ) contains the pairs < "abc" , "de-de" > and < "abc" , "de-de-1996" > (because these match the language range "de-DE" according to RFC 4647), but not the string "abc" (because it is not a pair with a language tag) or the pairs < "abc" , "de-deva" > and < "abc" , "de-latn-de" > (because these do not match the language range "de-DE" according to RFC 4647). The facet pair ( rdf:langRange "*" ) is mapped to the subset of the value space of rdf:PlainLiteral containing all pairs of the form < "abc" , "lc-langtag" >. In languages such as OWL 2, this can be used to specify that a data value must contain the language tag. It follows from the above that in datatyped interpretations that include the rdf:PlainLiteral datatype, the value space of rdf:PlainLiteral contains exactly all data values assigned to plain literals (with or without a language tag). The rdf:PlainLiteral datatype thus provides an explicit way of referring to this set. To eliminate another source of syntactic redundancy and to retain a large degree of interoperability with applications that do not understand the rdf:PlainLiteral datatype, the form of rdf:PlainLiteral literals in syntaxes for RDF graphs and for SPARQL is the already existing syntax for the corresponding plain literal, not the syntax for a typed literal. Therefore, typed literals with rdf:PlainLiteral as the datatype are considered by this specification to be not valid in syntaxes for RDF graphs or SPARQL. To implement this design and provide this interoperability, applications that employ this datatype MUST use plain literals (instead of rdf:PlainLiteral typed literals) whenever a syntax for plain literals is provided, such as in existing syntaxes for RDF graphs and SPARQL results. Additionally, systems may need similar restrictions for non-syntactic public interfaces. For instance, in extended SPARQL basic graph matching, the results of matching SPARQL basic graph patterns in an entailment regime that understands rdf:PlainLiteral MUST provide variable bindings in existing RDF plain literal form. This section defines functions that construct and operate on rdf:PlainLiteral data values. The terminology used and the way in which these functions are described are in accordance with the XQuery 1.0 and XPath 2.0 Functions and Operators [XPathFunc]. Each function is identified by a QName [XML Namespaces]. The error codes used in this section are given in Appendix G of the XPath 2.0 specification [XPath20] and Appendix C of XQuery and XPath function specification [XPathFunc]. plfn:PlainLiteral-from-string-lang( $arg1 as xs:string, $arg2 as xs:string) as rdf:PlainLiteral Summary: returns the data value < $arg1, lowercase($arg2) > if $arg2 is present, and returns the data value $arg1 otherwise. Both arguments must be of type xs:string or one of its subtypes, and $arg2 — if present — must be a (nonempty) language tag; otherwise, this function raises type error err:FORG0006. Note that, since in the value space of rdf:PlainLiteral language are in lowercase, this function converts $arg2 to lowercase. plfn:string-from-PlainLiteral( $arg as rdf:PlainLiteral) as xs:string Summary: returns the string part s if $arg is a rdf:PlainLiteral data value of the form < s, l > or of the form s. If $arg is not of type rdf:PlainLiteral, this function raises type error err:FORG0006. plfn:lang-from-PlainLiteral( $arg as rdf:PlainLiteral ) as xs:language Summary: returns the language tag l if $arg is an rdf:PlainLiteral data value of the form < s, l >, and returns the empty string if $arg is an rdf:PlainLiteral data value of the form s. If $arg is not of type rdf:PlainLiteral, this function raises type error err:FORG0006. The notion of collations used in this section is taken from Section 7.3.1 of XPath and XQuery function specification [XPathFunc]. plfn:compare( $comparand1 as rdf:PlainLiteral?, $comparand2 as rdf:PlainLiteral? ) as xs:integer? plfn:compare( $comparand1 as rdf:PlainLiteral?, $comparand2 as rdf:PlainLiteral?, $collation as xs:string ) as xs:integer? Summary: if either $comparand1 or $comparand2 is not of type rdf:PlainLiteral, of if $collation is specified but is not of type xs:string, this function raises type error err:FORG0006. Otherwise, the function returns the empty sequence if one of the arguments is empty, if one of $comparand1 and $comparand2 has a language tag and the other one does not, or if the language parts of $comparand1 and $comparand2 are unequal;. The two functions may be viewed as declared XQuery functions with the following definitions: declare function plfn:compare( $comparand1 as rdf:PlainLiteral?, $comparand2 as rdf:PlainLiteral? ) ) ) } declare function plfn:compare( $comparand1 as rdf:PlainLiteral?, $comparand2 as rdf:PlainLiteral? $collation as xs:string ) ), $collation) } plfn:length($arg as rdf:PlainLiteral) as xs:integer Summary: returns the number of characters in the string part s if $arg is an rdf:PlainLiteral data value of the form < s, l > or a string value s, respectively. If $arg is not of type rdf:PlainLiteral, this function raises type error err:FORG0006. This function may be viewed as a declared XQuery function with the following definition: declare function plfn:length($arg as rdf:PlainLiteral?) as xs:integer { return fn:string-length ( plfn:string-from-PlainLiteral( $arg ) ) } plfn:matches-language-range($arg as rdf:PlainLiteral?, $range as xs:string) as xs:boolean Summary: This function is only defined if $arg is a sequence of length 0 or 1 of literals of type rdf:PlainLiteral and $range is of type xs:string; if the parameters do not satisfy these typing conditions, the function raises a type error err:FORG0006. If the typing conditions are fulfilled, the function returns true in case $arg is an rdf:PlainLiteral:PlainLiteral data value. An empty input sequence is treated as a rdf:PlainLiteral data value consisting of the empty string, and accordingly on such input this function also returns false. The RIF and OWL Working Groups made parallel efforts to support strings with associated language tags, as found in RDF. This specification is the outcome of a collaboration between the two groups, and it is based on the work on the datatypes rif:text and owl:internationalizedString. In addition to members and chairs of both Working Groups, the editors would like to thank Addison Phillips, C. Michael Sperberg-McQueen, Eric Prud'hommeaux, Andy Seaborne, and Pat Hayes, along with other participants of the public-rdf-text mailing list, for their assistance in working out the details of this specification. This section summarizes the changes to this document since the Candidate Recommendation of 11 June, 2009. Since the last call draft of 21 April 2009, the following changes have been made:
http://www.w3.org/TR/2009/PR-rdf-plain-literal-20090922/
CC-MAIN-2015-48
refinedweb
2,063
51.28
[Previous: QtDesigner Module] [Qt's Modules] [Next: QtHelp Module] The QtUiTools module provides classes to handle forms created with Qt Designer. More... These forms are processed at run-time to produce dynamically-generated user interfaces. In order to generate a form at run-time, a resource file containing a .ui file is needed. Applications that use the form handling classes need to be configured to be built against the QtUiTools module. This is done by including the following declaration in a qmake project file to ensure that the application is compiled and linked appropriately. CONFIG += uitools A form loader object, provided by the QUiLoader class, is used to construct the user interface. This user interface can be retrieved from any QIODevice; for example, a QFile object can be used to obtain a form stored in a project's resources. The QUiLoader::load() function takes the user interface description contained in the file and constructs the form widget. To include the definitions of the module's classes, use the following directive: #include <QtUiTools> Note: These classes are part of the Open Source Versions of Qt and Qt Full Framework Edition for commercial users. See also Calculator Builder Example and World Time Clock Builder Example. [Previous: QtDesigner Module] [Qt's Modules] [Next: QtHelp Module]
http://doc.trolltech.com/4.5-snapshot/qtuitools.html
crawl-003
refinedweb
212
54.22
Give the following three codelets, /* main.c */ __attribute__((weak)) void foo(); int main(int argc, char const *argv[]) { foo(); return 0; } /* a.c */ __attribute__((weak)) void foo() {} /* b.c */ __attribute__((weak)) void foo() {} when linking with the command line gcc -o a main.c a.c b.c , the linker would complain something like ccfHPkfI.o:b.c:(.text+0x0): multiple definition of `.weak.foo.' ccriLvHy.o:a.c:(.text+0x0): first defined here" but it's okay under linux; Moreover, it looks like the mingw linker will mangle the weak symbols with the first defined symbol's name, hence I've to add some guard to prevent the multiple definitions error, then i change the codelets to the following. /* a.c */ /* Guard workaround for mingw's weak symbols linking.*/ #if defined(__MINGW32__) || defined(__MINGW64__) char __76dc9de9_9553_4eb6_b09d_ef4e9bbab8f0__; #endif __attribute__((weak)) void foo() {} /* b.c */ /* Guard workaround for mingw's weak symbols linking.*/ #if defined(__MINGW32__) || defined(__MINGW64__) char __6e108c68_72c3_4b1e_be43_b40e018b4c5a__; #endif __attribute__((weak)) void foo() {} Now finally it links however the executable would cause some "a.exe has stopped working" error. There are two workarounds about this: 1. Change the declaration to "void foo() __attribute__((section ".gnu.linkonce.0."));", put it into a special section does something similar to variable attribute's "__attribute__((selectany))"; 2. For C++, change the declaration to "inline void foo() __attribute__((used));", this is mimicking the c++ template function behavior and resulted in putting pseudo op ".linkonce discard" into the final assembly. I want to know why weak attribute under mingw would have such strange behavior? PS: I'm using GCC 4.7.2 and Binutils 2.22.90 under windows.
https://sourceforge.net/p/mingw-w64/discussion/723797/thread/cb56b388/
CC-MAIN-2017-04
refinedweb
274
68.87
Subject: Re: [boost] the <boost/detail/iomanip.hpp> header (please use it) From: Steven Watanabe (watanabesj_at_[hidden]) Date: 2011-01-14 20:12:32 AMDG On 1/13/2011 6:53 PM, Bryce Lelbach wrote: > On Linux, both clang and icc use GNU's C++ standard library by default. As of > version 4.5 of GNU's stdlib, a new implementation of the<iomanip> header has > been added, which makes use of C++0x features which only GCC supports (the > latest versions of clang, e.g. a very recent nightly build, might work; intel > certainly won't). The refactored<iomanip> header in GNU's stdlib does not > detect C++0x support and fallback on the old C++98 friendly code, which > unfortunately leaves clang-linux and intel-linux users in a bit of a bind. In > particular, this plagues clang users on Linux as clang will use the latest > available version of the GNU stdlib by default, meaning most users cannot have > both gcc-4.5 and clang installed without problems. > > I have implemented the<iomanip> header in<boost/detail/iomanip.hpp>, under > the boost::detail namespace (to avoid conflicts with system<iomanip> headers > that users/other code might include). The implementation conforms to the C++03 > standard (at least, I'm fairly confident it is standard compliant - reviews > and feedback would be welcome). Unfortunately, conforming to the standard isn't good enough. I think you just broke Codegear support in some places. After thinking about this some more, I think this is the wrong solution to the problem. Those who need to use this configuration should add a working iomanip to their compiler's search path. I am in favor of reverting this patch entirely. In Christ, Steven Watanabe Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2011/01/174959.php
CC-MAIN-2020-40
refinedweb
312
66.33
Handling Events Amazon ECS sends events on an "at least once" basis. This means you may receive more than a single copy of a given event. Additionally, events may not be delivered to your event listeners in the order in which the events occurred. To enable proper ordering of events, the detail section of each event contains a version property. Events with a higher version property number should be treated as occurring later than events with lower version numbers. Events with matching version numbers can be treated as duplicates. Example: Handling Events in an AWS Lambda Function The following example shows a Lambda function written in Python 2.7 that captures both task and container instance state change events, and saves them to one of two Amazon DynamoDB tables: ECSCtrInstanceState: Stores the latest state for a container instance. The table ID is the containerInstanceArnvalue of the container instance. ECSTaskState: Stores the latest state for a task. The table ID is the taskArnvalue of the task. import json import boto3 def lambda_handler(event, context): id_name = "" new_record = {} # For debugging so you can see raw event format. print('Here is the event:') print(json.dumps(event)) if event["source"] != "aws.ecs": raise ValueError("Function only supports input from events with a source type of: aws.ecs") # Switch on task/container events. table_name = "" if event["detail-type"] == "ECS Task State Change": table_name = "ECSTaskState" id_name = "taskArn" event_id = event["detail"]["taskArn"] elif event["detail-type"] == "ECS Container Instance State Change": table_name = "ECSCtrInstanceState" id_name = "containerInstanceArn" event_id = event["detail"]["containerInstanceArn"] else: raise ValueError("detail-type for event is not a supported type. Exiting without saving event.") new_record["cw_version"] = event["version"] new_record.update(event["detail"]) # "status" is a reserved word in DDB, but it appears in containerPort # state change messages. if "status" in event: new_record["current_status"] = event["status"] new_record.pop("status") # Look first to see if you have received a newer version of an event ID. # If the version is OLDER than what you have on file, do not process it. # Otherwise, update the associated record with this latest information. print("Looking for recent event with same ID...") dynamodb = boto3.resource("dynamodb", region_name="us-east-1") table = dynamodb.Table(table_name) saved_event = table.get_item( Key={ id_name : event_id } ) if "Item" in saved_event: # Compare events and reconcile. print("EXISTING EVENT DETECTED: Id " + event_id + " - reconciling") if saved_event["Item"]["version"] < event["detail"]["version"]: print("Received event is a more recent version than the stored event - updating") table.put_item( Item=new_record ) else: print("Received event is an older version than the stored event - ignoring") else: print("Saving new event - ID " + event_id) table.put_item( Item=new_record )
https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_cwet_handling.html
CC-MAIN-2018-43
refinedweb
430
58.69
Porting your apps from Django 0.96 to 1.0¶ Django 1.0 breaks compatibility with 0.96 in some areas. This guide will help you port 0.96 projects and apps to 1.0. The first part of this document includes the common changes needed to run with 1.0. If after going through the first part your code still breaks, check the section Less-common Changes for a list of a bunch of less-common compatibility issues. See also The 1.0 release notes. That document explains the new features in 1.0 more deeply; the porting guide is more concerned with helping you quickly update your code. Common changes¶ This section describes the changes between 0.96 and 1.0 that most users will need to make. Use Unicode¶ Change string literals ('foo') into Unicode literals (u'foo'). Django now uses Unicode strings throughout. In most places, raw strings will continue to work, but updating to use Unicode literals will prevent some obscure problems. See Unicode data for full details. Models¶ Common changes to your models file: Rename maxlength to max_length¶ Rename your maxlength argument to max_length (this was changed to be consistent with form fields): Replace __str__ with __unicode__¶ Replace your model’s __str__ function with a __unicode__ method, and make sure you use Unicode (u'foo') in that method. Remove prepopulated_from¶ Remove the prepopulated_from argument on model fields. It’s no longer valid and has been moved to the ModelAdmin class in admin.py. See the admin, below, for more details about changes to the admin. Remove core¶ Remove the core argument from your model fields. It is no longer necessary, since the equivalent functionality (part of inline editing) is handled differently by the admin interface now. You don’t have to worry about inline editing until you get to the admin section, below. For now, remove all references to core. Replace class Admin: with admin.py¶ Remove all your inner class Admin declarations from your models. They won’t break anything if you leave them, but they also won’t do anything. To register apps with the admin you’ll move those declarations to an admin.py file; see the admin below for more details. See also A contributor to djangosnippets has written a script that’ll scan your models.py and generate a corresponding admin.py. Example¶ Below is an example models.py file with all the changes you’ll need to make: Old (0.96) models.py: class Author(models.Model): first_name = models.CharField(maxlength=30) last_name = models.CharField(maxlength=30) slug = models.CharField(maxlength=60, prepopulate_from=('first_name', 'last_name')) class Admin: list_display = ['first_name', 'last_name'] def __str__(self): return '%s %s' % (self.first_name, self.last_name) New (1.0) models.py: class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) slug = models.CharField(max_length=60) def __unicode__(self): return u'%s %s' % (self.first_name, self.last_name) New (1.0) admin.py: from django.contrib import admin from models import Author class AuthorAdmin(admin.ModelAdmin): list_display = ['first_name', 'last_name'] prepopulated_fields = { 'slug': ('first_name', 'last_name') } admin.site.register(Author, AuthorAdmin) The Admin¶ One of the biggest changes in 1.0 is the new admin. The Django administrative interface (django.contrib.admin) has been completely refactored; admin definitions are now completely decoupled from model definitions, the framework has been rewritten to use Django’s new form-handling library and redesigned with extensibility and customization in mind. Practically, this means you’ll need to rewrite all of your class Admin declarations. You’ve already seen in models above how to replace your class Admin with a admin.site.register() call in an admin.py file. Below are some more details on how to rewrite that Admin declaration into the new syntax. Use new inline syntax¶ The new edit_inline options have all been moved to admin.py. Here’s an example: Old (0.96): class Parent(models.Model): ... class Child(models.Model): parent = models.ForeignKey(Parent, edit_inline=models.STACKED, num_in_admin=3) New (1.0): class ChildInline(admin.StackedInline): model = Child extra = 3 class ParentAdmin(admin.ModelAdmin): model = Parent inlines = [ChildInline] admin.site.register(Parent, ParentAdmin) See InlineModelAdmin objects for more details. Simplify fields, or use fieldsets¶ The old fields syntax was quite confusing, and has been simplified. The old syntax still works, but you’ll need to use fieldsets instead. Old (0.96): class ModelOne(models.Model): ... class Admin: fields = ( (None, {'fields': ('foo','bar')}), ) class ModelTwo(models.Model): ... class Admin: fields = ( ('group1', {'fields': ('foo','bar'), 'classes': 'collapse'}), ('group2', {'fields': ('spam','eggs'), 'classes': 'collapse wide'}), ) New (1.0): class ModelOneAdmin(admin.ModelAdmin): fields = ('foo', 'bar') class ModelTwoAdmin(admin.ModelAdmin): fieldsets = ( ('group1', {'fields': ('foo','bar'), 'classes': 'collapse'}), ('group2', {'fields': ('spam','eggs'), 'classes': 'collapse wide'}), ) See also - More detailed information about the changes and the reasons behind them can be found on the NewformsAdminBranch wiki page - The new admin comes with a ton of new features; you can read about them in the admin documentation. URLs¶ Update your root urls.py¶ If you’re using the admin site, you need to update your root urls.py. Old (0.96) urls.py: from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^admin/', include('django.contrib.admin.urls')), # ... the rest of your URLs here ... ) New (1.0) urls.py: from django.conf.urls.defaults import * # The next two lines enable the admin and load each admin.py file: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^admin/(.*)', admin.site.root), # ... the rest of your URLs here ... ) Views¶ Use django.forms instead of newforms¶ Replace django.newforms with django.forms – Django 1.0 renamed the newforms module (introduced in 0.96) to plain old forms. The oldforms module was also removed. If you’re already using the newforms library, and you used our recommended import statement syntax, all you have to do is change your import statements. Old: from django import newforms as forms New: from django import forms If you’re using the old forms system (formerly known as django.forms and django.oldforms), you’ll have to rewrite your forms. A good place to start is the forms documentation Handle uploaded files using the new API¶ Replace use of uploaded files – that is, entries in request.FILES – as simple dictionaries with the new UploadedFile. The old dictionary syntax no longer works. Thus, in a view like: def my_view(request): f = request.FILES['file_field_name'] ... ...you’d need to make the following changes: Work with file fields using the new API¶ The internal implementation of django.db.models.FileField have changed. A visible result of this is that the way you access special attributes (URL, filename, image size, etc) of these model fields has changed. You will need to make the following changes, assuming your model’s FileField is called myfile: Note that the width and height attributes only make sense for ImageField fields. More details can be found in the model API documentation. Use Paginator instead of ObjectPaginator¶ The ObjectPaginator in 0.96 has been removed and replaced with an improved version, django.core.paginator.Paginator. Templates¶ Learn to love autoescaping¶ By default, the template system now automatically HTML-escapes the output of every variable. To learn more, see Automatic HTML escaping. To disable auto-escaping for an individual variable, use the safe filter: This will be escaped: {{ data }} This will not be escaped: {{ data|safe }} To disable auto-escaping for an entire template, wrap the template (or just a particular section of the template) in the autoescape tag: {% autoescape off %} ... unescaped template content here ... {% endautoescape %} Less-common changes¶ The following changes are smaller, more localized changes. They should only affect more advanced users, but it’s probably worth reading through the list and checking your code for these things. Signals¶ - Add **kwargs to any registered signal handlers. - Connect, disconnect, and send signals via methods on the Signal object instead of through module methods in django.dispatch.dispatcher. - Remove any use of the Anonymous and Any sender options; they no longer exist. You can still receive signals sent by any sender by using sender=None - Make any custom signals you’ve declared into instances of django.dispatch.Signal instead of anonymous objects. Here’s quick summary of the code changes you’ll need to make: If you were using Django 0.96’s django.contrib.comments app, you’ll need to upgrade to the new comments app introduced in 1.0. See Upgrading from Django’s previous comment system for details. Local flavors¶ Sessions¶ Fixtures¶ Settings¶ Better exceptions¶ The old EnvironmentError has split into an ImportError when Django fails to find the settings module and a RuntimeError when you try to reconfigure settings after having already used them LOGIN_URL has moved¶ The LOGIN_URL constant moved from django.contrib.auth into the settings module. Instead of using from django.contrib.auth import LOGIN_URL refer to settings.LOGIN_URL. APPEND_SLASH behavior has been updated¶ In 0.96, if a URL didn’t end in a slash or have a period in the final component of its path, and APPEND_SLASH was True, Django would redirect to the same URL, but with a slash appended to the end. Now, Django checks to see whether/(.*/)$' Smaller model changes¶ Different exception from get()¶ Managers now return a MultipleObjectsReturned exception instead of AssertionError: Old (0.96): try: Model.objects.get(...) except AssertionError: handle_the_error() New (1.0): try: Model.objects.get(...) except Model.MultipleObjectsReturned: handle_the_error() LazyDate has been fired¶ The LazyDate helper class no longer exists. Default field values and query arguments can both be callable objects, so instances of LazyDate can be replaced with a reference to datetime.datetime.now: Old (0.96): class Article(models.Model): title = models.CharField(maxlength=100) published = models.DateField(default=LazyDate()) New (1.0): import datetime class Article(models.Model): title = models.CharField(max_length=100) published = models.DateField(default=datetime.datetime.now) DecimalField is new, and FloatField is now a proper float¶ Old (0.96): class MyModel(models.Model): field_name = models.FloatField(max_digits=10, decimal_places=3) ... New (1.0): class MyModel(models.Model): field_name = models.DecimalField(max_digits=10, decimal_places=3) ... If you forget to make this change, you will see errors about FloatField not taking a max_digits attribute in __init__, because the new FloatField takes no precision-related arguments. If you’re using MySQL or PostgreSQL, no further changes are needed. The database column types for DecimalField are the same as for the old FloatField. If you’re using SQLite, you need to force the database to view the appropriate columns as decimal types, rather than floats. To do this, you’ll need to reload your data.). To upgrade each application to use a DecimalField, you can do the following, replacing <app> in the code below with each app’s name: $ ./manage.py dumpdata --format=xml <app> > data-dump.xml $ ./manage.py reset <app> $ ./manage.py loaddata data-dump.xml Notes: - It. Say yes; we’ll restore this data in the third step, of course. - DecimalField is not used in any of the apps shipped with Django prior to this change being made, so you do not need to worry about performing this procedure for any of the standard Django models. If something goes wrong in the above process, just copy your backed up database file over the original file and start again. Internationalization¶ django.views.i18n.set_language() now requires a POST request¶ Previously, a GET request was used. The old behavior). _() is no longer in builtins¶ _() (the callable object whose name is a single underscore) is no longer monkeypatched into builtins – that is, it’s no longer available magically in every module. If you were previously relying on _() always being present, you should now explicitly import ugettext or ugettext_lazy, if appropriate, and alias it to _ yourself: from django.utils.translation import ugettext as _ HTTP request/response objects¶ Dictionary access to HttpRequest¶ HttpRequest objects no longer directly support dictionary-style access; previously, both GET and POST data were directly available on the HttpRequest object (e.g., you could check for a piece of form data by using if 'some_form_key' in request or by reading request['some_form_key']. This is no longer supported; if you need access to the combined GET and POST data, use request.REQUEST instead. It is strongly suggested, however, that you always explicitly look in the appropriate dictionary for the type of request you expect to receive (request.GET or request.POST); relying on the combined request.REQUEST dictionary can mask the origin of incoming data. Accessing HTTPResponse headers¶ django.http.HttpResponse.headers has been renamed to _headers and HttpResponse now supports containment checking directly. So use if header in response: instead of if header in response.headers:. Generic relations¶ Generic relations have been moved out of core¶ The generic relation classes – GenericForeignKey and GenericRelation – have moved into the django.contrib.contenttypes module. Testing¶ Management commands¶ Running management commands from your code¶ django.core.management has been greatly refactored. Calls to management services in your code now need to use call_command. For example, if you have some test code that calls flush and load_data: from django.core import management management.flush(verbosity=0, interactive=False) management.load_data(['test_data'], verbosity=0) ...you’ll need to change this code to read: from django.core import management management.call_command('flush', verbosity=0, interactive=False) management.call_command('loaddata', 'test_data', verbosity=0) Data structures¶ SortedDictFromList is gone¶ django.newforms.forms.SortedDictFromList was removed. django.utils.datastructures.SortedDict can now be instantiated with a sequence of tuples. To update your code: - Use django.utils.datastructures.SortedDict wherever you were using django.newforms.forms.SortedDictFromList. - Because django.utils.datastructures.SortedDict.copy() doesn’t return a deepcopy as SortedDictFromList.copy() did, you will need to update your code if you were relying on a deepcopy. Do this by using copy.deepcopy directly.
https://docs.djangoproject.com/en/1.4/releases/1.0-porting-guide/
CC-MAIN-2015-18
refinedweb
2,300
52.66
So far, this column series has explored cloud computing with both Google's and Amazon's platforms. Though they differ in implementation and structure, both platforms enable rapid and scalable deployment. They make it possible, as never before, to assemble, test, run, and maintain Java applications quickly and inexpensively. But the cloud isn't the only factor affecting the speed of Java development today. Open source solutions also enable you to assemble software applications quickly, because you don't need to write as much code anymore. Gone are the days of writing your own object-relational mapping (ORM), logging, or testing framework. Those problems have been solved time and again in the open source world and — face it — those solutions are almost always better than yours. Across the entire spectrum of Java development, open source innovation is making applications easier to assemble. Apache CouchDB, a new (at release 0.10.0 as of this writing) open source database, is no exception. It's easy to get going with CouchDB once you have it up and running. And all you need to work with it is an HTTP connection; no JDBC driver is required, nor do you need a third-party administrative-management platform. In this article, I'll introduce you to CouchDB and show you how you can rapidly get up to speed with using it. For ease of installation, you'll take advantage of Amazon's EC2 platform. And you'll communicate with CouchDB via a handy Groovy module. A document-oriented database Relational databases essentially rule the database market. But other types of databases — including object-orienteed and document-oriented databases, which both differ vastly from the relational-oriented world — make a lot of sense from time to time. CouchDB is a document-oriented database. It's schema-less and allows you to store documents in the form of a JavaScript Object Notation (JSON) string. Think of a parking ticket. This piece of paper contains a number of items including: - The date of the infraction - The time - The location - Your vehicle's description - Your license-plate information - The offense The format and the data gathered on a ticket can vary from jurisdiction to jurisdiction. Even with a standard parking-ticket form within a single jurisdiction, what is or isn't captured on the ticket most likely varies. For example, the officer issuing the citation might not fill in the time, or might omit the vehicle make and model, opting to enter just the license-plate details. The location might be the combination of two streets (such as the intersection of Fourth and Lexington) or just a fixed address (such as 19993 Main Street). But the rough semantics of what's gathered are similar. A ticket's data points can be modeled in a relational database, but the details get a bit hairy. For example, how do you capture an intersection effectively in a relational database? And in cases where no cross street exists, does the database then have a blank field for the second address (assuming you modeled it in such as way as to capture distinct street names in individual columns)? In these cases, the abstractness of a relational database might be a bit much. The information required is already there in the form of a document (the ticket). Why not just model the data as a document, which doesn't necessarily fit into a rigid relational model but roughly follows the semantics of a high-level model? That's where CouchDB comes into play. It allows you to model these types of domains in a flexible manner — as a self-contained document that contains no schema but, instead, a roughly similar blueprint to other documents. With CouchDB, you can search for documents, properties of documents, and even relate documents just as in the relational world. You do this using views, not SQL. Views are essentially functions that you write (in JavaScript) in the style of MapReduce; that is, you end up writing a map function and a reduce function. These functions work together to filter or extract data from your documents or exploit relationships among them quite efficiently. In fact, CouchDB is smart enough to run these functions only once, provided the underlying documents don't change, which makes views quite fast. What's particularly interesting about CouchDB is its design. CouchDB embodies the basic (and highly successful) concepts of the Web itself. It exposes a completely RESTful API that permits the creation, querying, updating, and removal of documents, views, and databases. This makes CouchDB quite easy to pick up and work with. You don't need drivers or other platforms to jump-start development: a browser is essentially it. That being said, a host of libraries are available that make working with CouchDB even easier — but under the covers, they simply exploit RESTful concepts via HTTP. CouchDB, much like the Web itself, was built to be scalable. It's written in Erlang, a concurrent programming language that supports building distributed, fault-tolerant, nonstop applications (see Resources). The language (now available as open source) was developed by Ericsson and has been widely leveraged in telecommunications environments. Installing CouchDB, cloud style Installation of CouchDB varies depending on your operating system. If you are on Windows®, you need to install Cygwin, the Microsoft C compiler, and a slew of other related dependencies. If you are on a Mac, you need to use Macports. If, however, you are running on a Linux® platform, such as Ubuntu, the installation couldn't be easier. But not everyone has an Ubuntu instance handy. Or do you? Of course you have an Ubuntu instance handy! Amazon's EC2 is a relatively inexpensive way to use Ubuntu on demand. Thus, with a bit of EC2 magic, you'll have CouchDB up and running in no time; when you're done, you can power it down, so to speak. First, you'll need to find an EC2 AMI that'll work as a base instance. I ended up using AMI ami-ccf615a5, an instance of Ubuntu 9.04, which was the latest version available at the time of this writing. (By the time you read this, 9.10 will be available along with, most likely, a newer AMI.) Using either Eclipse or the AWS Management Console, launch an instance of ami-ccf615a5. Be sure to set a security policy that permits access via SSH. (Although CouchDB uses HTTP, you'll communicate with it through an SSH tunnel for simplicity's sake.) You'll also need to use a key pair. (If you need guidance, refer to the previous two articles in this series, "You can borrow EC2" and "Easy EC2.") Once you've launched an EC2 instance of Ubuntu 9.04, you need to ssh to it. (Remember the instance might take a minute or so to boot up fully, so be patient.) For example, I can open up a terminal and ssh to the newly created instance like so: aglover#> ssh -i .ec2/agkey.pem root@ec2-174-129-157-167.compute-1.amazonaws.com The DNS name of my AMI was ec2-174-129-157-167.compute-1.amazonaws.com, and I'm referencing a key pair named agkey. Your DNS name and key pair will undoubtedly be different. At the command prompt on the clouded Ubuntu instance, type: apt-get update Then type: aptitude install couchdb These commands automatically install CouchDB. However, note that they won't install the latest version. You need to install CouchDB from source if you want the very latest version (see Resources). Once the commands finish executing, you can check to see if CouchDB is running by issuing a ps -eaf command. Look for a few processes running with couchdb in their path by piping the ps output to egrep. You should see something along the lines of the output shown in Listing 1: Listing 1. CouchDB is running (lines broken to fit article page width) couchdb 1820 1 0 00:54 ? 00:00:00 /bin/sh -e /usr/bin/couchdb -c /etc/couchdb/couch.ini -b -r 5 -p /var/run/couchdb.pid -o / couchdb 1827 1820 0 00:54 ? 00:00:00 /bin/sh -e /usr/bin/couchdb -c /etc/couchdb/couch.ini -b -r 5 -p /var/run/couchdb.pid -o / couchdb 1828 1827 0 00:54 ? 00:00:00 /usr/lib/erlang/erts-5.6.5/bin/beam -Bd -- -root /usr/lib/erlang -progname erl -- -home /v couchdb 1836 1828 0 00:54 ? 00:00:00 heart -pid 1828 -ht 11 Next, back on your local machine, you'll set up an SSH tunnel that lets you access the CouchDB instance running on the cloud, as if it were residing on your own machine. To do so, open up a new terminal session on your local machine and type: ssh -i your key -L 5498:localhost:5984 root@your AMI DNS Finally, open up a browser on your local machine. In the location bar, type. You should see a nice welcome message in JSON, like this one: {"couchdb":"Welcome","version":"0.8.0-incubating"} Now that it appears things are working, you're ready to put CouchDB through its paces. Working RESTfully with Groovy's RESTClient Because CouchDB exposes data via a RESTful HTTP interface, working with CouchDB (as you've already seen via your browser) is quite easy. Pretty much everything you want to do can be done via HTTP. You can choose among plenty of tools for interacting with HTTP. When working with RESTful interfaces, one of my favorites is the RESTClient extension to Groovy's HTTPBuilder (see Resources). HTTPBuilder — a wrapper for the Apache Commons Project's popular HTTPClient — adds some slick Groovy-ness to the syntax of HTTP POSTs, GETs, PUTs, and DELETEs. Because HTTPBuilder is built with and leverages Groovy, writing scripts that leverage RESTful concepts (such as communicating with CouchDB) couldn't be easier. Grape makes easy even quicker In keeping with the general themes of Java development 2.0 — quick, easy, and free (or cheap) — Groovy's handy Grape (Groovy Advanced Packaging Engine or Groovy Adaptable Packaging Engine) feature is particularly relevant when it comes to interacting with a library like HTTPBuilder (see Resources). Grape is a dependency manager that allows Groovy scripts and classes to autoconfigure their particular dependencies at run tieme. This makes using various open source libraries a breeze, because you don't need to download a series of JAR files just to start coding. For example, with Grape, you can write a Groovy script to use HTTPBuilder without having HTTPBuilder's required JARs beforehand. With Grape, they'll be downloaded (via Apache Ivy) at run time (or compile time). You leverage Grape via annotations and method calls. You can, for example, decorate a method or class declaration with a @Grab annotation. In this annotation, you specify some relevant metadata regarding the main dependency. (Through the magic of Ivy, all transitive dependencies will be figured out too). At run time or compile time (whichever is first), Grape downloads these dependencies and ensures they're in your classpath. If the dependencies are already downloaded (from a previous run, for instance), Grape nevertheless still ensures the proper JAR files are in your classpath. RESTing easy on CouchDB with Groovy Before you can create any documents in CouchDB, you must create a database. To create a parking-tickets database, issue an HTTP PUT via HTTPBuilder's slick domain-specific language (DSL) using its RESTClient, as shown in Listing 2. (All the Groovy code for this article's examples is available for download.) Listing 2. Creating a CouchDB database import static groovyx.net.http.ContentType.JSON import groovyx.net.http.RESTClient @Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.0-RC2') def getRESTClient(){ return new RESTClient("") } def client = getRESTClient() def response = client.put(path: "parking_tickets", requestContentType: JSON, contentType: JSON) assert response.data.ok == true : "response from server wasn't ok" CouchCB should return the response {"ok":true}. As you can see in Listing 2, in HTTPBuilder it's simple to parse JSON and ensure that the ok element's value is indeed true. Next, it's time to create some documents in keeping with the parking-tickets theme. To model a parking ticket, remember that a number of aspects are associated with a ticket. Also keep in mind that because these are actual forms that officers complete, some fields might not be filled out or even follow a prescribed pattern — think intersection vs. exact location. Using HTTPBuilder, you can create a document in CouchDB via an HTTP PUT (just as I did in Listing 2 to create the database). Because CouchDB works with JSON documents, you must follow JSON's name-value format. You do this by creating a map-like data structure in Groovy (which HTTPBuilder will transform into valid JSON). Listing 3 shows how: Listing 3. Creating a CouchDB document via RESTClient response = client.put(path: "parking_tickets/1234334325", contentType: JSON, requestContentType: JSON, body: [officer: "Kristen Ree", location: "199 Baldwin Dr", vehicle_plate: "Maryland 77777", offense: "Parked in no parking zone", date: "2009/01/31"]) assert response.data.ok == true : "response from server wasn't ok" assert response.data.id == "1234334325" : "the returned ID didn't match" A few things are going on in Listing 3. First, when issuing a PUT for a CouchDB document, you must assign a UUID. CouchDB can assign these for you, or you can manage them yourself. In Listing 3, I've just made one up ( 1234334325); this UUID is consequently appended to the URL. If that UUID is available, CouchDB will assign the PUTed document to it. In the body aspect of my put call, note how each name has an associated value, almost like a normal map. For instance, the assigning officer's name is Kristen Ree, and the location of the ticket is 199 Baldwin Dr. Listing 4 creates another parking ticket in CouchDB via the same technique: Listing 4. Another parking ticket def id = new Date().time response = client.put(path: "parking_tickets/${id}", contentType: JSON, requestContentType: JSON, body: [officer: "Anthony Richards", location: "Walmart Parking lot", vehicle_plate: "Delaware 4433-OP", offense: "Parked in non-parking space", date: "2009/02/01"]) assert response.data.ok == true : "response from server wasn't ok" assert response.data.id == "${id}" : "the returned ID didn't match" Every time I issue a PUT via RESTClient, I assert that the JSON response contains a true value for ok, and I verify that my intended id value is present. Note how in Listing 4, rather than making up the UUID, I'm now using the current time — not a foolproof technique, but it'll suffice for simple interactions. When you successfully create a new document in CouchDB, it responds with JSON containing the UUID and a revision ID. For example, this response represents the JSON that I'm validating in Listing 4: {"ok":true,"id":"12339892938945","rev":"12351463"} Your id and rev values will undoubtedly be different. Note that I can grab the id value by issuing a call such as response.data.id. In CouchDB, documents are tracked via revisions, so you can go back to a previous document version (via the revision ID), much as you can in CVS or Subversion. Views in CouchDB Now that I've created a few parking tickets (or documents in CouchDB speak), it's time to create a view in CouchDB. Remember, views are just MapReduce functions in action; thus, you must define them. In many cases, you don't need the reduce function; the map function can handle most things for you. It does just what it sounds like. You can essentially map what "things" or aspects you'd like to filter or find, for example. I've defined two tickets: one issued by Officer Ree and another issued by Officer Richards. To find all the tickets issued by Officer Ree, for example, you write a map function that filters the officer property accordingly. You then pass the results to CouchDB's emit function. Using CouchDB's admin interface: Futon You can define views via CouchDB's RESTful API or via CouchDB's administrative interface, dubbed Futon. Futon is just a Web application available at. Go there now, and (assuming you've created the database and documents along with me) you should see a simple interface for the parking_tickets database, as shown in Figure 1: Figure 1. The Futon interface If you select the parking_tickets database, you can then see a drop-down list on the far right (dubbed Select view:). You start defining a custom view by selecting the Custom query..., as shown in Figure 2: Figure 2. Futon's view-selection interface Now Futon presents an interface that allows you to define both a map function and a reduce function. (You might need to click the View code link). In the Map text box, define the simple map function shown in Listing 5: Listing 5. A simple map function in CouchDB function(doc) { if(doc.officer == "Kristen Ree"){ emit(null, doc); } } As you can see, the map function in Listing 5 is defined in JavaScript. All it does is filter the documents in the CouchDB database by a document's officer property. Specifically, the function passes a document to the emit only if the officer's name is Kristen Ree. Figure 3 shows where I've defined this function in Futon: Figure 3. Creating a MapReduce function Next, you're asked to provide a design document name (enter by_name) and a view name (enter officer_ree). These names will serve as a means to build a URL for invoking this view later (that is,). You can now use this view via HTTPBuilder, as shown in Listing 6: Listing 6. Invoking your new view response = client.get(path: "parking_tickets/_view/by_name/officer_ree", contentType: JSON, requestContentType: JSON) assert response.data.total_rows == 1 response.data.rows.each{ assert it.value.officer == "Kristen Ree" } This view correctly returns a JSON response containing only one document: the ticket issued by Officer Ree on January 31. The response object in Listing 6 hides the raw HTTP response by parsing the JSON accordingly. You can view the raw JSON response by calling the toString method on the data property of the response object. The raw response looks like Listing 7: Listing 7. The view's raw result {"total_rows":1,"offset":0,"rows":[ {"id":"1234334325","key":null, "value":{"_id":"1234334325","_rev":"4205717256","officer":"Kristen Ree", "location":"199 Baldwin Dr","vehicle_plate":"Maryland 77777", "offense":"Parked in no parking zone","date":"2009/01/31"}}]} As you can see from the raw JSON document returned, HTTPBuilder's ability to parse JSON effortlessly is quite handy, because it enables an object graph-like mechanism for assessing various attributes and their corresponding values. For demonstration purposes, I'll add some more documents to the database. In order to keep working through the examples, you should do the same using the code download. CouchDB's emit function works as an organizer of sorts. If you don't put a restriction in your map function (as I did in Listing 5), then the emit will essentially sort the passed-in documents. For example, if you want to obtain all tickets by date (think SQL's ORDER BY clause here) you can just emit by the document's date fields, as shown in Listing 8: Listing 8. A simpler map function function(doc) { emit(doc.date, doc); } Listing 9 issues an HTTP GET against this view (which I've given a design document name of dates and a view name of by_date). Listing 9. Another view invoked response = client.get(path: "parking_tickets/_view/dates/by_date", contentType: JSON, requestContentType: JSON) assert response.data.total_rows == 4 The query in Listing 9 returns all the documents in the parking_tickets database sorted by date. The assert statement simply verifies that the total_rows property is equal to 4. This is a key point. Views return results as well as a bit of metadata (such as the number of returned documents); thus, it helps to see the raw response before you start parsing away. Listing 10 shows the raw results: Listing 10. Raw JSON documents sorted by date {"total_rows":4,"offset":0,"rows":[ {"id":"85d4dbf45747e45406e5695b4b5796fe","key":"2009/01/30", "value": {"_id":"85d4dbf45747e45406e5695b4b5796fe","_rev":"1318766781", "officer":"Anthony Richards", "location":"54th and Main","vehicle_plate":"Virginia FCD-4444", "offense":"Parked in no parking zone","date":"2009/01/30"}}, { no parking zone","date":"2009/01/31"}}, {"id":"12339892938945","key":"2009/02/01", "value": {"_id":"12339892938945","_rev":"12351463","officer":"Anthony Richards", "location":"Walmart Parking lot","vehicle_plate":"Maine 4433-OP", "offense":"Parked in non-parking space", "date":"2009/02/01"}}]} What's interesting about defining views like this is that you can then pass in a key— that is, what you'd like the emit function's first value essentially to represent. For example, the view defined in Listing 8 essentially sorts by date. If you'd like to sort it by a specifeic date, then pass that date into the view query. For instance, just for fun, enter this URL in your browser's location box:"2009/01/31" This view then returns only the tickets issued on January 31. You should see a bunch of JSON-looking text in your browser window similar to what you can see in Listing 11. Notice that using your browser as your query tool is an especially easy way to view the raw JSON response of an HTTP request. Listing 11. Only two tickets issued on January 31 {"total_rows":4,"offset":1,"rows":[ { handicap zone without permit", "date":"2009/01/31"}}]} Views can be as specific as you'd like. For instance, with a little JavaScript string manipulation, I can write one that finds tickets issued anywhere on Main Street, as shown in Listing 12: Listing 12. Another view with some string magic function(doc) { if(doc.location.toLowerCase().indexOf('main') > 0){ emit(doc.location, doc); } } As you can see from Listing 12, if the location element of any document contains main, then the document is passed to the emit function. Keep in mind that this search is rather wide. If a document's location contains a string such as Germaine Street, it'll be returned too. For the small population of tickets I've defined, the view would return the results shown in Listing 13: Listing 13. Results filtered by Main Street {"total_rows":2,"offset":0,"rows":[ {"id":"123433432asdefasdf4325","key":"4th and Main", "value": {"_id":"123433432asdefasdf4325","_rev":"498239926", "officer":"Chris Smith","location":"4th and Main", "vehicle_plate":"VA FGA-JD33", "offense":"Parked in no parking zone","date":"2009/02/01"}}, {"id":"123433432223e432325","key":"54 and Main", "value": {"_id":"123433432223e432325","_rev":"841089995", "officer":"Kristen Ree","location":"54 and Main Street", "vehicle_plate":"Maryland 77777", "offense":"Parked in no parking zone","date":"2009/02/02"}}]} Note that the JSON response contains a key element, which describes why a particular document was emitted. This level of information is quite helpful. Also note how all along, the data found in the various tickets I've defined is somewhat inconsistent: some locations are precise, others aren't. Although this data could be stored in a relational database, it fits well with the documented-oriented model too, don't you think? Plus, with the power of Groovy and HTTPBuilder's ability to parse JSON effortlessly, it's quite easy to get at the data (much easier than with raw JDBC). CouchDB as the database for the Web CouchDB is especially interesting because it's so easy to get going with it. Relational databases are easy too, but what's nice about this database is how you can embrace its API if you already have some familiarity with, say, using a Web browser. What's more, because of CouchDB's RESTful API, you can communicate with it via cool frameworks like HTTPBuilder's RESTClient. You aren't limited to HTTPBuilder either; a number of Java libraries try to make working with CouchDB easier. One that is especially promising is jcouchdb (see Resources), which shields you from the RESTful-ness and JSON-ness of it all and allows you to work programmatically in the Java language with documents and views. Stay tuned for next month's column, where I'll return to Google App Engine. True to the spirit of open innovation, new frameworks are popping up that facilitate Google App Engine development and deployment. You'll see how one of them makes Java development 2.0 on Google's cloud platform even easier. Download Resources Learn - CouchDB: Visit the Apache CouchDB site. - MapReduce: This Wikipedia article explains the MapReduce programming model for processing large data sets. - "CouchDB basics for PHP developers" (Thomas Myer, IBM developerWorks, March 2010): PHP and CouchDB are a great match too. This article will get you started. - "Java development 2.0: You can borrow EC2 too" (Andrew Glover, developerWorks, September 2009): Get a hands-on introduction to developing for and deploying on the Amazon Elastic Compute Cloud (EC2). - "Build a RESTful Web service" (Andrew Glover, developerWorks, July 2008): This tutorial guides you step-by-step through the fundamental concepts of REST and building applications with Restlets. - "Crossing borders: Concurrent programming with Erlang" (Bruce Tate, developerWorks, April 2006): Erlang is getting some good press in the areas of concurrency, distributed systems, and soft real-time systems. - jcouchdb: Keep tabs on the jcouchdb project. - Browse the technology bookstore for books on these and other technical topics. - developerWorks Java technology zone: Find hundreds of articles about every aspect of Java programming. Get products and technologies - AWS Toolkit for Eclipse: Download the Eclipse plug-in for EC2. - Groovy: Download Groovy today. - CouchDB: Download the latest CouchDB version. Discuss - CouchDB mailing lists: Subscribe to the CouchDB support or development lists, or view the archives. -.
http://www.ibm.com/developerworks/library/j-javadev2-5/
CC-MAIN-2016-36
refinedweb
4,305
63.39
This is the mail archive of the libstdc++@gcc.gnu.org mailing list for the libstdc++ project. On Tue, Feb 25, 2003 at 01:42:49AM -0500, Phil Edwards wrote: > The question is whether member > #1 should additionally appear in the documentation for Derived. I'm changing this to 'on' for now. Also, more and better documentation, concentrating on man pages. 2003-02-25 Phil Edwards <pme at gcc dot gnu dot org> * docs/doxygen/Intro.3: Update with new (proper) names. * docs/doxygen/TODO: Update. * docs/doxygen/run_doxygen: More comments, fix up man pages. Fake entries for standard typedefs. * docs/doxygen/user.cfg.in: Turn INLINE_INHERITED_MEMB back on. * docs/html/documentation.html: Top-level man page is now called C++Intro. * include/std/std_limits.h: Doxygenate. Index: docs/doxygen/Intro.3 =================================================================== RCS file: /cvs/gcc/gcc/libstdc++-v3/docs/doxygen/Intro.3,v retrieving revision 1.7 diff -u -3 -p -r1.7 Intro.3 --- docs/doxygen/Intro.3 27 Mar 2002 21:41:28 -0000 1.7 +++ docs/doxygen/Intro.3 25 Feb 2003 23:58:45 -0000 @@ -1,8 +1,8 @@ .\" t .\" This man page is released under the FDL as part of libstdc++-v3. -.TH Intro 3 "27 March 2002" "GNU libstdc++-v3" "Standard C++ Library" +.TH C++Intro 3 "25 Febuary 2003" "GNU libstdc++-v3" "Standard C++ Library" .SH NAME -Intro \- Introduction to the GNU libstdc++-v3 man pages +C++Intro \- Introduction to the GNU libstdc++-v3 man pages .SH DESCRIPTION This man page serves as a brief introduction to the GNU implementation of the Standard C++ Library. For a better introduction and more complete @@ -12,10 +12,10 @@ homepage listed at the end. .P All standard library entities are declared within .I namespace std -and have manual entries beginning with "std_". For example, to see +and have manual entries beginning with "std::". For example, to see documentation of the template class .I std::vector -one would use "man std_vector". Some entities do not have a separate man +one would use "man std::vector". Some entities do not have a separate man page; for those see the main listing in "man Namespace_Std". .P All the man pages are automatically generated by Doxygen. For more @@ -37,7 +37,7 @@ Binder_functors Functors which "remember Comparison_functors Functors wrapping built-in comparisons. Containers An introduction to container classes. Func_ptr_functors Functors for use with pointers to functions. -Intro This page. +C++Intro This page. Intro_functors An introduction to function objects, or functors. Iterator_types Programatically distinguishing iterators/pointers. Logical_functors Functors wrapping the Boolean operations. @@ -112,10 +112,9 @@ need to know about it, but it can be use .TP .I libstdc++.so[.N] The library implementation in shared object form. This will be used in -preference to the static archive form by default. Currently N will either -start with 3 or with 4, but your system vendor may change the name as they -see fit. If N is in the 2.x series, then you are looking at the old -libstdc++-v2 library, which we do not maintain. +preference to the static archive form by default. N will be a number equal +to or greater than 3. If N is in the 2.x series, then you are looking at +the old libstdc++-v2 library, which we do not maintain. .TP .I libstdc++.la .TP Index: docs/doxygen/TODO =================================================================== RCS file: /cvs/gcc/gcc/libstdc++-v3/docs/doxygen/TODO,v retrieving revision 1.10 diff -u -3 -p -r1.10 TODO --- docs/doxygen/TODO 21 Nov 2002 07:06:40 -0000 1.10 +++ docs/doxygen/TODO 25 Feb 2003 23:58:45 -0000 @@ -19,11 +19,12 @@ entity to the generated TODO page. ----------------------------------------------------------- c17 FINISHED (Nothing in Clause 17 "exists" in terms of code.) -c18 <limits>, Note A +c18 FINISHED, Note A c19 Note A c20 Note A -c21 Untouched, Note B -c22 Untouched +c21 Untouched (top-level class note for basic_string done), + Note B +c22 Untouched; see docs/html/22_locale/* c23 See doxygroups.cc and Note B. Notes on what invalidates iterators need to be added. std::list-specific memfns need to be filled out. Index: docs/doxygen/run_doxygen =================================================================== RCS file: /cvs/gcc/gcc/libstdc++-v3/docs/doxygen/run_doxygen,v retrieving revision 1.19 diff -u -3 -p -r1.19 run_doxygen --- docs/doxygen/run_doxygen 21 Nov 2002 08:16:32 -0000 1.19 +++ docs/doxygen/run_doxygen 25 Feb 2003 23:58:45 -0000 @@ -1,7 +1,7 @@ #!/bin/sh # Runs doxygen and massages the output files. -# Copyright (C) 2001, 2002 Free Software Foundation, Inc. +# Copyright (C) 2001, 2002, 2003 Free Software Foundation, Inc. # # Synopsis: run_doxygen --mode=[user|maint|man] v3srcdir v3builddir # @@ -154,6 +154,11 @@ test $do_html = yes && { -e "s= at DATE@=${DATEtext}=" \ ${srcdir}/docs/doxygen/mainpage.html > ${outdir}/html_${mode}/index.html cd ${outdir}/html_${mode} + # The following bit of line noise changes annoying + # std::foo < typename _Ugly1, typename _Ugly2, .... _DefaultUgly17 > + # to user-friendly + # std::foo + # in the major "Compound List" page. sed -e 's=\(::[[:alnum:]_]*\)< .* >=\1=' annotated.html > annstrip.html mv annstrip.html annotated.html cp ${srcdir}/docs/doxygen/tables.html tables.html @@ -231,7 +236,40 @@ a\ mv TEMP $f done -cp ${srcdir}/docs/doxygen/Intro.3 . +# Also, break this (generated) line up. It's ugly as sin. +problematic=`grep -l '[^^]Definition at line' *.3` +for f in $problematic; do + sed 's/Definition at line/\ +.PP\ +&/' $f > TEMP + mv TEMP $f +done + +cp ${srcdir}/docs/doxygen/Intro.3 C++Intro.3 + +# Why didn't I do this at the start? Were rabid weasels eating my brain? +# Who the fsck would "man std_vector" when the class isn't named that? +for f in std_*; do + newname=`echo $f | sed 's/^std_/std::/'` + mv $f $newname +done +for f in __gnu_cxx_*; do + newname=`echo $f | sed 's/^__gnu_cxx_/__gnu_cxx::/'` + mv $f $newname +done +for f in *__policy_*; do + newname=`echo $f | sed 's/__policy_/__policy::/'` + mv $f $newname +done + +# Also, for some reason, typedefs don't get their own man pages. Sigh. +for f in ios streambuf istream ostream iostream stringbuf \ + istringstream ostringstream stringstream filebuf ifstream \ + ofstream fstream string; +do + echo ".so man3/std::basic_${f}.3" > std::${f}.3 + echo ".so man3/std::basic_${f}.3" > std::w${f}.3 +done echo :: echo :: Man pages in ${outdir}/man @@ -243,4 +281,3 @@ echo :: exit 0 # vim:ts=4:et: - Index: docs/doxygen/user.cfg.in =================================================================== RCS file: /cvs/gcc/gcc/libstdc++-v3/docs/doxygen/user.cfg.in,v retrieving revision 1.22 diff -u -3 -p -r1.22 user.cfg.in --- docs/doxygen/user.cfg.in 12 Jan 2003 02:56:49 -0000 1.22 +++ docs/doxygen/user.cfg.in 25 Feb 2003 23:58:46 -0000 @@ -127,7 +127,7 @@ ALWAYS_DETAILED_SEC = YES # ordinary class members. Constructors, destructors and assignment operators of # the base classes will not be shown. -INLINE_INHERITED_MEMB = NO +INLINE_INHERITED_MEMB = YES # pedwards -- this is useful, but ch27 gets huge # If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full Index: docs/html/documentation.html =================================================================== RCS file: /cvs/gcc/gcc/libstdc++-v3/docs/html/documentation.html,v retrieving revision 1.28 diff -u -3 -p -r1.28 documentation.html --- docs/html/documentation.html 4 Feb 2003 17:42:19 -0000 1.28 +++ docs/html/documentation.html 25 Feb 2003 23:58:46 -0000 @@ -84,9 +84,8 @@ libstdc++-html-*/index.html into a browser. Feedback (and additional documentation!) is welcome. </p> -<p> - In addition, an initial set of man pages are also available in the - same place as the HTML collections. Start with Intro(3). +<p>In addition, an initial set of man pages are also available in the + same place as the HTML collections. Start with C++Intro(3). </p> Index: include/std/std_limits.h =================================================================== RCS file: /cvs/gcc/gcc/libstdc++-v3/include/std/std_limits.h,v retrieving revision 1.21 diff -u -3 -p -r1.21 std_limits.h --- include/std/std_limits.h 30 Jan 2003 07:24:02 -0000 1.21 +++ include/std/std_limits.h 25 Feb 2003 23:58:46 -0000 @@ -149,66 +149,162 @@ namespace std { + /** + * @brief Describes the rounding style for floating-point types. + * + * This is used in the std::numeric_limits class. + */ enum float_round_style { - round_indeterminate = -1, - round_toward_zero = 0, - round_to_nearest = 1, - round_toward_infinity = 2, - round_toward_neg_infinity = 3 + round_indeterminate = -1, ///< Self-explanatory. + round_toward_zero = 0, ///< Self-explanatory. + round_to_nearest = 1, ///< To the nearest representable value. + round_toward_infinity = 2, ///< Self-explanatory. + round_toward_neg_infinity = 3 ///< Self-explanatory. }; + /** + * @brief Describes the denormalization for floating-point types. + * + * These values represent the presence or absence of a variable number + * of exponent bits. This type is used in the std::numeric_limits class. + */ enum float_denorm_style { + /// Indeterminate at compile time whether denormalized values are allowed. denorm_indeterminate = -1, + /// The type does not allow denormalized values. denorm_absent = 0, + /// The type allows denormalized values. denorm_present = 1 }; - // - // The primary class traits - // + /** + * @brief Part of std::numeric_limits. + * + * The @c static @c const members are usable as integral constant + * expressions. + * + * @note This is a seperate class for purposes of efficiency; you + * should only access these members as part of an instantiation + * of the std::numeric_limits class. + */ struct __numeric_limits_base { + /** This will be true for all fundamental types (which have + specializations), and false for everything else. */ static const bool is_specialized = false; + /** The number of @c radix digits that be represented without change: for + integer types, the number of non-sign bits in the mantissa; for + floating types, the number of @c radix digits in the mantissa. */ static const int digits = 0; + /** The number of base 10 digits that can be represented without change. */ static const int digits10 = 0; + /** True if the type is signed. */ static const bool is_signed = false; + /** True if the type is integer. + * @if maint + * Is this supposed to be "if the type is integral"? + * @endif + */ static const bool is_integer = false; + /** True if the type uses an exact representation. "All integer types are + exact, but not all exact types are integer. For example, rational and + fixed-exponent representations are exact but not integer." + [18.2.1.2]/15 */ static const bool is_exact = false; + /** For integer types, specifies the base of the representation. For + floating types, specifies the base of the exponent representation. */ static const int radix = 0; + /** The minimum negative integer such that @c radix raised to the power of + (one less than that integer) is a normalized floating point number. */ static const int min_exponent = 0; + /** The minimum negative integer such that 10 raised to that power is in + the range of normalized floating point numbers. */ static const int min_exponent10 = 0; + /** The maximum positive integer such that @c radix raised to the power of + (one less than that integer) is a representable finite floating point + number. */ static const int max_exponent = 0; + /** The maximum positive integer such that 10 raised to that power is in + the range of representable finite floating point numbers. */ static const int max_exponent10 = 0; + /** True if the type has a representation for positive infinity. */ static const bool has_infinity = false; + /** True if the type has a representation for a quiet (non-signaling) + "Not a Number." */ static const bool has_quiet_NaN = false; + /** True if the type has a representation for a signaling + "Not a Number." */ static const bool has_signaling_NaN = false; + /** See std::float_denorm_style for more information. */ static const float_denorm_style has_denorm = denorm_absent; + /** "True if loss of accuracy is detected as a denormalization loss, + rather than as an inexact result." [18.2.1.2]/42 */ static const bool has_denorm_loss = false; + /** True if-and-only-if the type adheres to the IEC 559 standard, also + known as IEEE 754. (Only makes sense for floating point types.) */ static const bool is_iec559 = false; + /** "True if the set of values representable by the type is finite. All + built-in types are bounded, this member would be false for arbitrary + precision types." [18.2.1.2]/54 */ static const bool is_bounded = false; + /** True if the type is @e modulo, that is, if it is possible to add two + positive numbers and have a result that wraps around to a third number + that is less. Typically false for floating types, true for unsigned + integers, and true for signed integers. */ static const bool is_modulo = false; + /** True if trapping is implemented for this type. */ static const bool traps = false; + /** True if tinyness is detected before rounding. (see IEC 559) */ static const bool tinyness_before = false; + /** See std::float_round_style for more information. This is only + meaningful for floating types; integer types will all be + round_toward_zero. */ static const float_round_style round_style = round_toward_zero; }; + /** + * @brief Properties of fundamental types. + * + * This class allows a program to obtain information about the + * representation of a fundamental type on a given platform. For + * non-fundamental types, the functions will return 0 and the data + * members will all be @c false. + * + * @if maint + * _GLIBCPP_RESOLVE_LIB_DEFECTS: DRs 201 and 184 (hi Gaby!) are + * noted, but not incorporated in this documented (yet). + * @endif + */ template<typename _Tp> struct numeric_limits : public __numeric_limits_base { + /** The minimum finite value, or for floating types with + denormalization, the minimum positive normalized value. */ static _Tp min() throw() { return static_cast<_Tp>(0); } + /** The maximum finite value. */ static _Tp max() throw() { return static_cast<_Tp>(0); } + /** The @e machine @e epsilon: the difference between 1 and the least + value greater than 1 that is representable. */ static _Tp epsilon() throw() { return static_cast<_Tp>(0); } + /** The maximum rounding error measurement (see LIA-1). */ static _Tp round_error() throw() { return static_cast<_Tp>(0); } + /** The representation of positive infinity, if @c has_infinity. */ static _Tp infinity() throw() { return static_cast<_Tp>(0); } + /** The representation of a quiet "Not a Number," if @c has_quiet_NaN. */ static _Tp quiet_NaN() throw() { return static_cast<_Tp>(0); } + /** The representation of a signaling "Not a Number," if + @c has_signaling_NaN. */ static _Tp signaling_NaN() throw() { return static_cast<_Tp>(0); } + /** The minimum positive denormalized value. For types where + @c has_denorm is false, this is the minimum positive normalized + value. */ static _Tp denorm_min() throw() { return static_cast<_Tp>(0); } };
http://gcc.gnu.org/ml/libstdc++/2003-02/msg00389.html
crawl-001
refinedweb
2,276
51.24
Kernel initialization. Part 2. Early interrupt and exception handling In the previous part we stopped before setting of early interrupt handlers. At this moment we are in the decompressed Linux kernel, we have basic paging structure for early boot and our current goal is to finish early preparation before the main kernel code will start to work. We already started to do this preparation in the previous first part of this chapter. We continue in this part and will know more about interrupt and exception handling. Remember that we stopped before following function: idt_setup_early_handler(); from the arch/x86/kernel/head64.c source code file. But before we start to sort out this function, we need to know about interrupts and handlers. Some theory An interrupt is an event caused by software or hardware to the CPU. For example a user have pressed a key on keyboard. On interrupt, CPU stops the current task and transfer control to the special routine which is called - interrupt handler. An interrupt handler handles and interrupt and transfer control back to the previously stopped task. We can split interrupts on three types: - Software interrupts - when a software signals CPU that it needs kernel attention. These interrupts are generally used for system calls; - Hardware interrupts - when a hardware event happens, for example button is pressed on a keyboard; - Exceptions - interrupts generated by CPU, when the CPU detects error, for example division by zero or accessing a memory page which is not in RAM. Every interrupt and exception is assigned a unique number which is called - vector number. Vector number can be any number from 0 to 255. There is common practice to use first 32 vector numbers for exceptions, and vector numbers from 32 to 255 are used for user-defined interrupts. CPU uses vector number as an index in the Interrupt Descriptor Table (we will see description of it soon). CPU catches interrupts from the APIC or through its pins. Following table shows 0-31 exceptions: ---------------------------------------------------------------------------------------------- |Vector|Mnemonic|Description |Type |Error Code|Source | ---------------------------------------------------------------------------------------------- |0 | #DE |Divide Error |Fault|NO |DIV and IDIV | |--------------------------------------------------------------------------------------------- |1 | #DB |Reserved |F/T |NO | | |--------------------------------------------------------------------------------------------- |2 | --- |NMI |INT |NO |external NMI | |--------------------------------------------------------------------------------------------- |3 | #BP |Breakpoint |Trap |NO |INT 3 | |--------------------------------------------------------------------------------------------- |4 | #OF |Overflow |Trap |NO |INTO instruction | |--------------------------------------------------------------------------------------------- |5 | #BR |Bound Range Exceeded|Fault|NO |BOUND instruction | |--------------------------------------------------------------------------------------------- |6 | #UD |Invalid Opcode |Fault|NO |UD2 instruction | |--------------------------------------------------------------------------------------------- |7 | #NM |Device Not Available|Fault|NO |Floating point or [F]WAIT | |--------------------------------------------------------------------------------------------- |8 | #DF |Double Fault |Abort|YES |An instruction which can generate NMI | |--------------------------------------------------------------------------------------------- |9 | --- |Reserved |Fault|NO | | |--------------------------------------------------------------------------------------------- |10 | #TS |Invalid TSS |Fault|YES |Task switch or TSS access | |--------------------------------------------------------------------------------------------- |11 | #NP |Segment Not Present |Fault|NO |Accessing segment register | |--------------------------------------------------------------------------------------------- |12 | #SS |Stack-Segment Fault |Fault|YES |Stack operations | |--------------------------------------------------------------------------------------------- |13 | #GP |General Protection |Fault|YES |Memory reference | |--------------------------------------------------------------------------------------------- |14 | #PF |Page fault |Fault|YES |Memory reference | |--------------------------------------------------------------------------------------------- |15 | --- |Reserved | |NO | | |--------------------------------------------------------------------------------------------- |16 | #MF |x87 FPU fp error |Fault|NO |Floating point or [F]Wait | |--------------------------------------------------------------------------------------------- |17 | #AC |Alignment Check |Fault|YES |Data reference | |--------------------------------------------------------------------------------------------- |18 | #MC |Machine Check |Abort|NO | | |--------------------------------------------------------------------------------------------- |19 | #XM |SIMD fp exception |Fault|NO |SSE[2,3] instructions | |--------------------------------------------------------------------------------------------- |20 | #VE |Virtualization exc. |Fault|NO |EPT violations | |--------------------------------------------------------------------------------------------- |21-31 | --- |Reserved |INT |NO |External interrupts | ---------------------------------------------------------------------------------------------- To react on interrupt CPU uses special structure - Interrupt Descriptor Table or IDT. IDT is an array of 8-byte descriptors like Global Descriptor Table, but IDT entries are called gates. CPU multiplies vector number by 8 to find the IDT entry. But in 64-bit mode IDT is an array of 16-byte descriptors and CPU multiplies vector number by 16 to find the entry in the IDT. We remember from the previous part that CPU uses special GDTR register to locate Global Descriptor Table, so CPU uses special register IDTR for Interrupt Descriptor Table and lidt instruction for loading base address of the table into this register. 64-bit mode IDT entry has following structure: 127 96 -------------------------------------------------------------------------------- | | | Reserved | | | -------------------------------------------------------------------------------- 95 64 -------------------------------------------------------------------------------- | | | Offset 63..32 | | | -------------------------------------------------------------------------------- 63 48 47 46 44 42 39 34 32 -------------------------------------------------------------------------------- | | | D | | | | | | | | Offset 31..16 | P | P | 0 |Type |0 0 0 | 0 | 0 | IST | | | | L | | | | | | | -------------------------------------------------------------------------------- 31 16 15 0 -------------------------------------------------------------------------------- | | | | Segment Selector | Offset 15..0 | | | | -------------------------------------------------------------------------------- Where: Offset- is offset to entry point of an interrupt handler; DPL- Descriptor Privilege Level; P- Segment Present flag; Segment selector- a code segment selector in GDT or LDT IST- provides ability to switch to a new stack for interrupts handling. And the last Type field describes type of the IDT entry. There are three different kinds of gates for interrupts: - Task gate - Interrupt gate - Trap gate Interrupt and trap gates contain a far pointer to the entry point of the interrupt handler. Only one difference between these types is how CPU handles IF flag. If interrupt handler was accessed through interrupt gate, CPU clear the IF flag to prevent other interrupts while current interrupt handler executes. After that current interrupt handler executes, CPU sets the IF flag again with iret instruction. Other bits in the interrupt descriptor is reserved and must be 0. Now let's look how CPU handles interrupts: - CPU save flags register, CS, and instruction pointer on the stack. - If interrupt causes an error code (like #PFfor example), CPU saves an error on the stack after instruction pointer; - After interrupt handler executes, iretinstruction will be used to return from it. Now let's back to code. Fill and load IDT We stopped at the following function: idt_setup_early_handler(); idt_setup_early_handler is defined in the arch/x86/kernel/idt.c like the following: void __init idt_setup_early_handler(void) { int i; for (i = 0; i < NUM_EXCEPTION_VECTORS; i++) set_intr_gate(i, early_idt_handler_array[i]); load_idt(&idt_descr); } where NUM_EXCEPTION_VECTORS expands to 32. As we can see, We're filling only first 32 IDT entries in the loop, because all of the early setup runs with interrupts disabled, so there is no need to set up interrupt handlers for vectors greater than 32. Here we call set_intr_gate in the loop, which takes two parameters: - Number of an interrupt or vector number; - Address of the idt handler. and inserts an interrupt gate to the IDT table which is represented by the &idt_descr array. The early_idt_handler_array array is declaredd in the arch/x86/include/asm/segment.h header file and contains addresses of the first 32 exception handlers: extern const char early_idt_handler_array[NUM_EXCEPTION_VECTORS][EARLY_IDT_HANDLER_SIZE]; The early_idt_handler_array is 288 bytes array which contains address of exception entry points every nine bytes. Every nine bytes of this array consist of two bytes optional instruction for pushing dummy error code if an exception does not provide it, two bytes instruction for pushing vector number to the stack and five bytes of jump to the common exception handler code. You will see more detail in the next paragraph. The set_intr_gate function is defined in the arch/x86/kernel/idt.c source file and looks: static void set_intr_gate(unsigned int n, const void *addr) { struct idt_data data; BUG_ON(n > 0xFF); memset(&data, 0, sizeof(data)); data.vector = n; data.addr = addr; data.segment = __KERNEL_CS; data.bits.type = GATE_INTERRUPT; data.bits.p = 1; idt_setup_from_table(idt_table, &data, 1, false); } First of all it checks that passed vector number is not greater than 255 with BUG_ON macro. We need to do this because we are limited to have up to 256 interrupts. After this, we fill the idt data with the given arguments and others, which will be passed to idt_setup_from_table. The idt_setup_from_table function is defined in the same file as the set_intr_gate function like the following: static void idt_setup_from_table(gate_desc *idt, const struct idt_data *t, int size, bool sys) { gate_desc desc; for (; size > 0; t++, size--) { desc.offset_low = (u16) t->addr; desc.segment = (u16) t->segment desc.bits = t->bits; desc.offset_middle = (u16) (t->addr >> 16); desc.offset_high = (u32) (t->addr >> 32); desc.reserved = 0; memcpy(&idt[t->vector], &desc, sizeof(desc)); if (sys) set_bit(t->vector, system_vectors); } } which fill temporary idt descriptor with the given arguments and others. And then we just copy it to the certain element of the idt_table array. idt_table is an array of idt entries: gate_desc idt_table[IDT_ENTRIES] __page_aligned_bss; Now we are moving back to main loop code. After main loop finishes, we can load Interrupt Descriptor table with the call of the: load_idt((const struct desc_ptr *)&idt_descr); where idt_descr is: struct desc_ptr idt_descr __ro_after_init = { .size = (IDT_ENTRIES * 2 * sizeof(unsigned long)) - 1, .address = (unsigned long) idt_table, }; and load_idt just executes lidt instruction: asm volatile("lidt %0"::"m" (idt_descr)); Okay, now we have filled and loaded Interrupt Descriptor Table, we know how the CPU acts during an interrupt. So now time to deal with interrupts handlers. Early interrupts handlers As you can read above, we filled IDT with the address of the early_idt_handler_array. In this section, we are going to look into it in detail. We can find it in the arch/x86/kernel/head_64.S assembly file: ENTRY(early_idt_handler_array) i = 0 .rept NUM_EXCEPTION_VECTORS .if ((EXCEPTION_ERRCODE_MASK >> i) & 1) == 0 UNWIND_HINT_IRET_REGS pushq $0 # Dummy error code, to make stack frame uniform .else UNWIND_HINT_IRET_REGS offset=8 .endif pushq $i # 72(%rsp) Vector number jmp early_idt_handler_common UNWIND_HINT_IRET_REGS i = i + 1 .fill early_idt_handler_array + i*EARLY_IDT_HANDLER_SIZE - ., 1, 0xcc .endr UNWIND_HINT_IRET_REGS offset=16 END(early_idt_handler_array) We can see here, interrupt handlers generation for the first 32 exceptions. We check here, if exception has an error code then we do nothing, if exception does not return error code, we push zero to the stack. We do it for that stack was uniform. After that we push vector number on the stack and jump on the early_idt_handler_common which is generic interrupt handler for now. After all, every nine bytes of the early_idt_handler_array array consists of optional push of an error code, push of vector number and jump instruction to early_idt_handler_common. We can see it in the output of the objdump util: $ objdump -D vmlinux ... ... ... ffffffff81fe5000 <early_idt_handler_array>: ffffffff81fe5000: 6a 00 pushq $0x0 ffffffff81fe5002: 6a 00 pushq $0x0 ffffffff81fe5004: e9 17 01 00 00 jmpq ffffffff81fe5120 <early_idt_handler_common> ffffffff81fe5009: 6a 00 pushq $0x0 ffffffff81fe500b: 6a 01 pushq $0x1 ffffffff81fe500d: e9 0e 01 00 00 jmpq ffffffff81fe5120 <early_idt_handler_common> ffffffff81fe5012: 6a 00 pushq $0x0 ffffffff81fe5014: 6a 02 pushq $0x2 ... ... ... As we may know, CPU pushes flag register, CS and RIP on the stack before calling interrupt handler. So before early_idt_handler_common will be executed, stack will contain following data: |--------------------| | %rflags | | %cs | | %rip | | error code | <-- %rsp |--------------------| Now let's look on the early_idt_handler_common implementation. It locates in the same arch/x86/kernel/head_64.S assembly file. First of all we increment early_recursion_flag to prevent recursion in the early_idt_handler_common: incl early_recursion_flag(%rip) Next we save general registers on the stack: pushq %rsi movq 8(%rsp), %rsi movq %rdi, 8(%rsp) pushq %rdx pushq %rcx pushq %rax pushq %r8 pushq %r9 pushq %r10 pushq %r11 pushq %rbx pushq %rbp pushq %r12 pushq %r13 pushq %r14 pushq %r15 UNWIND_HINT_REGS We need to do it to prevent wrong values of registers when we return from the interrupt handler. After this we check the vector number, and if it is #PF or Page Fault, we put value from the cr2 to the rdi register and call early_make_pgtable (we'll see it soon): cmpq $14,%rsi jnz 10f GET_CR2_INTO(%rdi) call early_make_pgtable andl %eax,%eax jz 20f otherwise we call early_fixup_exception function by passing kernel stack pointer: 10: movq %rsp,%rdi call early_fixup_exception We'll see the implementaion of the early_fixup_exception function later. 20: decl early_recursion_flag(%rip) jmp restore_regs_and_return_to_kernel After we decrement the early_recursion_flag, we restore registers which we saved before from the stack and return from the handler with iretq. It is the end of the interrupt handler. We will examine the page fault handling and the other exception handling in order. Page fault handling In the previous paragraph we saw the early interrupt handler which checks if the vector number is page fault and calls early_make_pgtable for building new page tables if it is. We need to have #PF handler in this step because there are plans to add ability to load kernel above 4G and make access to boot_params structure above the 4G. You can find the implementation of early_make_pgtable in arch/x86/kernel/head64.c and takes one parameter - the value of cr2 register, which contains the address caused page fault. Let's look on it: int __init early_make_pgtable(unsigned long address) { unsigned long physaddr = address - __PAGE_OFFSET; pmdval_t pmd; pmd = (physaddr & PMD_MASK) + early_pmd_flags; return __early_make_pgtable(address, pmd); } We initialize pmd and pass it to the __early_make_pgtable function along with address. The __early_make_pgtable function is defined in the same file as the early_make_pgtable function as the following: int __init __early_make_pgtable(unsigned long address, pmdval_t pmd) { unsigned long physaddr = address - __PAGE_OFFSET; pgdval_t pgd, *pgd_p; p4dval_t p4d, *p4d_p; pudval_t pud, *pud_p; pmdval_t *pmd_p; ... ... ... } It starts from the definition of some variables which have *val_t types. All of these types are declared as alias of unsigned long using typedef. After we made the check that we have no invalid address, we're getting the address of the Page Global Directory entry which contains base address of Page Upper Directory and put its value to the pgd variable: again: pgd_p = &early_top_pgt[pgd_index(address)].pgd; pgd = *pgd_p; And we check if pgd is presented. If it is, we assign the base address of the page upper directory table to pud_p: pud_p = (pudval_t *)((pgd & PTE_PFN_MASK) + __START_KERNEL_map - phys_base); where PTE_PFN_MASK is a macro which mask lower 12 bits of (pte|pmd|pud|pgd)val_t. If pgd is not presented, we check if next_early_pgt is not greater than EARLY_DYNAMIC_PAGE_TABLES which is 64 and present a fixed number of buffers to set up new page tables on demand. If next_early_pgt is greater than EARLY_DYNAMIC_PAGE_TABLES we reset page tables and start again from again label. If next_early_pgt is less than EARLY_DYNAMIC_PAGE_TABLES, we assign the next entry of early_dynamic_pgts to pud_p and fill whole entry of the page upper directory with 0, then fill the page global directory entry with the base address and some access rights: if (next_early_pgt >= EARLY_DYNAMIC_PAGE_TABLES) { reset_early_page_tables(); goto again; } pud_p = (pudval_t *)early_dynamic_pgts[next_early_pgt++]; memset(pud_p, 0, sizeof(*pud_p) * PTRS_PER_PUD); *pgd_p = (pgdval_t)pud_p - __START_KERNEL_map + phys_base + _KERNPG_TABLE; And we fix pud_p to point to correct entry and assign its value to pud with the following: pud_p += pud_index(address); pud = *pud_p; And then we do the same routine as above, but to the page middle directory. In the end we assign the given pmd which is passed by the early_make_pgtable function to the certain entry of page middle directory which maps kernel text+data virtual addresses: pmd_p[pmd_index(address)] = pmd; After page fault handler finished its work, as a result, early_top_pgt contains entries which point to the valid addresses. Other exception handling In early interrupt phase, exceptions other than page fault are handled by early_fixup_exception function which is defined in arch/x86/mm/extable.c and takes two parameters - pointer to kernel stack which consists of saved registers and vector number: void __init early_fixup_exception(struct pt_regs *regs, int trapnr) { ... ... ... } First of all we need to make some checks as the following: if (trapnr == X86_TRAP_NMI) return; if (early_recursion_flag > 2) goto halt_loop; if (!xen_pv_domain() && regs->cs != __KERNEL_CS) goto fail; Here we just ignore NMI and make sure that we are not in recursive situation. After that, we get into: if (fixup_exception(regs, trapnr)) return; The fixup_exception function finds the actual handler and call it. It is defined in the same file as early_fixup_exception function as the following: int fixup_exception(struct pt_regs *regs, int trapnr) { const struct exception_table_entry *e; ex_handler_t handler; e = search_exception_tables(regs->ip); if (!e) return 0; handler = ex_fixup_handler(e); return handler(e, regs, trapnr); } The ex_handler_t is a type of function pointer, which is defined like: typedef bool (*ex_handler_t)(const struct exception_table_entry *, struct pt_regs *, int) The search_exception_tables function looks up the given address in the exception table (i.e. the contents of the ELF section, __ex_table). After that, we get the actual address by ex_fixup_handler function. At last we call actual handler. For more information about exception table, you can refer to Documentation/x86/exception-tables.txt. Let's get back to the early_fixup_exception function, the next step is: if (fixup_bug(regs, trapnr)) return; The fixup_bug function is defined in arch/x86/kernel/traps.c. Let's have a look on the function implementation: int fixup_bug(struct pt_regs *regs, int trapnr) { if (trapnr != X86_TRAP_UD) return 0; switch (report_bug(regs->ip, regs)) { case BUG_TRAP_TYPE_NONE: case BUG_TRAP_TYPE_BUG: break; case BUG_TRAP_TYPE_WARN: regs->ip += LEN_UD2; return 1; } return 0; } All what this funtion does is just returns 1 if the exception is generated because #UD (or Invalid Opcode) occured and the report_bug function returns BUG_TRAP_TYPE_WARN, otherwise returns 0. Conclusion This is the end of the second part about linux kernel insides. If you have questions or suggestions, ping me in twitter 0xAX, drop me email or just create issue. In the next part we will see all steps before kernel entry point - start_kernel function. Please note that English is not my first language and I am really sorry for any inconvenience. If you found any mistakes please send me PR to linux-insides.
https://0xax.gitbooks.io/linux-insides/Initialization/linux-initialization-2.html
CC-MAIN-2019-04
refinedweb
2,808
50.26
/* * > /* Note!. */ #define IEEE80211_CHAN_W_SCAN 0x00000001 #define IEEE80211_CHAN_W_ACTIVE_SCAN 0x00000002 #define IEEE80211_CHAN_W_IBSS 0x00000004 /* Channel information structure. Low-level driver is expected to fill in chan, * freq, and val fields. Other fields will be filled in by 80211.o based on * hostapd information and low-level driver does not need to use them. The * limits for each channel will be provided in 'struct ieee80211_conf' when * configuring the low-level driver with hw->config callback. If a device has * a default regulatory domain, IEEE80211_HW_DEFAULT_REG_DOMAIN_CONFIGURED * can be set to let the driver configure all fields */ struct ieee80211_channel { short chan; /* channel number (IEEE 802.11) */ short freq; /* frequency in MHz */ int val; /* hw specific value for the channel */ int flag; /* flag for hostapd use (IEEE80211_CHAN_*) */ unsigned char power_level; unsigned char antenna_max; }; #define IEEE80211_RATE_ERP 0x00000001 #define IEEE80211_RATE_BASIC 0x00000002 #define IEEE80211_RATE_PREAMBLE2 0x00000004 #define IEEE80211_RATE_SUPPORTED 0x00000010 #define IEEE80211_RATE_OFDM 0x00000020 #define IEEE80211_RATE_CCK 0x00000040 #define IEEE80211_RATE_MANDATORY 0x00000100 #define IEEE80211_RATE_CCK_2 (IEEE80211_RATE_CCK | IEEE80211_RATE_PREAMBLE2) #define IEEE80211_RATE_MODULATION(f) \ (f & (IEEE80211_RATE_CCK | IEEE80211_RATE_OFDM)) /* Low-level driver should set PREAMBLE2, OFDM and CCK flags. * BASIC, SUPPORTED, ERP, and MANDATORY flags are set in 80211.o based on the * configuration. */ struct ieee80211_rate { int rate; /* rate in 100 kbps */ int val; /* hw specific value for the rate */ int flags; /* IEEE80211_RATE_ flags */ int val2; /* hw specific value for the rate when using short preamble * (only when IEEE80211_RATE_PREAMBLE2 flag is set, i.e., for * 2, 5.5, and 11 Mbps) */ signed char min_rssi_ack; unsigned char min_rssi_ack_delta; /* following fields are set by 80211.o and need not be filled by the * low-level driver */ int rate_inv; /* inverse of the rate (LCM(all rates) / rate) for * optimizing channel utilization estimates */ }; /** *; /** * struct ieee80211_tx_queue_stats_data - transmit queue statistics * * @len: number of packets in queue * @limit: queue length limit * @count: number of frames sent */ struct ieee80211_tx_queue_stats_data { unsigned int len; unsigned int limit; unsigned int count; /** * enum ieee80211_tx_queue - transmit queue number * * These constants are used with some callbacks that take a * queue number to set parameters for a queue. * * @IEEE80211_TX_QUEUE_DATA0: data queue 0 * @IEEE80211_TX_QUEUE_DATA1: data queue 1 * @IEEE80211_TX_QUEUE_DATA2: data queue 2 * @IEEE80211_TX_QUEUE_DATA3: data queue 3 * @IEEE80211_TX_QUEUE_DATA4: data queue 4 * @IEEE80211_TX_QUEUE_SVP: ?? * @NUM_TX_DATA_QUEUES: number of data queues * @IEEE80211_TX_QUEUE_AFTER_BEACON: transmit queue for frames to be * sent after a beacon * @IEEE80211_TX_QUEUE_BEACON: transmit queue for beacon frames */ enum ieee80211_tx_queue { IEEE80211_TX_QUEUE_DATA0, IEEE80211_TX_QUEUE_DATA1, IEEE80211_TX_QUEUE_DATA2, IEEE80211_TX_QUEUE_DATA3, IEEE80211_TX_QUEUE_DATA4, IEEE80211_TX_QUEUE_SVP, NUM_TX_DATA_QUEUES, /* due to stupidity in the sub-ioctl userspace interface, the items in * this struct need to have fixed values. As soon as it is removed, we can * fix these entries. */ IEEE80211_TX_QUEUE_AFTER_BEACON = 6, IEEE80211_TX_QUEUE_BEACON = 7 }; struct ieee80211_tx_queue_stats { struct ieee80211_tx_queue_stats_data data[NUM_TX_DATA_QUEUES]; }; struct ieee80211_low_level_stats { unsigned int dot11ACKFailureCount; unsigned int dot11RTSFailureCount; unsigned int dot11FCSErrorCount; unsigned int dot11RTSSuccessCount; }; /* Transmit control fields. This data structure is passed to low-level driver * with each TX frame. The low-level driver is responsible for configuring * the hardware to use given values (depending on what is supported). */ struct ieee80211_tx_control { int tx_rate; /* Transmit rate, given as the hw specific value for the * rate (from struct ieee80211_rate) */ int rts_cts_rate; /* Transmit rate for RTS/CTS frame, given as the hw * specific value for the rate (from * struct ieee80211_rate) */ #define IEEE80211_TXCTL_REQ_TX_STATUS (1<<0)/* request TX status callback for * this frame */ #define IEEE80211_TXCTL_DO_NOT_ENCRYPT (1<<1) /* send this frame without * encryption; e.g., for EAPOL * frames */ #define IEEE80211_TXCTL_USE_RTS_CTS (1<<2) /* use RTS-CTS before sending * frame */ #define IEEE80211_TXCTL_USE_CTS_PROTECT (1<<3) /* use CTS protection for the * frame (e.g., for combined * 802.11g / 802.11b networks) */ #define IEEE80211_TXCTL_NO_ACK (1<<4) /* tell the low level not to * wait for an ack */ #define IEEE80211_TXCTL_RATE_CTRL_PROBE (1<<5) #define IEEE80211_TXCTL_CLEAR_DST_MASK (1<<6) #define IEEE80211_TXCTL_REQUEUE (1<<7) #define IEEE80211_TXCTL_FIRST_FRAGMENT (1<<8) /* this is a first fragment of * the frame */ #define IEEE80211_TXCTL_LONG_RETRY_LIMIT (1<<10) /* this frame should be send * using the through * set_retry_limit configured * long retry value */ u32 flags; /* tx control flags defined * above */ u8 key_idx; /* keyidx from hw->set_key(), undefined if * IEEE80211_TXCTL_DO_NOT_ENCRYPT is set */ u8 retry_limit; /* 1 = only first attempt, 2 = one retry, .. * This could be used when set_retry_limit * is not implemented by the driver */ u8_rate *rate; /* internal 80211.o rate */ struct ieee80211_rate *rts_rate; /* internal 80211.o rate * for RTS/CTS */ int alt_retry_rate; /* retry rate for the last retries, given as the * hw specific value for the rate (from * struct ieee80211_rate). To be used to limit * packet dropping when probing higher rates, if hw * supports multiple retry rates. -1 = not used */ int type; /* internal */ int ifindex; /* internal */ }; /** *, }; /** *; int flag; }; /** * enum ieee80211_tx_status_flags - transmit status flags * * Status flags to indicate various transmit conditions. * * @IEEE80211_TX_STATUS_TX_FILTERED: The frame was not transmitted * because the destination STA was in powersave mode. * * @IEEE80211_TX_STATUS_ACK: Frame was acknowledged */ enum ieee80211_tx_status_flags { IEEE80211_TX_STATUS_TX_FILTERED = 1<<0, IEEE80211_TX_STATUS_ACK = 1<<1, }; /** * struct ieee80211_tx_status - transmit status * * As much information as possible should be provided for each transmitted * frame with ieee80211_tx_status(). * * @control: a copy of the &struct ieee80211_tx_control passed to the driver * in the tx() callback. * * @flags: transmit status flags, defined above * * ; int ack_signal; int queue_length; int queue_number; }; /** * enum ieee80211_conf_flags - configuration flags * * Flags to define PHY configuration options * * @IEEE80211_CONF_SHORT_SLOT_TIME: use 802.11g short slot time * @IEEE80211_CONF_RADIOTAP: add radiotap header at receive time (if supported) * */ - types of 802.11 network interfaces * * @IEEE80211_IF_TYPE_AP: interface in AP mode. * @IEEE80211_IF_TYPE_MGMT: special interface for communication with hostap * daemon. Drivers should never see this type. * @IEEE80211_IF_TYPE_STA: interface in STA (client) mode. * @IEEE80211_IF_TYPE_IBSS: interface in IBSS (ad-hoc) mode. * @IEEE80211_IF_TYPE_MNTR: interface in monitor (rfmon) mode. * @IEEE80211_IF_TYPE_WDS: interface in WDS mode. * @IEEE80211_IF_TYPE_VLAN:, }; /** * struct ieee80211_if_init_conf - initial configuration of an interface * * @if_id: internal interface ID. This number has no particular meaning to * drivers and the only allowed usage is to pass it to * ieee80211_beacon_get() and ieee80211_get_buffered_bc() functions. * This field is not valid for monitor interfaces * (interfaces of %IEEE80211_IF_TYPE_MNTR type). * @type: one of &enum ieee80211_if_types constants. Determines the type of * added/removed interface. * @mac_addr: pointer to MAC address of the interface. This pointer is valid * until the interface is removed (i.e. it cannot be used after * remove_interface() callback was called for this interface). * This pointer will be %NULL for monitor interfaces, be careful. * * { int if_id; int type; void *mac_addr; }; /** * struct ieee80211_if_conf - configuration of an interface * * @type: type of the interface. This is always the same as was specified in * &struct ieee80211_if_init_conf. The type of an interface never changes * during the life of the interface; this field is present only for * convenience. * @bssid: BSSID of the network we are associated to/creating. * @ssid: used (together with @ssid_len) by drivers for hardware that * generate beacons independently. The pointer is valid only during the * config_interface() call, so copy the value somewhere if you need * it. * @ssid_len: length of the @ssid field. * @generic_elem: used (together with @generic_elem_len) by drivers for * hardware that generate beacons independently. The pointer is valid * only during the config_interface() call, so copy the value somewhere * if you need it. * @generic_elem_len: length of the generic element. * @beacon: beacon template. Valid only if @host_gen_beacon_template in * &struct ieee80211_hw is set. The driver is responsible of freeing * the sk_buff. * @beacon_control: tx_control for the beacon template, this field is only * valid when the @beacon field was set. * * This structure is passed to the config_interface() callback of * &struct ieee80211_hw. */ struct ieee80211_if_conf { int type; u8 *bssid; u8 *ssid; size_t ssid_len; u8 *generic_elem; size_t generic_elem_len; struct sk_buff *beacon; struct ieee80211_tx_control *beacon_control; }; /** * enum ieee80211_key_alg - key algorithm * @ALG_NONE: Unset key algorithm, will never be passed to the driver * @ALG_WEP: WEP40 or WEP104 * @ALG_TKIP: TKIP * @ALG_CCMP: CCMP (AES) */ typedef enum ieee80211_key_alg { ALG_NONE, ALG_WEP, ALG_TKIP, ALG_CCMP, } ieee80211_key_alg; /** *. */ enum ieee80211_key_flags { IEEE80211_KEY_FLAG_WMM_STA = 1<<0, IEEE80211_KEY_FLAG_GENERATE_IV = 1<<1, IEEE80211_KEY_FLAG_GENERATE_MMIC= 1<<2, }; /** * */ struct ieee80211_key_conf { ieee80211_key_alg alg; u8 hw_key_idx; u8 flags; s8 keyidx; u8 keylen; u8 key[0]; }; #define IEEE80211_SEQ_COUNTER_RX 0 #define IEEE80211_SEQ_COUNTER_TX 1 /** * enum set_key_cmd - key command * * Used with the set_key() callback in &struct ieee80211_ops, this * indicates whether a key is being removed or added. * * @SET_KEY: a key is set * @DISABLE_KEY: a key must be disabled */ typedef enum set_key_cmd { SET_KEY, DISABLE_KEY, } set_key_cmd; /** * struct ieee80211_hw - hardware information and state * TODO: move documentation into kernel-doc format */ at 2 */ /* Whether RX frames passed to ieee80211_rx() include FCS in the end */ #define IEEE80211_HW_RX_INCLUDES_FCS (1<<3) /* Some wireless LAN chipsets buffer broadcast/multicast frames for * power saving stations in the hardware/firmware and others rely on * the host system for such buffering. This option is used to * configure the IEEE 802.11 upper layer to buffer broadcast/multicast * frames when there are power saving stations so that low-level driver * can fetch them with ieee80211_get_buffered_bc(). */ #define IEEE80211_HW_HOST_BROADCAST_PS_BUFFERING (1<<4) /* hole at 5 */ /* hole at 6 */ /* hole at 7 */ /* hole. * * This is called to enable hardware acceleration of encryption and * decryption. The address will be the broadcast address for default * keys, the other station's hardware address for individual keys or * the zero address for keys that will be used only for transmission. * * The local_address parameter will always be set to our own address, * this is only relevant if you support multiple local addresses. * * When transmitting, the TX control data will use the hw_key_idx * selected by the low-level driver. * *. * * This callback can sleep, and is only called between add_interface * and remove_interface calls, i.e. while the interface with the * given local_address is enabled. * * The ieee80211_key_conf structure pointed to by the key parameter * is guaranteed to be valid until another call to set_key removes * it, but it can only be used as a cookie to differentiate keys. */ int (*set_key)(struct ieee80211_hw *hw, set_key_cmd cmd, const u8 *local_address, const u8 *address, struct ieee80211_key_conf *key); /*); /* Handle ERP IE change notifications. Must be atomic. */ void (*erp_ie_changed)(struct ieee80211_hw *hw, u8 changes, int cts_protection, int preamble); /* Flags for the erp_ie_changed changes parameter */ #define IEEE80211_ERP_CHANGE_PROTECTION (1<<0) /* protection flag changed */ #define IEEE80211_ERP_CHANGE_PREAMBLE (1<<1) /* barker preamble mode changed */ /* * sent. */ void ieee80211_tx_status(struct ieee80211_hw *hw, struct sk_buff *skb, struct ieee80211_tx_status *status); void ieee80211_tx_status_irqsafe(struct ieee80211_hw *hw, struct sk_buff *skb, struct ieee80211_tx_status *status); /** * ieee80211_beacon_get - beacon generation function * @hw: pointer obtained from ieee80211_alloc_hw(). * @if_id: interface ID from &struct ieee80211_if_init_conf. * @control: will be filled with information needed to send this beacon. * * If the beacon frames are generated by the host system (i.e., not in * hardware/firmware), the low-level driver uses this function to receive * the next beacon frame from the 802.11 code. The low-level is responsible * for calling this function before beacon data is needed (e.g., based on * hardware interrupt). Returned skb is used only once and low-level driver * is responsible of freeing it. */ struct sk_buff *ieee80211_beacon_get(struct ieee80211_hw *hw, int if_id, struct ieee80211_tx_control *control); /** * ieee80211_rts_get - RTS frame generation function * @hw: pointer obtained from ieee80211_alloc_hw(). * @if_id: interface ID from &struct ieee80211_if_init_conf. * @frame: pointer to the frame that is going to be protected by the RTS. * @frame_len: the frame length (in octets). * @frame_txctl: &struct ieee80211_tx_control of the frame. * @rts: The buffer where to store the RTS frame. * *. */ void ieee80211_rts_get(struct ieee80211_hw *hw, int if_id, const void *frame, size_t frame_len, const struct ieee80211_tx_control *frame_txctl, struct ieee80211_rts *rts); /** * ieee80211_rts_duration - Get the duration field for an RTS frame * @hw: pointer obtained from ieee80211_alloc_hw(). * @frame_len: the length of the frame that is going to be protected by the RTS. * @frame_txctl: &struct ieee80211_tx_control of the frame. * * If the RTS is generated in firmware, but the host system must provide * the duration field, the low-level driver uses this function to receive * the duration field value in little-endian byteorder. */ __le16 ieee80211_rts_duration(struct ieee80211_hw *hw, int if_id, size_t frame_len, const struct ieee80211_tx_control *frame_txctl); /** * ieee80211_ctstoself_get - CTS-to-self frame generation function * @hw: pointer obtained from ieee80211_alloc_hw(). * @frame: pointer to the frame that is going to be protected by the CTS-to-self. * @frame_len: the frame length (in octets). * @frame_txctl: &struct ieee80211_tx_control of the frame. * @cts: The buffer where to store the CTS-to-self frame. * *. */ void ieee80211_ctstoself_get(struct ieee80211_hw *hw, int if_id, const void *frame, size_t frame_len, const struct ieee80211_tx_control *frame_txctl, struct ieee80211_cts *cts); /** * ieee80211_ctstoself_duration - Get the duration field for a CTS-to-self frame * @hw: pointer obtained from ieee80211_alloc_hw(). * @frame_len: the length of the frame that is going to be protected by the CTS-to-self. * @frame_txctl: &struct ieee80211_tx_control of the frame. * * If the CTS-to-self is generated in firmware, but the host system must provide * the duration field, the low-level driver uses this function to receive * the duration field value in little-endian byteorder. */ __le16 ieee80211_ctstoself_duration(struct ieee80211_hw *hw, int if_id, size_t frame_len, const struct ieee80211_tx_control *frame_txctl); /** * ieee80211_generic_frame_duration - Calculate the duration field for a frame * @hw: pointer obtained from ieee80211_alloc_hw(). * @frame_len: the length of the frame. * @rate: the rate (in 100kbps) at which the frame is going to be transmitted. * * Calculate the duration field of some generic frame, given its * length and transmission rate (in 100kbps). */ __le16 ieee80211_generic_frame_duration(struct ieee80211_hw *hw, int if_id, size_t frame_len, int rate); /** * ieee80211_get_buffered_bc - accessing buffered broadcast and multicast frames * @hw: pointer as obtained from ieee80211_alloc_hw(). * @if_id: interface ID from &struct ieee80211_if_init_conf. * @control: will be filled with information needed to send returned frame. * *. * * Note:. */ struct sk_buff * ieee80211_get_buffered_bc(struct ieee80211_hw *hw, int if_id, struct ieee80211_tx_control *control); /*. */ int ieee80211_get_hdrlen(u16 fc); /** * ieee80211_wake_queue - wake specific queue * @hw: pointer as obtained from ieee80211_alloc_hw(). * @queue: queue number (counted from zero). * * Drivers should use this function instead of netif_wake_queue. */ void ieee80211_wake_queue(struct ieee80211_hw *hw, int queue); /** * ieee80211_stop_queue - stop specific queue * @hw: pointer as obtained from ieee80211_alloc_hw(). * @queue: queue number (counted from zero). * * Drivers should use this function instead of netif_stop_queue. */ void ieee80211_stop_queue(struct ieee80211_hw *hw, int queue); /** * ieee80211_start_queues - start all queues * @hw: pointer to as obtained from ieee80211_alloc_hw(). * * Drivers should use this function instead of netif_start_queue. */ void ieee80211_start_queues(struct ieee80211_hw *hw); /** * ieee80211_stop_queues - stop all queues * @hw: pointer as obtained from ieee80211_alloc_hw(). * * Drivers should use this function instead of netif_stop_queue. */ void ieee80211_stop_queues(struct ieee80211_hw *hw); /** * ieee80211_wake_queues - wake all queues * @hw: pointer as obtained from ieee80211_alloc_hw(). * * Drivers should use this function instead of netif_wake_queue. */ void ieee80211_wake_queues(struct ieee80211_hw *hw); /** * ieee80211; } #endif /* MAC80211_H */
https://gitlab.flux.utah.edu/xcap/xcap-capability-linux/-/blame/070ac3a2651e3c1c4d277c5f1981517427c386a7/include/net/mac80211.h
CC-MAIN-2021-21
refinedweb
2,245
54.52
The three ways to execute a GraphQL query from React with AWS AppSync (and how to choose) AWS AppSync is a managed GraphQL service that can (and probably should) act as the data layer for your app. I’m not going to go into the details of how to configure it since I’ve gone through that in excruciating detail recently (see blog #1, #2, #3, and #4). Rather, I want to take a look at how you can send a query to AWS AppSync from your React (or React Native) app. You have three basic choices: - Include a query within a component using AWS Amplify. - Wrap your query in the Connect component using AWS Amplify. - Use the Apollo Client with the AWS AppSync SDK. Which do you choose depends on what your needs are. There is no “one size fits all”. Let’s look at the options: Include a query within a component using AWS Amplify The first version of the query utilizes the API.graphql() method from the AWS Amplify library. You can execute queries, mutations, and subscriptions from this form. It’s an async network call, so expect to deal with promises and errors. Here is the canonical form of a simple query: public async componentWillMount() { try { const result = await API.graphql(graphqlOperation('{ me { id name } }')); console.log('componentWillMount: result = ', result); this.setState({ loading: false, data: result.data.me }); } catch (err) { this.setState({ loading: false, errors: [ err.message ] }); } } There are a couple of notes here: - I’m using async/await to ensure I wait for the data. - I must use try/catch so that I can catch network and authentication errors. The result has a data block with the fields that I requested: result = Object { "data": Object { "me": Object { "id": "ARO*****:CognitoIdentityCredentials", "name": null } } } All the fields you requested are returned, but the value may be null if no data is available. If I’ve got a component that has to get data from the network or I am using a library to do all the calls (and mocking those calls for testability), this is a great way to do it. However, if I decide to incorporate the call within a component, I have to worry about how I am going to test that component. I’d more likely place the call within a library and swap out the library with a mocked call at that point. I also have to deal with online/offline capabilities. The AWS Amplify library does not do offline at this point in time, so if I want that functionality, I’m going to have to go to a different library. Pros: - It’s simple to set up an execute the query, mutation, or subscription. - It works with the AWS Amplify CLI and configuration file, so configuration is a snap. - It works easily with my preferred Flux implementation. - Simplified codebase = less stuff to go wrong. Cons: - You will need to be careful to ensure that your components can be unit tested. - There is no offline capabilities. Wrap your query in the AWS Amplify Connect component The next step is to use the <Connect> component to wrap my component. The <Connect> component will give you loading and error conditions, so you can use those to handle network conditions. Let’s say I have a component that is normally used like this: <UserBlock name={"Adrian Hall"}/> I want to use the <Connect> query to connect this to the me query that I was using before. I might do this: const UserBlockFunction = () => { return ( <Connect query={graphqlOperation('{ me { id name } }')}> {(response) => { if (response.loading) { return (<LoadingIndicator loading={response.loading}/>); } else if (response.data && response.data.me) { return (<UserBlock name={response.data.me.name}/>); } else { return (<ErrorIndicator errors={response.errors}/>); } }} </Connect> ); }; export default UserBlockFunction; In this version, I’ve got three cases: - The query is loading (loading == true) - The query has returned data (response.data.me is defined) - The query ended in one or more errors (response.errors is defined) I can use this to generate different output within my exported function for each condition. I generally have the underlying components as one set of files, then I connect them to the GraphQL API as another set of files. Pros: - I can test my underlying components individually without resorting to network connectivity. - I can hook individual parts of my component hierarchy as needed, resulting in much flexibility. - The API is powerful, yet simple. That leads to elegant and readable code that is easy to debug. Cons: - It no longer works with my Flux configuration, so I now have two state systems to deal with. - Still no offline support. Use the Apollo Client with the AWS AppSync SDK. The final method is to bring in a heavyweight client like the Apollo Client. It took me some time to learn the Apollo Client and it’s overkill for most situations. In this method, you create an AWS AppSync Client, then use that to configure the Apollo Client. Then wrap your entire app within the Apollo Client. Your connected components now have full knowledge of the Apollo Client, but your lower level components can remain oblivious (just like the <Connect> component I discussed above). Let’s look at the same functionality as before. First, configure the client within your main app code: import gql from 'graphql-tag'; import AWSAppSyncClient, { AUTH_TYPE } from 'aws-appsync'; import aws_config from './aws-exports'; import App from './src/App'; const client = new AWSAppSyncClient({ url: aws_config.aws_appsync_graphqlEndpoint, region: aws_config.aws_appsync_region, auth: { type: aws_config.aws_appsync_authenticationType, apiKey: aws_config.aws_appsync_apiKey, } }); const WithProvider = () => ( <ApolloProvider client={client}> <Rehydrated> <App /> </Rehydrated> </ApolloProvider> ); export default WithProvider; Then create the connected component: import gql from 'graphql-tag'; import { graphql } from 'react-apollo'; import * as React from 'react'; import UserBlockComponent from '../components/UserBlock'; const query = gql` query me { me { id name } } `; class UserBlock extends React.Component { render() { if (this.props.loading) { return (<LoadingIndicator/>): } else if (props.errors) { return (<ErrorIndicator errors={this.props.errors}/>); } else { return (<UserBlockComponent name={this.props.name}/>); } } } export default graphql(query, { options: { fetchPolicy: 'cache-and-network' }, props: props => ({ loading: props.loading, errors: props.errors, name: props.data.me.name || 'undefined' }) })(UserBlock); More power, but more complexity and more places for things to go wrong. Pros: - Offline capabilities are available. Queries are cached and mutations are queued for later transmission - I can test my underlying components individually without resorting to network connectivity. Cons: - This is a complex client that will take time to learn fully. - Offline can introduce caching bugs (such as stale data) that just didn’t exist before. - I have to wrap a good portion of my app in the Apollo client, replacing the Flux implementation (or at least making it harder to implement and follow the data flow). Wrap Up Here is the basic version that covers the advice I would give as of this writing: - Use the Apollo Client with the AWS AppSync SDK if you need offline capabilities. - Wrap your component in the AWS Amplify Connect component for the majority of online-only cases, then use API.graphql()for the mutations to send data to the server. - Use API.graphql()only if you want to do a query outside of a React component. - Keep an eye on the AWS Amplify library as they are always extending the functionality of the client.
https://adrianhall.github.io/cloud/2019/01/15/three-ways-graphql-react-awsappsync/
CC-MAIN-2019-43
refinedweb
1,212
57.67
10.13: Recursive Functions - Page ID - 14674 Before you can learn how the floodFill() function works, you need to learn about recursion. Recursion is a simple concept: A recursive function is just a function that calls itself, like the one in the following program: def passFortyTwoWhenYouCallThisFunction(param): print('Start of function.') if param != 42: print('You did not pass 42 when you called this function.') print('Fine. I will do it myself.') passFortyTwoWhenYouCallThisFunction(42) # this is the recursive call if param == 42: print('Thank you for passing 42 when you called this function.') print('End of function.') passFortyTwoWhenYouCallThisFunction(41) (In your own programs, don’t make functions have names as long as passFortyTwoWhenYouCallThisFunction(). I’m just being stupid and silly. Stupilly.) When you run this program, the function gets defined when the def statement on line 1 executes. The next line of code that is executed is line 10, which calls passFortyTwoWhenYouCallThisFunction() and passes (gasp!) 41. As a result, the function calls itself on line 5 and passes 42. We call this call the recursive call. This is what our program outputs: Start of function. You did not pass 42 when you called this function. Fine. I will do it myself. Start of function. Thank you for passing 42 when you called this function. End of function. End of function. Notice that the "Start of function." and "End of function." text appears twice. Let’s figure out what exactly happens and what order it happens in. On line 10, the function is called and 41 is passed for the param parameter. Line 2 prints out "Start of function.". The condition on line 3 will be True (since 41 != 42) so Line 3 and 4 will print out their messages. Line 5 will then make a call, recursively, to the function and passes 42 for the param parameter. So execution starts on line B again and prints out "Start of function.". Line 3’s condition this time is False, so it skips to line 6 and finds that condition to be True. This causes line 7 to be called and displays "Thank you..." on the screen. Then the last line of the function, line 8, will execute to print out ―End of function.‖ and the function returns to the line that called it. But remember, the line of code that called the function was line 5. And in this original call, param was set to 41. The code goes down to line G and checks the condition, which is False (since 41 == 42 is False) so it skips the print() call on line 7. Instead, it runs the print() call on line 8 which makes "End of function." display for a second time. Since it has reached the end of the function, it returns to the line of code that called this function call, which was line 10. There are no more lines of code after line 10, so the program terminates. Note that local variables are not just local to the function, but to a specific call of the function.
https://eng.libretexts.org/Bookshelves/Computer_Science/Book%3A_Making_Games_with_Python_and_Pygame_(Sweigart)/10%3A_Star_Pusher/10.13%3A_Recursive_Functions
CC-MAIN-2021-25
refinedweb
510
84.88
ACCESS MODIFIER: Public : public class is visible in other package,field is visible everywhere(class must be public too) Private:private variables or methods may be used only by instance of the same class that declares the variable or method,a private feature may only be accessed by the class that owns the feature. Protected: Is available to all clasas in the same package and also available to all subclasses of the class that owns the protected feature. Default: what you get by default ie.without any access modifier(ie,public,privateor protected).It means that it is visible to all within a particular package. NON ACCESS MODIFIER: Static: -. final: - A final class can’t be extended ie.,final class may not be subclassed. - A final method can’t be overridden when its class is inherited. You can’t change value of a final variable(is a constant).Abstract: - An abstract class is a class designed with implementation gaps for subclasses t fill in and is deliberately incomplete. A calss cannot be both final and abstract . - abstract methods cannot be private. - abstract methods cannot be final. Static block:. BACK
http://candidjava.com/access-modifiers-in-java/
CC-MAIN-2018-30
refinedweb
189
58.89
In a non-trivial application, the architecture is as important as the quality of the code itself. We can have well-written pieces of code, but if we don’t have a good organization, we’ll have a hard time as the complexity increases. There’s no need to wait until the project is half-way done to start thinking about the architecture. The best time is before starting, using our goals as beacons for our choices. Node.js doesn’t have a de facto framework with strong opinions on architecture and code organization in the same way that Ruby has the Rails framework, for example. As such, it can be difficult to get started with building full web applications with Node. In this article, we’re going to build the basic functionality of a note-taking app using the MVC architecture. To accomplish this, we’re going to employ the Hapi.js framework for Node.js and SQLite as a database, using Sequelize.js, plus other small utilities to speed up our development. We’re going to build the views using Pug, the templating language. What is MVC? Model-View-Controller (or MVC) is probably one of the most popular architectures for applications. As with a lot of other cool things in computer history, the MVC model was conceived at PARC for the Smalltalk language as a solution to the problem of organizing applications with graphical user interfaces. It was created for desktop applications, but since then, the idea has been adapted to other mediums including the web. We can describe the MVC architecture in simple words: - Model: The part of our application that will deal with the database or any data-related functionality. - View: Everything the user will see. Basically the pages that we’re going to send to the client. - Controller: The logic of our site, and the glue between models and views. Here we call our models to get the data, then we put that data on our views to be sent to the users. Our application will allow us to publish, see, edit and delete plain-text notes. It won’t have other functionality, but because we’ll have a solid architecture already defined we won’t have big trouble adding things later. You can check out the final application in the accompanying GitHub repository, so you get a general overview of the application structure. Laying out the Foundation The first step when building any Node.js application is to create a package.json file, which is going to contain all of our dependencies and scripts. Instead of creating this file manually, npm can do the job for us using the init command:}`); }); This is going to be the foundation of our application. First, we indicate that we’re going to use strict mode, which is a common practice when using the Hapi.js framework. Next, we include our dependencies and instantiate a new server object where we set the connection port to 3000 (the port can be any number above 1023 and below 65535.) Our first route for our server will work as a test to see if everything is working, so a “Hello, world!” message is enough for us. In each route, we have to define the HTTP method and path (URL) that it will respond to, and a handler, which is a function that will process the HTTP request. The handler function can take two arguments: request and.g. development or production). For example, we can have an in-memory instance of SQLite for development purposes, but a real SQLite database file on production. Selecting the settings depending on the current environment is quite simple. Since we also have an env variable in our file which will contain either development or production, we can do something like the following to get the database settings (for example): const dbSettings = Settings[Settings.env].db; So dbSettings will contain the setting of an in-memory database when the env variable is development, or will contain the path of a database file when the env variable is production. Also, we can add support for a .env file, where we can store our environment variables locally for development purposes; this is accomplished using a package like dotenv for Node.js, which will read a .env file from the root of our project and automatically add the found values to the environment. You can find an example in the dotenv repository. Note: If you decide to also use a .env file, make sure you install the package with npm install -s dotenv and add it to .gitignore so you don’t publish any sensitive information. Our settings.js file will look like this: // This will load our .env file and add the values to process.env, // IMPORTANT: Omit this line if you don't want to use this functionality require('dotenv').config({silent: true}); module.exports = { port: process.env.PORT || 3000, env: process.env. If you get any errors, ensure you have an updated installation. Defining the Routes The definition of routes gives us an overview of the functionality supported by our application. To create our additional routes, we just have to replicate the structure of the route that we already have in our server.js file, changing the content of each one. Let’s start by creating a new directory called lib in our project. Here we’re going to include all the JS components. Inside lib, let’s create a routes.js file and add the following content: 'use strict'; module.exports = [ // We're going to define our routes here ]; In this file, we’ll export an array of objects that contain each route of our application. To define the first route, add the following object to the array: { method: 'GET', path: '/', handler: (request, reply) => { reply('All the notes will appear here'); }, config: { description: 'Gets all the notes available' } }, Our first route is for the home page ( /) and since it will only return information we assign it a GET method. For now, it will only give us the message All the notes will appear here, which we’re going to change later for a controller function. The description field in the config section is only for documentation purposes. Then, we create the four routes for our notes under the /note/ path. Since we’re building a CRUD application, we('This note no longer exists'); }, config: { description: 'Deletes the selected note' } }, We’ve done the same as in the previous route definition, but this time we’ve changed the method to match the action we want to execute. The only exception is the delete route. In this case, we’re going to define it with the GET method rather than DELETE and add an extra /delete in the path. This way, we can call the delete action just by visiting the corresponding URL. Note: If you plan to implement a strict REST interface, then you would have to use the DELETE method and remove the /delete part of the path. We can name parameters in the path by surrounding the word in brackets ({ … }). Since we’re going to identify notes by a slug, we add {slug} to each path, with the exception of the PUT route. We don’t need it there, because we’re not going to interact with a specific note, but to create one. You can read more about Hapi.js routes on the official documentation. Now, we have to add our new routes to the server.js file. Let’s import the routes file at the top of the file: const Routes = require('./lib/routes'); and replace our current test route with the following: server.route(Routes); Building the Models Models allow us to define the structure of the data and all the functions to work with it. In this example, we’re going to use the SQLite database with Sequelize.js which is going to provide us with a better interface using the ORM (Object-Relational Mapping) technique. It will also provide us a database-independent interface. Setting up the database For this section, we’re going to use Sequelize.js and SQlite. You can install and include them as dependencies by executing the following command: npm install -s sequelize sqlite3 Now create a models directory inside lib/ with a file called index.js which is going to contain the database and Sequelize.js setup, and include the following content: 'use strict'; const Fs = require('fs'); const Path = require('path'); const Sequelize = require('sequelize'); const Settings = require('../../settings'); // Database settings for the current environment const dbSettings = Settings[Settings.env].db; const sequelize = new Sequelize(dbSettings.database, dbSettings.user, dbSettings.password, dbSettings); const db = {}; // Read all the files in this directory and import them as models Fs.readdirSync(__dirname) .filter((file) => (file.indexOf('.') !== 0) && (file !== 'index.js')) .forEach((file) => { const model = sequelize.import(Path.join(__dirname, file)); db[model.name] = model; }); db.sequelize = sequelize; db.Sequelize = Sequelize; module.exports = db; First, we include the modules that we’re going to use: Fs, to read the files inside the models folder, which is going to contain all the models. Path, to join the path of each file in the current directory. Sequelize, that will allow us to create a new Sequelize instance. Settings, which contains the data of our settings.js file from the root of our project. Next, we create a new sequelize variable that will contain a Sequelize instance with our database settings for the current environment. We’re going to use sequelize to import all the models and make them available in our db object. The db object is going to be exported and will contain our database methods for each model; it will be available in our application when we need to do something with our data. To load all the models, instead of defining them manually, we look for all the files inside the models directory (with the exception of the index.jsfile) and load them using the import function. The returned object will provide us with the CRUD methods, which we then add to the db object. At the end, we add sequelize and Sequelize as part of our db object, the first one is going to be used in our server.js file to connect to the database before starting the server, and the second one is included for convenience if you need it in other files too. Creating our Note model In this section, we’re going to use the Moment.js package to help with Date formatting. You can install it and include it as a dependency with the following command: npm install -s moment Now, we’re going to create a note.js file inside the models directory, which is going to be the only model in our application; it will provide us with all the functionality we need. Add the following content to that file: 'use strict'; const Moment = require('moment'); module.exports = (sequelize, DataTypes) => { let Note = sequelize.define('Note', { date: { type: DataTypes.DATE, get: function () { return Moment(this.getDataValue('date')).format('MMMM Do, YYYY'); } }, title: DataTypes.STRING, slug: DataTypes.STRING, description: DataTypes.STRING, content: DataTypes.STRING }); return Note; }; We export a function that accepts a sequelize instance, to define the model, and a DataTypes object with all the types available in our database. Next, we define the structure of our data using an object where each key corresponds to a database column and the value of the key defines the type of data that we’re going to store. You can see the list of data types in the Sequelize.js documentation. The tables in the database are going to be created automatically based on this information. In the case of the date column, we also define a how Sequelize should return the value using a getter function ( get key). We indicate that before returning the information it should be first passed through the Moment utility to be formatted in a more readable way ( MMMM Do, YYYY). Note: Although we’re getting a simple and easy to read date string, add the views once we build them. We can think of controllers as functions that will join our models with our views; they will communicate with our models to get the data, and then return that data inside a view. The Home Controller The first controller that we’re going to build will handle the home page of our site. Create a home.js file inside get an array containing all the notes in our database. We can arrange the results in descending order, using the order parameter in the options object passed to the findAll method, so the last item will appear first. You can check all the available options in the Sequelize.js documentation. Once we have the home controller, we can edit our routes.js file. First, we import the module at the top of the file, next to the Path module import: const Home = require('./controllers/home'); Then we add the controller we just made to the array: { method: 'GET', path: '/', handler: Home, config: { description: 'Gets all the notes available' } }, are going to handle your front-end logic, we’re going to return an HTML block to simplify the logic on the client. Also, note that the date is being generated on the fly when we execute the function, using new Date(). The “read” function To search just one element we use the findOne method on our model. Since we identify notes by their slug, the where filter must contain the slug provided by the client in the URL (:). read: (request, reply) => { Models.Note .findOne({ where: { slug: request.params.slug } }) .then((result) => { reply(result); }); }, As in the previous function, we will just return the result, which is going to be an object containing the note information. The views are going to be used once we build them in the Building the Views section. The “update” function To update a note, we use the update method on our model. It takes two objects, the new values that we’re going to replace and the options containing a where filter with the note slug, which is the note that we’re going to update. update: (request, reply) => { const values = { title: request.payload.noteTitle, description: request.payload.noteDescription, content: request.payload.noteContent }; const options = { where: { slug: request.params.slug } }; Models.Note .update(values, options) .then(() => { Models.Note .findOne(options) .then((result) => { reply(result); }); }); }, After updating our data, since our database won’t return the updated note, we can find the modified note again to return it to the client, so we can show the updated version as soon as the changes are made. The “delete” function The delete controller will remove the note by providing the slug to the destroy function of our model. Then, once the note is deleted, we redirect to the home page. To accomplish this, we use the redirect function of the Hapi.js reply object. delete: (request, reply) => { Models.Note .destroy({ where: { slug: request.params.slug } }) .then(() => reply.redirect('/')); } Using the Note controller in our routes At this point, we should have our note controller file ready with all the CRUD actions. But to use them, we have to include it in our routes file. First, let’s import our controller at the top of the routes.js file: const Note = require('./controllers/note'); We have to replace each is going to be reused across our views. Also, we’re going to use this component in some of our controller functions to build a note on the fly in the back-end to simplify the logic on the client. Create a file in lib/views/components called note.pug with the following content: article') The note view The note page is pretty similar to the home page, but in this case, we show a menu with options specific to the current note, the content of the note and the same form as in the home page but with the current note information already filled, so it’s there when we update it. Create a file in lib/views called note.pug with the following content: extends layout block content just add it on top of the list on the home page, and when we update a note we replace the content for the new one in the note view. Adding support for views on the server To make use of our views, we have to include them in our controllers and add the required settings. In our server.js file, let’s import the Node Path utility at the top of the file, since we’re using it in our code to indicate the path of our views. const Path = require('path'); Now, replace the server.route(Routes); line with the following code block:.view('home', { data: { notes: result }, page: 'Home—Notes Board', description: 'Welcome to my Notes Board' }); After registering the Vision plugin, we now have a view method available on the reply object, we’re going to use it to select the home view in our views directory and to send the data that); We use the renderFile method from Pug to render the note template with the data we just received from our model. Setting the note view: read function When we enter a note page, we should get the note template with the content of our note. To do this, we have to replace the); Note: The delete function doesn’t need a view, since it will just redirect to the home page once the note is deleted. Serving Static Files The JavaScript and CSS files that we’re using on the client side are provided by Hapi.js from the static/public/ directory. But it won’t happen automatically; we have to indicate to the server that we want to define this folder as public. This is done using the Inert package, which you can install with the following command: npm install -s inert In the server.register function inside the server.js file, import the Inert plugin and register it with Hapi like this: server.register([ require('vision'), require('inert') ], (err) => { Now we have to define the route where we’re going to provide the static files, and their location on our server’s filesystem. Add the following entry at the end of the exported object in routes.js: { // Static files method: 'GET', path: '/{param*}', handler: { directory: { path: Path.join(__dirname, '../static/public') } }, config: { description: 'Provides static resources' } } This route will use the GET method and we like to take this example a bit further, after finishing all the small details (not related the architecture) to make this a robust application, you could implement an authentication system so only registered users are able to publish and edit notes. But your imagination is the limit, so feel free to fork the application repository,!
https://www.sitepoint.com/node-js-mvc-application/
CC-MAIN-2018-09
refinedweb
3,152
63.8
Hi everybody, I have been having trouble with the output of a set of points for my triangle program. When I run my program, it outputs in the end "triangle1 coordinates: Vertex A is java.awt.Point[x=12,y=13]" and I have no idea how to format it to hide the "java.awt.Point" part. Any advice would be greatly appreciated! Thanks in advance. public class TriangleTester { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter the x- and y- coordinates of the first vertex: "); int a1 = scan.nextInt(); int a2 = scan.nextInt(); System.out.println("Enter the x- and y- coordinates of the second vertex: "); int b1 = scan.nextInt(); int b2 = scan.nextInt(); System.out.println("Enter the x- and y- coordinates of the third vertex: "); int c1 = scan.nextInt(); int c2 = scan.nextInt(); Triangle triangle1 = new Triangle(a1, a2, b1, b2, c1, c2); System.out.println(triangle1.toString()); } } public class Triangle { private int xA; private int yA; private int xB; private int yB; private int xC; private int yC; Point vertexA; Point vertexB; Point vertexC; public Triangle(Point vertexA, Point vertexB, Point vertexC) { vertexA = vertexA; vertexB = vertexB; vertexC = vertexC; } public Triangle(int xA, int yA, int xB, int yB, int xC, int yC) { vertexA = new Point(xA, yA); vertexB = new Point(xB, yB); vertexC = new Point(xC, yC); } public String toString() { return "Vertex A is " + vertexA.toString(); } }
https://www.daniweb.com/programming/software-development/threads/386872/how-format-the-output-of-a-point-for-triangle-class
CC-MAIN-2021-17
refinedweb
238
56.86
I'm scraping and saving (as a comma-delimited text file) information on roll call votes in the US House of Representatives. Each line in the resulting file takes the following form: Roll Call Number, Bill, Date, Representative, Vote, Total Yeas, Total Nays Where I'm running into trouble is scraping the dates from 1-Nov-2001 (roll call 414) onward. Instead of matching 1-Nov-2001, the regex matches incorrectly or breaks. In the first case, it matches the string '-AND-'. The text does change between #414 and #415 to include the string 'YEAS-AND-NAYS'. I'm betting I've written the regex wrong, but I'm not seeing it. What might I need to change to match the date instead? The relevant code is below. import urllib2, datetime, sys, re, string import xml.etree.ElementTree as ET for i in range(414,514): if i < 10: num_string = "00"+str(i) elif i < 100: num_string = "0"+str(i) elif i > 100: num_string = str(i) print num_string, datetime.datetime.now() url = ""+num_string+".xml" text = urllib2.urlopen(url).read() tree = ET.fromstring(text) notags = ET.tostring(tree, encoding="utf8", method="text") dte = re.search(r'[0-9]*-[A-Za-z]*-[0-9]*', notags).group() print dte Using a regular expression against an XML document is never a good idea (seriously). You can achieve the desired result without any regular expressions by extracting the date from the relevant XML element (I've used lxml.etree instead of xml.etree.ElementTree, but the principle will be the same). Also, I've added an easier way to generate a 3-digit number (leading 0 if necessary). import urllib2, datetime, sys, string import lxml.etree for i in range(414,416): num_string = '{:03d}'.format(i) print num_string, datetime.datetime.now() url = ""+num_string+".xml" xml = lxml.etree.parse(urllib2.urlopen(url)) root = xml.getroot() actdate = root.xpath('//action-date')[0] dte = actdate.text.strip() print dte If you insist on using a regular expression, then [0-9]+-[A-Za-z]+-[0-9]+ would be better as it guarantees at least one digit followed by dash followed by at least one letter followed by dash followed by at least one digit (as holdenweb mentions in his comment).
http://m.dlxedu.com/m/askdetail/3/98fc5adb3492fd7f8e640d1c3f20924a.html
CC-MAIN-2018-47
refinedweb
371
69.58
Problem Description HowardLewisShip, April 26 2004, 1-0-alpha-4 One of the tenets of HiveMind is that deployment descriptors for J2EE are in verbose XML, and that this is a bad thing. And yet, the descriptors for HiveMind are themselves XML and can be quite verbose. Several people, especially ErikHatcher, have repeatedly pointed this out to me. As things currently stand, XML is used for several basic reasons: - It's easy to use an XML parser to read the kind of hierarchical data inside a descriptor. It's easy to generate HiveDoc directly from the XML. - It is easier to use existing SAX parsers (now part of the JDK) than to write our own parser. Proposed Solution We can define our own special purpose langage for the descriptors. The language could be more readable and succinct than the equivalent XML. More work would have to be put into the HiveDoc, to generate the HiveDoc directly from the descriptor objects, or to generate an intermediate XML format from the descriptor objects. I've been working on SimpleDataLanguage (SDL), which is isomorphic to a well-defined subset of XML. Rather than get into the messy details, here's an example of a HiveMind module deployment descriptor expressed as SDL: module (id=myapp.ui.toolbar version="1.0.1") { configuration-point(id=ToolbarActions) { schema { element (name=item) { attribute (name=label required=true) attribute (name=icon required=true) attribute (name=action-class) attribute (name=service-id) conversion (class=myapp.ui.toolbar.ToolbarAction) { map (attribute=action-class property=action translator=object) map (attribute=service-id property=action translator=service) } } } } contribution (configuration-id=ToolbarAction) { item (label=Open icon=Open.gif service-id=OpenService) } service-point (id=OpenService interface=myapp.ui.toolbar.ToolbarAction) { invoke-factory(service-id=hivemind.BuilderFactory) { construct(class=myapp.ui.toolbar.impl.OpenActionImpl log-property=log messages-property=messages) { set(name=frob value=grognard) set-service(name=dialogViewer service-id=myapp.ui.DialogViewer) set-configuration(name=pipeline configuration-id=myapp.ui.FileOpenPipeline) } } add-interceptor(service-id=hivemind.LoggingFactory) } } Remember, XML started as a document format, where using punctuation for blocking delimiters was a bad idea, since such characters could show up in the document text. Our use of HiveMind deployment descriptors is a much more constrained environment, more like scripting than like pure documents. For example, quoting of attributes is not necessary for most attributes, just the ones with whitespace (or other characters outside a specific subset) in the value. Also, many parts of XML were intended to make it easier to write an XML parser (though, over time, things have twisted such that a fully conformant XML parser is now an enourmous beast). Again ... not our concern. This solution involves nailing down precisely (in BNF) what our format will look like and writing that parser. I have been experimenting with JavaCC, and have put together an SDL parser that emits SAX parse events. With very minor changes to the DescriptorParser class we could convert our XML descriptors to SDL. We could even support both formats! Discussion What about using something like Groovy to configure and wire everything up? This has the obvious downside that you're working at an imperetive vs. declarative level, probably interacting with the HiveMind object model in some fashion, but has the benefit of being a familiar syntax, very lightweight, and is reusing an existing technology (rather than inventing a proprietary grammar). HowardLewisShip: Groovy may not be fully stable for months and represents a significant new dependency at a time when I'd like to remove dependencies. I'm also not sure how we could get the desired level of (line precise) exception reporting. However, I'd like folks to noodle some more on the ideas of using scripting languages to perform some of the work (especially with respect to the conversion of XML objects). Maybe that is the right approach to removing XML from HiveMind ... that's thiking outside the box. In the meantime, I've updated the example above to reflect a slightly more verbose but significantly more consistent approach (based on additional thoughts I had composing this blog entry). Keeping the design isomorphic to a subset of XML had advantages ... I can just make my parser spew out SAX events, maybe even feed it into a SDL (Simple Data Language) to XML to HTML pipeline. HarishKrishnaswamy: I am completely against the idea of a proprietary language. I think it will certainly hinder adoption. I would like to see a Java scripting language being used for this purpose. I agree Groovy is certainly not stable but Beanshell is. I have already wipped up some configuration for work using Beanshell with line precise error reporting. And all that is needed is a simple helper class and a very small Beanshell script to execute the configuration one node at a time. The script will look something like this: evalModule(url, helper, interpreter, callstack) { setAccessibility(true); reader = null; try { reader = new InputStreamReader(url.openStream()); parser = new Parser(reader); parser.setRetainComments(true); while (!parser.Line()/* eof */) { node = parser.popNode(); node.setSourceFile(url.toString()); // Cache the line number for error reporting purposes helper.setCurrentLineNumber(node.getLineNumber()); node.eval(callstack, interpreter); } } finally { if (reader != null) reader.close(); } } And the configuration file could look like this: servicePoint("service-id", ServiceInterface.class); // Singleton service constructed via constructor injection singleton(implementation("service-id", ServiceImplementation.class, new Object[]{1.34, "some string", service("some-service-id")})); // Pooled service constructed via setter injection dependencies = new HashMap(); dependencies.put("property1", property1Value); dependencies.put("anotherService", service("anotherServiceId")); pooled(implementation("service-id", ServiceImplementation.class, dependencies)); And something along the same lines can be used for configuration too. servicePoint, service, implementation, singleton, pooled ... are all methods in our helper class that will do the needful. Although I haven't yet tried out to build a doc from the config file, I am pretty sure its very simple. Beanshell already has a Bshdoc.bsh script that generates javadoc like doc. ChristianEssl: I like Harish's idea of using Beanshell. It is indeed less verbose than xml. Maybe somehow it could be possible to replace the dependencies map and constructor-array with a closure, which directly constructs the implementation. To me this would be the main advantage of using an alternative config format. Apart of this can someone point out what the disadvantages of xml are except of the verbosity and that ejb (and most other frameworks) use it too. Especially for contributions I think xml is much better than scripting, because you basicly define your own specialized easy-to-use language. Is there some thought of mixing scripting with xml? HowardLewisShip: You might notice I'm unconvinced about using scripting. The core issue is the XML. The way Sun uses XML (lots of elements, no attributes) is super-duper verbose. The XML formats used by HiveMind deployment descriptors are more straight-forward, but are still hard on the eyes ... the extra verbosity inherent in all those open and close brackets, the unnecessary quotes, the long verbose close tags --- those all become distractions to the eye, obscuring the real intent. The SimpleDataLanguage I've been proposing here is (especially for Java coders) more natural, because of the use of curly braces to denote enclosure of elements. And yet, your could easily write a translator that converts back and forth between a subset of XML and SDL. The examples above, using BeanShell, were, in my opinion, even more obscure than the XML versions. In addition, the code seems to expect each line to be a fully executable statement, which is going to make anything reasonable in terms of configuration even more awkward. HarishKrishnaswamy: Christian, I am not sure how you can construct the service from with the configuration file using simple closures. Could you elaborate? Howard, Beanshell is simply plain Java with some syntax sugar, so it is not necessary that every line should be an executable statement. I think the use of a scripting language is two-fold - make the config file smaller and simpler, and also simplify the framework internals. The SDL, although looks better than XML, still requires a lot of typing. HowardLewisShip: I think we can optimize the format somewhat; the SDL version is isomorphic to the XML version, but even the XML version could be made more succinct. We seem to be in a situation of declarative (SDL/XML) vs. procedural (scripting). To me, scripting opens up a whole can of worms ... and sacrifices one of the key features of HiveMind: line precise error reporting. Groovy builders are a step up from pure BeanShell statements but still miss the mark. I think HiveDoc will also suffer. I have nothing against something like: . . . invoke-factory (service-id=foo.bar.BeanShellServiceFactory) { script { << return new MyServiceImpl(. . .); >> } } . . . The << . . . >> syntax fills the same role as CDATA sections in XML ... everyting inside the delimiters is passed through as-is. I like the idea of scripting, but I like line precise error reporting much, much more. I also think scripting introduces further problems if and when there is tool support (the tool has to parse the script, which is not nearly so regular as the SDL or XML). HarishKrishnaswamy: Why do you think line precise error reporting has to be sacrificed with a scripting language? why something like the script above would n't work? With a scripting language the parser is already built, the tool will simply have to work with the AST (much simpler than working with the raw grammer). Yes, I could use a BeanShellServiceFactory, but I am still not seeing the benefit of SDL. HowardLewisShip: I must be, from ignorance, misunderstanding the while (!parser.Line()) { node = parser.popNode() ... } stuff. I was looking at that as "read a line, execute a line", but that's obviously not what it is doing. I'd be interested in seeing a real, formatted example, and more detailed notes about how line-precise error reporting is maintained. I'm not completely stubborn, but if you want to change my mind (especially considering who ends up doing the most work) you have to work really hard ... but when this has happened in the past, I will fully embrace the final solution (witness: implicit components, etc., in Tapestry 3.0 --- which started with a flame by Marc Fluery). IliaHonsali: I suggest to keep using xml for conf files, the main purpose of xml is to store data not to be easy to view, so, once hivemind come stable "someone" will make gui to mask the xml (with eclipse it'is easy), xml is also something usual that not scare newbies like me. HowardLewisShip: My current leaning is to allow multiple formats; the existing XML support, potentially the SDL format and the YAML format. However, the idea of linking up a scripting language is intriguing ... I just want the contingent that is pushing the idea to provide a full and viable solution. Meanwhile, out-of-band, EricHatcher pointed to an developerWorks article that really sums up the situation while raising (for me, at least) the question: who is this XML for: HiveMind, or . HowardLewisShip: JavaCC generates a token stream and each token knows it start and end line number and column. I think it will be much easier to support this than with XML. I suspect we'll be able to easily get that information out of the parser and into the plugin. Like Tapestry, a plugin shouldn't be all that necessary ... the SDL stuff takes the teeth out of XML, making it look quite pleasant. HarishKrishnaswamy: Ok, here's the same example with little more details. /** * Service point definition */ servicePoint("service-id", ServiceInterface.class); /** * Singleton service constructed via constructor injection */ singleton ( implementation ( "service-id", ServiceImplementation.class, new Object[] {1.34, "some string", service("some-service-id")} // constructor arguments ) ); /** * Pooled service constructed via setter injection */ dependencies = new HashMap(); dependencies.put("property1", property1Value); dependencies.put("anotherService", service("anotherServiceId")); pooled ( implementation ( "service-id", ServiceImplementation.class, dependencies // Setter properties ) ); This file will be read and built by a builder class that will look something like this: public class BshBuilder { ... public void buildModule(URL moduleUrl, Registry registry) { try { Interpreter interpreter = new Interpreter(); helper = new BshBuilderHelper(registry); helper.setCurrentModuleName(moduleUrl.toString()); interpreter.set("$helper$", helper); interpreter.eval("importObject($helper$)"); // This is a mixin command interpreter.eval("importCommands(\"path/to/evalModule.bsh\")"); interpreter.set("$interpreter$", interpreter); interpreter.set("$callstack$", new CallStack(interpreter.getNameSpace())); interpreter.set("$url$", moduleUrl); interpreter.eval("evalModule($url$, $helper$, $interpreter$, $callstack$)"); } catch (Exception e) { handleInterpreterException(e); } } ... } evalModule.bsh is the same script that I had posted previously. The BshBuilderHelper will look something like this: public class BshBuilderHelper { ... String _currentModuleName; int _currentLineNumber; public void servicePoint(String serviceId, Class serviceInterface) { Location location = new Location(_currentModuleName, _currentLineNumber); // Register the service point along with the location } public Object implementation(String serviceId, Class serviceImplementation, Object[] constructorArgs) { Location location = new Location(_currentModuleName, _currentLineNumber); // Register the service implementation along with the location return service; } public Object service(String serviceId) { // Get service return service; } public Object singleton(Object service) { // Make service a singleton return service; } ... } BshBuilder receives the module descriptor sets up the BeanShell interpreter by mixing in the BshBuilderHelper object and executes the evalModule script. The evalModule script reads the module descriptor one statement at a time, sets the line number of the executing node in the helper, and executes it. The helper does the needful. And that's pretty much all for handling the descriptors. Of late, I have really subscribed into KISS and Enabling Attitude principles and these ideas are simply a repercussion of that. KnutWannheden: Harish, your example is IMO getting very close to a purely descriptive form (like the SDL or XML approach). Of course someone could (ab)use the BSH design to write an absurdly cryptic module descriptor. This is where I gather you say the Enabling Attitude principle comes in to play. IMO the only thing with the XML descriptor which doesn't conform to this principle is the XML syntax itself, and that's what SDL should solve. But then again with the plethora of XML processing / spewing tools I think XML also has some nice advantages. Also I think one of the main purposes of using a descriptive syntax is to make the descriptor itself readable. And, as previously noted, if users put arbitrary Java code into the descriptor I think it could prove difficult for HiveDoc to produce something useful. HarishKrishnaswamy: Couple things I forgot to mention: Producing HiveDoc is just as simple because the comments could be a part of the AST and we could annotate them for HiveDoc. And secondly, with this approach I don't think we need a special tool like Spindle for the descriptors; the eclipse scrapbook page is good enough, IMO. I certainly like the SDL far better than XML for reasons I have already mentioned, but my point of using scripting language was to save us the trouble of creating another language and make it more easily adoptable. If I were new to HiveMind, I wouldn't want to worry about the schema and factory and friends. I would simply want to say here's my service point and here's the implementation, you do your thing and get me the service. Or here's the configuration point and here's all the contributions. Don't get me wrong, I still like all the concepts in HiveMind, its just the usage And just to make it clear, there are no flames here! ColinSampaleanu: I don't know if you're looking for outside opinions, but I hate the idea of inventing a new format like SDL. I agree it's a a bit cleaner and easier to type than XML, but ultimately it doesn't seem to me the gain is that great that it makes up for the fact that it's completely proprietary and nobody is able to leverage the work of anybody else (i.e. other tools able to read the same format). For this reason, YAML or even a scrpting solution like Groovy or BeanShell are preferable to me, along with XML which should remain a standby. ChristianEssl: I like BeanShell more and more. Especially Harish's format looks quite readable and the Eclipse support is especially cool. What I still don't like is the way of constructing service-impl. As said it's not only unconvinient but also prevents the use of other ServiceImplementationFactories. I'd like to see this happen through a script as well. Sorry that I did not respond to the closure question, but I was thinking of a solution and I've now at least an idea how it maybe could work: Instead of giving the implementation method a map or array, it should be given the name of a method defined in the script. The method would have the same signature and the same function as ServiceImplementationFactory.createCoreServiceImplementation. Now the implementation() method would look up the corresponding BshMethod serialize it and store it (encoded) in an Element. Than it would setup the implementation-descriptor so that a special BeanShellServiceImplementationFactory is called with the Element as parameter. During runtime the Factory would just take the BshMethod (cache it) and execute it. (This means of course that the method is not executed in the context of the descriptor-script - so it's not a closure). I think a similar aproach could be used for interceptors. Beside of this I like BeanShell, because I think most of the verbosity of xml-descriptors for containers (not only for HiveMind) comes from cut-and-paste for common tasks. Ie if you want to add a logging interceptor to five services you have to type the whole implementation stuff 5 times where only the service-id changes. Compare this with BeanShell where you just define a method (in a lib) and pass it an array of service-ids. DieterBogdoll: To be honest, I don't understand the necessity for a SDL. But if you all need them its okay for me. But I think it is utmost important to keep XML as a configuration mechanism. Mike Henderson: I've been looking hard at Groovy and Groovy Markup gives you something like SDL without having to write a parser. I've implemented a builder class for connecting beans together with Groovy Markup: HowardLewisShip: I'm not saying that you can't build beans using the scripting language of your choice. I'm simply saying that doing so, you may lose some of the benefits of HiveMind. HiveDoc, for starters. Line precise error reporting, potentially. And it adds to the dependencies. I'd certainly endorse the idea of an add-on library to let you use scripting if that's your way, but I don't want to see the core of HiveMind screwed just to support scripting, which only some people think is the One True Path. SteveGibson: For us, we use a lot of XML already, so being able to keep XML for me is very important. A lot of people are saying they don't want to invent a new language - SDL. Well, to me, this looks a lot like IBMs Stanza format, used in AIX forever, and also the configuration format a company I used to work for came up with - purely because you specify the object you want to create and assign the properties. I think the SDL is very readable, and would probably use it if we didn't already use lots of XML files and *gasp* properties files. NareshSikha: I hope that the bulk of Hivemind Services and Configurations are written by junior developers who are more concerned about their resume than the strength of the architecture they are fulfilling. This will afford more time for architects and leads to solve the interesting problems. Therefore I think tools should be delivered to help developers author valid module definitions (Eclipse plugins are a good starting point). Then the details of the definition are more or less irrelevant. Barring that, please, please, give junior developers a chance to strengthen their resume by allowing for industry standard means for communicating metadata (XML). AchimHuegen: Now that I worked with SDL I would like to share my opinion: I don't think the benefit of SDL is big enough to counter-balance the disadvantages. The main differences to XML are the use of curly braces instead of start and end tags and the way of quoting. The use of braces enhances readability on the one hand but reduces it on the other hand for larger files. Apparently the verbose xml format is sometimes even helpful. I couldn't resist to quote the main hivemodule.sdl, sorry howard : {{{ } // element construct - } // parameters-schema }}} Use of quotation marks is simply inverted, which could be a bit confusing: XML: <bean name="bean2"> <string>testValue2</string> </bean> SDL: bean (name=bean2) { string { "testValue2" } } The differences are subtle but must be learned by developers. Furthermore, there are still some open questions like encoding (character sets). I think, the main problem behind "too much xml" is not the xml format itself, but the definition of verbose schemes and the shifting of programming logic to xml files. The definition of proprietary formats by each library is no solution for these problems. MicahSchehl: XML is great because of it's wide acceptance-- but it is difficult to read and I am often overwhelmed with XML I am not familiar with. I would like to see a project which aims to allow anyone to use syntax that they desire for configuration files. The project would interpret the config file and generate the XML that so many other projects expect. The generation could be done at compile time (generate XML files) or at runtime (SAX events). The project could have default interpreters such as JavaScript or SDL. This is just my first thoughts on this. RichardClark: BeanShell looks like a fairly dangerous choice, IMO. Both of its licenses (LGPL or Sun's community license) create interesting problems for the deployer in a commercial environment (the LGPL pushes you to set up a source code distribution mechanism, while Sun's license carries detailed documentation requirements to keep the lawyers happy); this could be a show-stopper to adoption in many places. SDL or XML might make a developer work harder to learn HiveMind, but the wrong license will get the lawyers to kill HiveMind's usage cold.
http://wiki.apache.org/hivemind/NotXMLProposal?highlight=BeanShell
CC-MAIN-2014-52
refinedweb
3,727
54.52
-17-2012 08:02 PM hi, i had some questions reg some ucf constraints. if i interface an fpga device (say xc5vsx50t) with some external device (like a zbt sram), then how can i decide if the UCF constraint slew should FAST or SLOW for an o/p pin? is there any particular value, feature, rate, etc. that I can look for in the datasheet of the external device that can tell me if slew should be FAST or SLOW? the sram works from 160 to 200MHz. also, the zbt sram i have has operating voltage of 2.5 to 3.3v. so in this case, as per the levels, i can use the iostandard of lvttl or lvcmos25 ... so can i use either or is there some restriction on when to use which iostandard? lastly, how can i decide what the drive strength of the o/p pin should be? this drive strength should correlate to which value of the external device so that the current matches and the device can work properly? Do let me know if there are any particular rules to decipher which constraint goes where and gets what value ...? Thanks and regards, Z 12-18-2012 05:44 AM - edited 12-18-2012 05:49 AM Before I answer this I will qualify myself by saying that what follows shouldn't be taken as gospel :) SLEW RATE Choosing the slew rate for your signal will be largely dependent on what frequency your data is being transmitted at. You don't want the rise/fall time of the data to be in the same order of magnitude as the data period. Does the ZBT RAM datasheet indicate what slew rate it has (or expects) on its data? You should aim to match it. HOWEVER - having too many FAST slew rate pins in one bank may lead to SSO (simultaneous switching output) noise issues in the device, You should check the FPGA datasheet for allowable maximums. IOSTANDARD Again, in general, this is dependent on what you are interfacing to. If you are transmitting/receiving data from an LVTTL source, you should match it. I would have expected a RAM to be LVCMOS but then perhaps the RAM datasheet will tell you more. DRIVE STRENGTH Drive Strength will be dependent on the line impedance of your data. If you are driving a signal across the board or trying to source illuminate an LED, you may need to up the strength. If you have very short tracks, like a parallel connection to a RAM could be, you may not need such high strength. The higher the drive strength, the more overshoot and ringing you may find on your signal. My experience with this is that it is experience-based. However you calculate it, you'll need to verify it on the board anyway so take your best guess, measure it and change it if necessary. Also note that SSO noise (as mentioned above) can be affected by too many high strength outputs. Again, check the FPGA datasheet for allowable maximums. Hope this helps (or helps someone more knowledgeable than me correct my mistakes!). Regards, Howard 12-18-2012 06:03 AM I'd just like to add that slew rate, drive stength, and IO standard all affect the interface timing. The device data sheet has a table of delay "adders" for each IO standard, drive strength, slew rate combination. These will give you an idea of how each parameter affects timing. Simultaneous switching issues are more pronounced with faster slew rate, higher interface voltages, and higher drive strength. Luckily Virtex 5 parts are packaged such that even at the fastest edge rates the SSO issues are minimised. This may not be the case in cheaper devices which are typically in packages with more lead inductance. If you're using a source-synchronous interface (FPGA drives clock and data to the RAM), then keeping the settings the same for all outputs will keep the skew at a minimum, and you may be able to use slower slew rates or lower drive strength because of the matching "adder" delays. Usually in a memory interface, it's the return (read data) data path where you run into problems with high-speed sampling. This is much more likely to determine the required output speed of the interface, because now the delays are additive. Again you may be able to use a slower output speed if your logic has a dynamic sampling point adjustment like the MIG core, which calibrates out the external round trip delays. -- Gabor 12-18-2012 07:59 AM hi hgleamon1, thanks for your reply. for iostandard and drive strenght, i can understand that it is experience based and can vary. i.e if the voltage level of the peripheral device is from 2.5v to 3.3v, we can use either lvcom or lvttl. and so on for the drive strength too, depending on trace length, impedence etc. however, i am more concerned about slew rate. as i mentioned in my original post, the only factors i've seen in the peripheral device datasheet are rise/fall time - around 1 - 2 ns and setup and hold times - around 5 ns. and the device itself works at 200MHz (max). so would this need a FAST slew rate or a SLOW slew rate? (i guess fast) upto what rise time/fall time, should i take the slew rate to be slow and above that, a slew rate of fast? will it depend on riste/fall time or setup/hold time or some other factor? as such, in the datasheet i have, there is nothing special that specifies the device slew rate as such ... do let me know ... thanks for any other inputs ... 12-18-2012 08:38 AM First up: DS202 is the DC and switching characteristics for Virtex 5. Choose your IOSTANDARD and then look through the tables on, for example, page 32 for details of SLOW and FAST slews for your devices speed grade. Think about what I and Gabor wrote and apply your best judgement. On an additional note: If the RAM is powered by a given voltage (let's say 3.3V), I suggest that you power your RAM interface by the same voltage. If the RAM can handle LVTTL, then that could be a suitable IOSTANDARD. If the RAM only accepts LVCMOS, then you should probably pick that IOSTANDARD. How could you select an IOSTANDARD otherwise? Also note that, once you have picked an IOSTANDARD for a bank, EVERY pin of that bank must be the same IOSTANDARD. Regards, Howard 12-18-2012 09:22 AM . 12-18-2012 09:25 AM @bassman59 wrote: . Ah, yes. Thanks for that. Good spot. 12-18-2012 10:26 AM Regarding the choice of LVTTL or LVCMOS, there is no real difference for FPGA outputs, LVTTL outputs drive to the rails just like LVCMOS. The main difference is in the input voltage thresholds, which in the case of LVTTL are not relative to Vcco, and can be quite asymmetric as the bank voltage gets lower. For a high-speed interface, the slew-time can be a significant portion of the clock to output delay, and you need to be careful that the input logic threshold doesn't add too much additional time as in the case of LVTTL with 2.5V Vcco, where the high logic threshold becomes close to the positive rail. I would suggest reading the fine data sheet from the memory chip, and see what the test conditions are when they report output timing. Most likely they will have a diagram that shows the threshold levels used for the reported timing values. -- Gabor
https://forums.xilinx.com/t5/General-Technical-Discussion/reg-ucf-file-constraints/m-p/281302
CC-MAIN-2019-13
refinedweb
1,287
71.04
NAME ng_ipfw - interface between netgraph and IP firewall SYNOPSIS #include <netgraph/ng_ipfw.h> DESCRIPTION The ipfw node implements interface between ipfw(4) and netgraph(4) subsystems. HOOKS The ipfw node supports an arbitrary number of hooks, which must be named using only numeric characters. OPERATION Once the ng_ipfw module is loaded into the kernel, a single node named ipfw is automatically created. No more ipfw nodes can be created. Once destroyed, the only way to recreate the node is to reload the ng_ipfw */ struct ifnet *ifp; /* interface, for ip_output */ int dir; /* packet direction */ #define NG_IPFW_OUT 0 #define NG_IPFW_IN 1 int flags; /* flags, for ip_output() */ }; Packets received by a node from netgraph(4) must be tagged with struct ng_ipfw_tag tag. Packets re-enter IP firewall processing at the next rule. If no tag is supplied, packets are discarded. CONTROL MESSAGES This node type supports only the generic control messages. SHUTDOWN This node shuts down upon receipt of a NGM_SHUTDOWN control message. Do not do this, since the new ipfw node can only be created by reloading the ng_ipfw module. SEE ALSO ipfw(4), netgraph(4), ipfw(8), mbuf_tags(9) HISTORY The ipfw node type was implemented in FreeBSD 6.0. AUTHORS The ipfw node was written by Gleb Smirnoff 〈glebius@FreeBSD.org〉.
http://manpages.ubuntu.com/manpages/karmic/man4/ng_ipfw.4freebsd.html
CC-MAIN-2015-22
refinedweb
211
64.51
IRC log of ws-addr on 2006-10-23 Timestamps are in UTC. 19:49:52 [RRSAgent] RRSAgent has joined #ws-addr 19:49:52 [RRSAgent] logging to 19:50:08 [bob] zakim, this will be ws_addrws 19:50:08 [Zakim] I do not see a conference matching that name scheduled near this time, bob 19:50:36 [bob] zakim, this will be ws_addrwg 19:50:36 [Zakim] ok, bob; I see WS_AddrWG()4:00PM scheduled to start in 10 minutes 19:51:00 [bob] Meeting: Web Services Addressing WG Teleconference 19:51:04 [David_Illsley] David_Illsley has joined #ws-addr 19:51:11 [bob] Chair: Bob Freund 19:52:17 [TonyR] TonyR has joined #ws-addr 19:53:14 [Dug] Dug has joined #ws-addr 19:53:44 [Zakim] WS_AddrWG()4:00PM has now started 19:53:51 [Zakim] +Doug_Davis 19:55:46 [Zakim] +Bob_Freund 19:56:02 [Zakim] +??P4 19:56:22 [TonyR] zakim, ??p4 is me 19:56:22 [Zakim] +TonyR; got it 19:56:37 [TonyR] zakim, who is on the phone? 19:56:37 [Zakim] On the phone I see Doug_Davis, Bob_Freund, TonyR 19:56:41 [Zakim] + +44.196.286.aaaa 19:57:06 [bob] agenda: 19:57:08 [David_Illsley] zakim, +44.196.286.aaa is me 19:57:08 [Zakim] +David_Illsley; got it 19:57:48 [Dug] How do i tell zakim to list me as "Dug" instead of "Doug_Davis" ? 19:58:15 [Zakim] +??P6 19:58:25 [Dug] zakim, Doug_Davis is Dug 19:58:25 [Zakim] +Dug; got it 19:58:28 [Dug] cool - thanks! 19:58:38 [pauld] pauld has joined #ws-addr 19:58:38 [MrGoodner] MrGoodner has joined #ws-addr 19:58:57 [bob] zakim, cool - thanks! 19:58:57 [Zakim] I don't understand 'cool - thanks!', bob 19:59:18 [Zakim] +Mark_Little 20:00:25 [Zakim] +Gilbert_Pilz 20:00:42 [Zakim] +[Sun] 20:00:46 [agupta] agupta has joined #ws-addr 20:00:48 [gpilz] gpilz has joined #ws-addr 20:01:05 [Zakim] +Tom_Rutt 20:01:35 [plh] plh has joined #ws-addr 20:02:00 [prasad] prasad has joined #ws-addr 20:02:06 [Zakim] +Plh 20:02:06 [TRutt_] TRutt_ has joined #ws-addr 20:02:22 [PaulKnight] PaulKnight has joined #ws-addr 20:02:38 [Zakim] +Paul_Knight 20:02:45 [agupta] zakim, [Sun] is me 20:02:45 [Zakim] +agupta; got it 20:02:58 [anish] anish has joined #ws-addr 20:03:13 [plh] zakim, ??p6 is MarcG 20:03:17 [Zakim] +MarcG; got it 20:03:35 [Zakim] +Anish_Karmarkar 20:03:49 [Zakim] +Paul_Downey 20:04:16 [Zakim] +Prasad_Yendluri 20:04:39 [bob] Observer+ Doug Davis (IBM) 20:04:45 [Zakim] +[IBM] 20:04:55 [Paco] Paco has joined #ws-addr 20:05:35 [Zakim] +[IPcaller] 20:05:52 [David_Illsley] zakim, mute me 20:05:52 [Zakim] David_Illsley should now be muted 20:06:27 [dorchard] dorchard has joined #ws-addr 20:06:36 [pauld] zakim, IPcaller contains Katy 20:06:36 [Zakim] +Katy; got it 20:06:48 [Zakim] +Dave_Hull 20:06:52 [dhull] dhull has joined #ws-addr 20:06:58 [Katy] Katy has joined #ws-addr 20:08:19 [bob] scribe David Hull 20:08:26 [anish] Scribe: dhull 20:08:28 [bob] scribe: David Hull 20:09:16 [dhull] bob: One item not on agenda: I have been asked by Policy chairs about potential of joint task team for working out policy assertions for WSA 20:09:35 [dhull] bob: Today's proposal moves in that direction. 20:10:02 [anish] q+ 20:10:11 [dhull] philippe: Will this slow us down? 20:10:14 [dhull] bob: Don't know 20:10:55 [dhull] anish: Seems like good idea. Had some discussion with UsingAddressing. Say it can be used as a policy assertion. Shouldn't take long to come up with such an assertion, as we already have something ready. 20:11:11 [dhull] Anish: Can also say that XMLP has been asked for similar effort regarding MTOM 20:11:27 [dhull] Bob: how about drafting one and throwing it over the fence for review? Or should we work jointly? 20:11:47 [dhull] Dhull: Prefer throwing it over the fence. 20:12:01 [dhull] Bob: There being no objection, let's take that tack. 20:12:22 [dhull] Bob: No addtions to agenda; agenda stands as is. 20:12:32 [anish] q- 20:12:33 [TRutt_] q+ 20:12:40 [dhull] Bob: Approval of minutes. Any objections? 20:13:03 [dhull] Tom: Editorial error in header number in issue number (same in both headers). Is this important? 20:13:20 [dhull] Bob: Will check before posting. Other issues? 20:13:31 [bob] ack tru 20:13:38 [dhull] Bob: I will review minutes then post them. 20:14:06 [dhull] Bob: AIs (beyond constant plea for more WSDL testers -- speak right up ...) 20:14:10 [dhull] Omnes: Dead silence 20:14:18 [dhull] Bob: AI Tony to complete table. 20:15:44 [dhull] Tony: Working on it. [gives an example referencing instead of copying rule 5]. Noting that faults may be returned even when anon is prohibited if headers aren't proceesed yet. 20:16:24 [dhull] Bob: New issues: Wanted to raise possibility of generating primer/FAQ. What do folks think? 20:16:38 [dhull] Crickets: Chirp, chirp 20:17:07 [dhull] Gil: Sounds like a good idea. I've had to explain WSA to customers in past, what it is, what it solves. Would be useful. 20:17:16 [dhull] Bob: Who would write it. 20:17:27 [dhull] Katy: Great idea, but it will be hard to get someone to find time. 20:17:32 [dhull] MGoodner: WOuld not have time. 20:17:49 [dhull] Arun: Very good idea. Have blogged about it, but do not have time. 20:17:53 [pauld] sent my 2p worth to the list: 20:18:03 [gpilz] I could spend some time on a WS-A primer 20:18:22 [dhull] Bob: Arun, is there anything you've already done you could contribute? 20:18:29 [dhull] Arun: Could send it later this week. 20:19:02 [dhull] Bob: Gil, could you look it over and get scope of effort? 20:19:04 [dhull] Gil: Yes 20:19:22 [dhull] Bob: Good. At least want to stop questions to "Guru" about where to send faults. 20:19:51 [dhull] Bob: Now to the main event, CR33. 20:20:09 [dhull] Bob: When we left off we were discussing Paco & Anish's proposal. 20:20:42 [Zakim] +DOrchard 20:20:54 [dhull] Paco: Simple proposal for A6 on our list. Requires no changes to core, just cover anon assertion in WSDL. 20:22:09 [dhull] Paco: There are two proposals. We prefer option 1. Three options: WSA fully supported, WSA supported but all responses over backchannel, WSA supported but no backchannel responses. 20:22:33 [dhull] Paco: We assume backchannel exists and is identifiable for some transports. 20:22:56 [dhull] Paco: Option 1: Get rid of wsaw:Anonymous and wsaw:UsingAddressing 20:22:59 [yinleng] yinleng has joined #ws-addr 20:23:25 [dhull] Paco: Option 2: Keep wsaw:UsingAddressing, default is fully supported, options for other tow possibilities. 20:24:04 [Zakim] +??P19 20:24:11 [yinleng] zakim, ??p19 is me 20:24:11 [Zakim] +yinleng; got it 20:24:24 [dhull] Anish: Wanted to reiterate that this is quite in line with WS-Policy request. Also, had some suggestions for names but didn't converge. We can always discuss this. Better suggestions welcome. 20:24:48 [dhull] Bob: We can always talk about names separate from concept. What do people feel about concept. 20:25:08 [dhull] Pins: Drop noisily 20:25:21 [dhull] Bob: Does this completely resolve CR33? 20:25:29 [dhull] Anish: We think so. 20:25:51 [dhull] Bob: How do we reconcile this with string compare wording in core spec? 20:25:52 [pauld] zakim, who is noisy? 20:26:01 [dhull] someone has a speakerphone on 20:26:09 [dhull] Anish: Looking ... 20:26:09 [Zakim] pauld, listening for 11 seconds I heard sound from the following: Anish_Karmarkar (16%), [IBM] (42%), DOrchard (25%) 20:26:14 [dhull] Paco: Need to refresh memory 20:26:15 [bob] zakim, whi is making noise 20:26:15 [Zakim] I don't understand 'whi is making noise', bob 20:26:18 [pauld] zakim, who is noisy? 20:26:26 [Dug] q+ 20:26:33 [Zakim] pauld, listening for 10 seconds I heard sound from the following: 19 (19%), Bob_Freund (95%), DOrchard (28%) 20:26:40 [anish] q+ 20:27:09 [dhull] Dug: THink the string compare is orthogonal issue. Paco's proposal just says "however you determine it, this tells you whether you can". 20:27:29 [dhull] Paco: Can't recall anything relevant to stirng compare (?) 20:27:34 [pauld] zakim, who is noisy? 20:27:42 [bob] ack dug 20:27:49 [bob] ack anish 20:27:50 [Zakim] pauld, listening for 11 seconds I heard sound from the following: Anish_Karmarkar (86%), DOrchard (12%) 20:28:11 [dhull] Anish: I agree with dug and paco. I assume you're talking about 3.2.1 that says that comparing address is just a string compare. Don't think that's relevant because we're talking about backchannel, not anon. 20:28:13 [dhull] q+ 20:28:30 [dhull] Anish: THis marker means service has this capability. 20:28:37 [bob] ack dhull 20:28:42 [dorchard] zakim, who is noisy? 20:29:00 [Zakim] dorchard, listening for 10 seconds I heard sound from the following: Bob_Freund (0%), Dave_Hull (90%), DOrchard (28%), Plh (0%) 20:29:05 [bob] Dhull: not passionately against this proposal, but feels that the ground is a bit slippery 20:29:29 [pauld] mute, dorchard 20:29:30 [dorchard] zakim, mute me 20:29:30 [Zakim] DOrchard should now be muted 20:29:56 [Paco] q+ 20:30:50 [bob] Dhull: made a proposal to have a way to place information in the address field to mark as to purpose 20:31:10 [bob] dhull: use regex to recognize the uri 20:31:32 [bob] q? 20:32:14 [bob] Dhull: "backchannel" creates a bit of problem of scope 20:32:54 [dhull] Paco: Responding to question about "what does backchannel mean". Shouldn't be a problem. Everyone knows what it means for HTTP. It should be part of defining a binding for a transport to be used with WSA. 20:32:55 [Zakim] -Mark_Little 20:33:02 [dhull] would be nice to have a non-HTTP example 20:33:30 [dhull] Bob: Would this work for you, Dug? 20:33:53 [anish] q+ 20:34:05 [dhull] Dug: Looks like either would work. Not sure about David's, need to grok it. Would probably work. Leaning toward Paco's 20:34:06 [bob] ack paco 20:34:11 [bob] ack anish 20:34:40 [bob] +1 as to scheme attribute 20:35:13 [dhull]. 20:35:36 [MrGoodner] q+ 20:35:46 [bob] ack mrg 20:36:10 [dhull] MGoodner: Wondering if nested assertions were considered. E.g., backchannel as sub-assertion of WSA supported. 20:36:42 [dhull] Anish: Did consider it. Don't remember details of why we ended up thinking that independent assertions would be better. 20:37:40 [dhull] Paco: Was some discussion. Recommendation of Policy was either fully nested, or capture meaning at top level so intersection was more meaningful. This is WS-Policy best practice. Mark, do you see an advantage to nesting? 20:38:06 [dhull] MGoodner: Not yet, but these seem like further qualifications of WSA supported. But only had time for a quick look. 20:38:37 [dhull] Paco: Actually option 2 is very much along those lines. Would leave using addressing, other markers qualify them. Marker also remains in WSDL (independent of policy). 20:39:01 [dhull] MGoodner: Do policy guidelines talk about whether nesting would be appropriate? 20:39:16 [dhull] Paco: DOn't know. Separate assertions seemed better. 20:39:37 [dhull] Bob: Is this general direction something folks are comfortable. 20:39:44 [dhull] Tony: Can live with it? 20:39:53 [dhull] ?: Option 1 or option 2? 20:39:59 [dhull] Bob: General direction. 20:40:08 [anish] s/\?/Dug/ 20:40:58 [dhull] Bob: Am I correct in understanding that WSDL marker gives general control, policy can give finer control. 20:41:15 [dhull] Anish: Thought we were using same tack as before. These can be either WSDL or policy assertions. 20:41:30 [dhull] Paco: THink people will move to policy, but this allows for grandfathering 20:41:39 [dhull] Bob: So we mirror in either WSDL or Policy 20:41:41 [dhull] Anish: Yes 20:41:54 [dhull] Bob: So given sub-options here, which way do we go? 20:42:13 [dhull] Bob: (Looking at Paco's most recent email) 20:42:23 [dhull] Bob: Paco, what do you recommend 20:42:43 [dhull] Paco: Option 1 is much cleaner. Doesn't split between WSDL and policy. Can still use WSDL markers 20:43:14 [bob] 20:43:14 [anish] 20:43:38 [MrGoodner] q+ 20:43:45 [David_Illsley] MGoodner, Warning against nesting: Last sentence of 20:43:47 [bob] ack mrg 20:44:04 [dhull] MGoodner: Policy assertions only without WSDL markers? 20:44:42 [dhull] Paco: Email just proposed three policy assertions. May be WSDL markers. May use just policy or just WSDL. Helps people who don't yet support policy. I'm OK with that. 20:44:46 [dorchard] q+ 20:44:53 [dorchard] zakim, unmute me 20:44:53 [Zakim] DOrchard should no longer be muted 20:45:04 [dhull] Bob: This would move us back to LC, right? 20:45:20 [dhull] Philippe: Yes, it would. 20:45:30 [bob] ack dorc 20:45:41 [dhull] DaveO: Does this marker appear any place UsingAddressing can be used? 20:45:45 [dhull] Paco: Yes 20:45:48 [MrGoodner] q+ 20:45:56 [dhull] DaveO: Effectively, take any place UA is used and put this in 20:46:00 [bob] ack mrg 20:46:00 [dhull] Paco: Yes, you can. 20:46:18 [dhull] MGoodner: What would be impact of using option 2, additively? STill LC? 20:46:41 [dhull] Bob: You mean adding two add'l WSDL markers? 20:46:46 [dhull] Mgoodner: Right 20:47:07 [dhull] MGoodner: Does this change LC 20:47:18 [dhull] Bob: Design change, not editorial change 20:47:30 [dhull] MGoodner: E.g., could new elements go into new namespace? 20:47:37 [dhull] Bob: Maybe. Philippe? 20:47:57 [Katy] q+ 20:48:05 [dhull] Anish: Remove anon, add two new? 20:48:22 [dhull] Bob: Proposal is publish what we have, then publish 1.1 with addition in new namespace. 20:48:38 [dhull] MG: Was proposing keeping existing namespace, new namespace for new elements 20:48:49 [dhull] Anish: Remove wsaw:anon from existing namespace 20:48:58 [dhull] MG: DOn't know, just trying to understnd 20:49:16 [dhull] Anish: Either way ahve to get rid of wsaw:Anon. What would it mean to remove element and keep namespace? 20:49:22 [bob] ack katy 20:49:54 [dorchard] q+ to say that removing would be an incompatible change as there would be unexpected behaviour 20:50:20 [pauld] zakim, mute dorchard 20:50:20 [Zakim] DOrchard should now be muted 20:50:22 [dhull] Katy: Before we actually add these, should check for requirement. 20:50:41 [dhull] Katy: If we remove wsaw:anon, we will have a namespace change as there is interop issue 20:50:49 [bob] ack dorch 20:50:50 [pauld] zakim, unmute dorchard 20:50:51 [Zakim] dorchard, you wanted to say that removing would be an incompatible change as there would be unexpected behaviour 20:50:56 [Zakim] DOrchard was not muted, pauld 20:51:56 [dhull]) 20:52:00 [dhull] Anish: My concern to. 20:52:15 [dhull] Bob: Seems like breaking change to me. Pub rules would move us back to LC, new namespace. 20:53:02 [plh] q+ 20:53:04 [dhull]. 20:53:58 [MrGoodner] q+ 20:53:58 [MrGoodner] q+ 20:54:10 [bob] ack plh 20:54:15 [dhull] DaveO:. 20:54:36 [bob] q+ plh 20:55:10 [dhull] Anish: Taking it a bit further. We would wsaw:UA, two more qnames, not anonymous. Old version has US, anon. If you see wsaw:anon, newer QName, have older client, what should client assume? Full support? Backchannel? 20:55:59 [dhull] DaveO: Would be interesting set of use cases to run. Can't run through it in real time here. WOuld be useful experiment to try. Old/new client/server against various setting of the params. Can't see failure case off the top of my head. 20:56:12 [dhull] Bob: So if we propose it's a non-breaking change, show analysis. 20:56:19 [bob] ack plh 20:56:20 [dhull] DaveO: If it's a breaking change, show the break. 20:57:00 [dhull] Philippe: If we're introducing new elements, we should give other groups a chance to review, so we should go to LC. Not the end of the world. Can do CR stuff in the interim. 20:57:02 [bob] ack mrg 20:57:40 [dhull] MG: Analysis of whether it's a breaking change would be interesting. Believe we're using UA feature right now, so want to understand feature. IF there's a non-breaking way to keep it and add on, want to explore that. 20:58:15 [anish] q+ 20:58:26 [dhull] MG: IF there's a request from WSP to define assertion, if it wasn't a breaking change to lose anon etc., could't those assertions be defined there, not here? (i.e. in new document). Wasn't that th requeest. 20:58:29 [dhull] Bob: Not sure 20:58:36 [bob] ack anish 20:59:30 [dhull]. 21:00:03 [dhull] Katy: Could consider removing wsaw:Anon and keeping these markers. Would cause namespace change, but better for long term. 21:00:07 [dhull] Bob: Feels cleaner to me. 21:01:17 [dhull]. 21:01:58 [dhull] Bob: You've convinced me of need for more analysis with your earlier points. Need to run the scenarios. Also need to see if namespaces would get tangled. 21:02:18 [MrGoodner] q+ 21:02:35 [dhull] Bob: Is this the approach we need to solve CR33. Get the sense that option 1 is the way to go but need to do more legwork, analysis, due diligience on namespace issue. 21:02:36 [bob] ack mrg 21:03:10 [dhull] MG: Don't want to rule out option 2, as we're using UA currently. Want to understand analysis of possible breaking change. Wnat to compare option 1 vs. 2 here. 21:03:34 [dhull] MG: Also not sure whether it's appropriate to say backchannel without even mentioning anonymous. 21:04:18 [MrGoodner] q+ 21:04:37 [dhull]. 21:04:42 [bob] ack mrg 21:05:24 [dhull] MG: BUt that's not all of the opinions expressed. Some said that the extra URIs were not appropriate to begin with. Need to think it over more, wanted to air concern. 21:05:26 [Dug] if the URI is mentioned as an example then its ok but if its mentioned as the only URI then CR33 is not closed. 21:05:37 [Dug] s/closed/resolved/ 21:05:39 [dhull] Bob: P & A, are you willing to take this further. 21:05:59 [dhull] Anish: Need to talk about what kind of wordings we want, and the sort of analysis that DaveO mentioned. 21:06:14 [gpilz] you need to say somthing about what qualifies as "a backchannel" or you are just opening up a whole universe of interop problems 21:06:59 [Dug] "as defined by the transport" or something like that - but mentioning specific URIs doesn't address the issue 21:07:21 [dhull]. 21:07:23 [Dug] (I should say "mentioning" and "limiting the URIs") 21:07:55 [gpilz] q+ 21:07:56 [David_Illsley] gpilz, I'm not sure I agree, surely a client knows what backchannels are available to it? 21:08:18 [dhull] Dug: If we modify the proposal to say what "backchannel means" and it's just anon, we haven't addressed CR33. If anon is an example, that's fine. 21:08:24 [bob] ack gil 21:08:28 [dhull] (so who says if some other URI is backchannel?) 21:08:39 [bob] ack gp 21:09:18 [dhull] Gil: How does client evaluate "backchannel"? Client needs to know what server thinks it is. Otherwise it has to guess which URIs are OK. Has to be some way for client to figure out what this service will or will nto accept. 21:09:36 [dhull] Paco: This is a per binding/transport thing. You need to define a lot of things with a binding anywya. 21:09:58 [dhull] Gil: But if I'm using WSA anon I know what's up. But if I have some other URI, how do I know? 21:10:06 [anish] q+ 21:10:07 [dhull] Paco: IF you're using the URI you know what it means. 21:10:15 [dhull] Gil: I know what it menas, but not if it will be accepted. 21:10:32 [dhull] Paco: You know it means use the backchannel, and you know if that's OK. YOu have enough information. 21:10:38 [bob] ack ani 21:10:42 [Dug] Gil - wouldn't that be an RM issue? let RM define a policy assertion that says whether or not RManonURI is supported 21:11:00 [dhull] Anish: If you want that level of precision, then you may want option A8, which changes core, or DaveH's proposal. 21:11:05 [gpilz] dug - that's an idea 21:11:09 [dhull] Isn't RMAnon independent of transport? 21:11:31 [gpilz] q+ 21:11:31 [dhull] Anish: Want to leave core alone and leave what backchannel means to the binding. 21:11:40 [dhull] Bob: Meta-backchannel. Whatever it means to you. 21:11:51 [David_Illsley] gpilz, I was convinced earlier in the week that RM don't need a policy assertion as if it's supported there'll be a MakeConnection operation in the wsdl 21:12:17 [dhull] (missed something) 21:12:21 [bob] ack gpil 21:12:27 [Dug] david_I - true 21:12:37 [MrGoodner] q+ 21:12:52 [dhull] Gil: Inclined toward this approach of skirting the issue of what qualifies or not, but does it introduce interop problems? 21:13:11 [Dug] leave WSA simple and extensible 21:13:28 [dhull] Bob: A year or so ago we talked about what we meant by backchannel. Concluded that the transport knows what it is and it is what it is. This moves a step more clearly in this direction. 21:13:32 [bob] ack mrg 21:13:44 [Paco] q+ 21:13:57 [Dug] does the core spec already say Anon == backchannel? 21:14:36 [bob] ack paco 21:14:38 [dhull]. 21:15:44 [MrGoodner] q+ 21:16:25 [dhull],... 21:16:27 [dhull] ...or give assertions that have behavior behind them. WE give assertions. 21:16:34 [Dug] q+ 21:16:40 [bob] ack mrg 21:17:22 [dhull] MG: Would agree more if RM URI were limited to RM uses. But it isn't, according to RM CD, which is publically available. Assuming RM is engaged is a wrong assumption. There are proposals in front of TC that compose with using wsa anon. 21:17:22 [bob] ack dug 21:18:18 [MrGoodner] q+ 21:18:23 [gpilz] +1 to dug 21:18:46 [bob] ack mrg 21:18:53 [dhull]... 21:18:55 [dhull] ...what backchannel means. 21:19:27 [dhull] MG: So in WSA abstractly defining a marker that means backchannel, and WSA has defined anon, should we advice other specs to define a related marker for their URI. 21:19:56 [dhull] Dug: Not a hard requirement, but couldn't hurt, whether or not new special URI are anonymous in nature. 21:20:06 [dhull] MG: So how does none apply in this discussion of backchannel. 21:20:11 [dhull] Dug: It doesn't. 21:21:03 [MrGoodner] Are we back to wsaw:Anonymous again? 21:21:16 [dh. 21:21:23 [dhull] Bob: Sounds like primer material. 21:21:52 [dhull] Bob: Any more that we can fruiitfully hash out without going into next level of detail? 21:22:16 [dhull] Bob: A&P have next step to do. Do we want to keep option 2 on table? 21:22:38 [dhull] MG: Yes. Especially w.r.t. analyzing for breaking change 21:22:46 [dhull] Bob: Are you amenable? 21:23:04 [dhull] Bob: i.e. to keeping Option 2 on the table for analysis. 21:23:13 [dhull] Paco: THink that's fair. 21:23:20 [dhull] Anish: Fine with it. 21:23:56 [dhull] Anish: Would like to say that this analysis would be useful independent of backchannel issue, particularly since request was from WSP WG. 21:24:19 [dhull] Bob: So we are done with CR33 discussion for today. 21:24:52 [dhull] Bob: Or were any of the other options more attactive? 21:25:01 [dhull] Omnes: Nada 21:25:29 [dhull] Bob: AOB? 21:26:37 [dhull] Paco: When do we need to do this? 21:27:05 [dhull] Bob: Should have proposal out no later than Wed or Thu, otherwise call on 30 October would be a waste. 21:27:16 [dhull] Paco: Happy to send this out by then. 21:27:28 [dhull] MG: Should we give RX TC more time and come back in 2 weeks? 21:28:40 [dhull] Bob: I could describe this as a general direction. Next RX TC call is Thu. Would that be fruitful, if it's OK with them. So we can go ahead with 30 Oct. Would like to close CR33 soonest. 21:28:48 [dhull] Paco: Will have it out by Thu. 21:28:59 [dhull] Bob: Next call October 30. 21:29:15 [dhull] Tony: I have uploaded modified table for CR31, so we can discuss that. 21:29:22 [dhull] Bob: CR33 will impact the table 21:29:25 [dhull] Tony: THought it might. 21:29:47 [dhull] Bob: Adjourned 21:29:47 [Zakim] -MarcG 21:29:49 [Zakim] -agupta 21:29:49 [Zakim] -[IBM] 21:29:51 [Zakim] -Tom_Rutt 21:29:52 [Zakim] -DOrchard 21:29:54 [Zakim] -Gilbert_Pilz 21:29:55 [Zakim] -yinleng 21:29:56 [Zakim] -Anish_Karmarkar 21:29:57 [Zakim] -Paul_Knight 21:29:58 [Zakim] -David_Illsley 21:30:00 [Zakim] -TonyR 21:30:05 [Zakim] -Dug 21:30:06 [Zakim] -Dave_Hull 21:30:08 [agupta] agupta has left #ws-addr 21:30:08 [Zakim] -Bob_Freund 21:30:09 [Zakim] -Plh 21:30:13 [Zakim] -Prasad_Yendluri 21:31:53 [TonyR] TonyR has left #ws-addr 21:32:01 [yinleng] yinleng has left #ws-addr 21:32:31 [Zakim] -[IPcaller] 21:32:49 [bob] rrsagent, make logs public 21:33:25 [bob] rrsagent, generate minutes 21:33:25 [RRSAgent] I have made the request to generate bob 21:35:09 [bob] action: paco and anish to do a further analysis leaving open both options 1 and 2 with respect to breaking changes and namespace issues 21:35:28 [Dug] Dug has left #ws-addr 21:35:45 [bob] action: arun to publish what he has to the group as a starting point (possibly) for a primer 21:35:58 [bob] rrsagent, generate minutes 21:35:58 [RRSAgent] I have made the request to generate bob 21:38:23 [TRutt_] TRutt_ has left #ws-addr 21:38:44 [bob] action: bob to describe this general direction to the RX TC on the Thursday teleconference 21:38:52 [bob] rrsagent, generate minutes 21:38:52 [RRSAgent] I have made the request to generate bob 21:39:22 [bob] scribenick: dhull 21:39:31 [bob] rrsagent, henerate minutes 21:39:31 [RRSAgent] I'm logging. I don't understand 'henerate minutes', bob. Try /msg RRSAgent help 21:39:41 [bob] rrsagent, generate minutes 21:39:41 [RRSAgent] I have made the request to generate bob 21:44:36 [bob] bob has left #ws-addr 22:05:01 [Zakim] disconnecting the lone participant, Paul_Downey, in WS_AddrWG()4:00PM 22:05:02 [Zakim] WS_AddrWG()4:00PM has ended 22:05:06 [Zakim] Attendees were Bob_Freund, TonyR, +44.196.286.aaaa, David_Illsley, Dug, Mark_Little, Gilbert_Pilz, Tom_Rutt, Plh, Paul_Knight, agupta, MarcG, Anish_Karmarkar, Paul_Downey, 22:05:08 [Zakim] ... Prasad_Yendluri, [IBM], Katy, Dave_Hull, DOrchard, yinleng 23:41:29 [Zakim] Zakim has left #ws-addr
http://www.w3.org/2006/10/23-ws-addr-irc
CC-MAIN-2014-35
refinedweb
4,845
72.97
Reporting logical disk information for live serversWilliam L. Thomas, Jr. May 25, 2012 2:38 PM I am trying to create a report based on the "file server" information collected from a live server browse. The information I need to collect is: 1) Server Name 2) Drive Letter 3) Logical Drive Name 4) Total Logical Volume Size 5) Total Logical Volume Free Space All the information I need can be found when I browse a live server but I cannot find a way to collect the information. You cannot Audit "File System" in the live server browse (only the objects under "File System") and I cannot find a blcli command or commands that would get me the information (e.g. such as a GetFilSystemInfo command under the Server namespace). I am flummoxed. Any help or guidance will be greatly appreciated. 1. Re: Reporting logical disk information for live serversSean Berry May 25, 2012 2:41 PM (in response to William L. Thomas, Jr.) Can you get this from the Hardware object? (I think so) 2. Reporting logical disk information for live serversWilliam L. Thomas, Jr. May 25, 2012 4:19 PM (in response to Sean Berry) D'oh! I looked under "File System" and saw that I could not use that and immediately started trying to write a blcli script to gather the information (which was not successful). Never even occurred to me to look under "Hardware". My bad. I can create a job to gather the information I need from there. Although this does answer my question, I am still a bit curious if this can be done using the blcli. Nothing to burn too many brain cycles on but since I tried and was unsuccessful, I am just wondering if it is even possible. 3. Re: Reporting logical disk information for live serversGerardo Bartoccini May 28, 2012 7:37 AM (in response to William L. Thomas, Jr.) The only thing you can get out of a server by means of blcli is properties, if I understand your question. For all the rest, you can’t use blcli. Part of the server inventory information is available by means of blquery. Not sure you can get what you need though. From Hardware Information you can get Logical Disk information, and snapshot it so you can build reports, without any needs of scripting. HTH
https://communities.bmc.com/thread/67130
CC-MAIN-2016-44
refinedweb
393
71.34
#include <wx/richtext/richtextbuffer.h> A class representing a rich text object border. colour. Gets the colour as a long. Returns the border flags. Gets the border style. Gets the border width. True if the border has a valid colour. True if the border has a valid style. True if the border has a valid width. True if the border has no attributes set. True if the border is valid. Set the valid flag for this border. Equality operator. Removes a border flag. Removes the specified attributes from this object. Resets the border style, colour, width and flags. Sets the border colour. Sets the border colour. Sets the border flags. Sets the border style. Sets the border width. Sets the border width.
https://docs.wxwidgets.org/3.0/classwx_text_attr_border.html
CC-MAIN-2018-51
refinedweb
122
90.77
Introduction to ES6 Interview Questions and Answers Now, if you are looking for a job that is related to ES6 then you need to prepare for the 2020 ES6 Interview Questions. It is true that every interview is different as per the different job profiles but still to clear the interview you need to have a good and clear knowledge of ES6 processes. Here, we have prepared the important ES6 Interview Question and answers which will help you get success in your interview. ES6 is referred to as ECMAScript with version 6 was released in the year 2015. ECMAScript is defined as the scripting language that has been standardized by ECMAScript international. ECMAScript is the proper name of the language that is mainly referred to as JavaScript. It has been mainly used as the client-side server scripting language. It has been released with a lot of features that make the language more flexible and extensive. ES6 is still not having all the browser support. These questions are divided into two parts are as follows: Part 1 – ES6 Interview Questions (Basic) This first part covers basic ES6 Interview Questions and Answers Q1. Define ES6 and mention the new features of ES6? Answer: Refer to the introduction part for the definition of ES6. Below are the new features listed: - Constants (Immutable variables) - Scoping - Arrow functions - Extended parameter handling - Template literals - Extended literals - Modules - Classes - Enhanced Regular expressions - Enhanced object properties. - Destructuring Assignment - Symbol Type - Iterators - Generator - Map/Set & WeakMap/WeakSet - Typed Arrays - Built-in Methods - Promises - Metaprogramming - Internationalization and Localization. Q2. How do you use ES6 or the best way to use ES6 in a project? Answer: As it is mentioned that ES6 is not supported by all the browsers, so to use ES6 script we need to convert into the ES5 script which is supported by all the browsers. To convert into a pre-ES6 script, we required transpilers like Babel. Babel is a popular javascript transpiler used for this purpose, which allows ES-6 code to convert into an ES-5 script to support by all the browsers. Let us move to the next ES6 Interview Questions Q3. What are Constants in ES6? Answer: Constants are also referred to as Immutable variables. It means that the value of a constant variable cannot be changed. The value that has been assigned at the time of the declaration remains unchanged. For e.g. const X= 5.0, here the value of X remains 5 every time and it cannot be changed. Q4. What are Block Scoped variables and functions? Answer: This is the common ES6 Interview Question which is asked in an interview. The variables and functions are defined as indefinite blocks. It means these can be used where the variables and functions are defined or declared. If we have declared variable and function in any function block then their scope will be limit to that function only, they cannot be accessible outside the block/function. ‘Const’ keyword cannot change the value of a variable. ‘let’ keyword allows variable value to be re-assigned, it can be in for loop or arrays. Q5. Explain briefly about Arrow functions? Answer: Arrow functions support expressions bodies and statement bodies which returns the value of an expression and makes the syntax more expressive. Arrow functions have lexical ‘this’ feature as well. Arrow (=>) is used as part of the syntax. Lexical this is declared or defined where the function is written. It comes under the umbrella of lexical scope; lexical scope has access to variables that are in its parent scope. Part 2 – ES6 Interview Questions (Advanced) Let us now have a look at the advanced ES6 Interview Questions and Answers. Q6. Explain about Webpack and the benefits of using Webpack? Answer: Webpack is used to bundle javascript files that can be used in a browser. Webpack processes the application and builds a dependency graph to map each module of the project requirement and generated the bundles. It allows you to run that environment which has been hosted babel. The advantage of using a web pack is that it bundles multiple modules and packs into a single JavaScript file. It integrated the dev server which helps in updating code and asset management. Q7. Explain about Default parameter values, Rest parameter, Spread operator? Answer: Default parameter values are used to initialize the functions with default values. The value of a parameter can be anything like a null value, number or function. The rest parameter is used to retrieve all the arguments to invoke the function. It means we can push the items of different categories separately. The rest parameter uses the rest parameter to combine parameters into a single array parameter. A spread operator is donated by … and then the variable name has been provided. E.g. ‘…X’ syntax of spread operator. It has been used to manipulate objects and array in ES6 and to copy the enumerable properties from one object to another. Let us move to the next ES6 Interview Questions. Q8. Explain about Internationalization and localization? Answer: These are the APIs which are standard API of JavaScript that helps in different tasks like collation, Number formatting, Currency formatting, Date and time formatting. - Collation: It is used for searching within a set of strings and sorting a set of strings. It is parameterized by locale and aware of Unicode. - Number Formatting: Numbers can be formatted with localized separators and digit grouping. The other things that include are style formatting, numbering system, percent, and precision. - Currency formatting: Numbers can be formatted mainly with currency symbols, with localized separators and digit grouping. - Date and time formatting: it has been formatted with localized separators and ordering. The format can be short, long and other parameters like locale and time zone. Q9. What is a Destructuring assignment and explain in brief? Answer: This is the frequently asked ES6 Interview Questions which is asked in an interview. Destructuring assignment is used to bind the set of a variable to the corresponding values. It mainly refers to the use of patterns to extract the parts of an object. A destructuring assignment has different forms like array matching, object matching, shorthand notation, object matching, deep matching, object and array matching, default values, parameter context matching and fail-soft destructuring. Some are explained as: - Array matching/object matching, shorthand notation/ object matching, deep matching: It is intuitive and flexible of arrays into individual variables during an assignment. - Object and Array matching: It is simple and defined default values for destructuring of objects and arrays. Q10. Explain briefly about classes, modules, and proxies? Answer: Classes are based on the OOP style that is object-oriented programming. The class declaration makes the patterns easier to use. It supports inheritance, base class access, static methods, and constructors. - Modules: it defines the patterns from popular javascript module loaders. It supports exporting or importing the values from or to modules without the global namespace. It supports marking the value as the default exported value and max-min values. - Proxies: It enables object creation with a wide variety of behaviors available to host objects. It can be used for logging, profiling, etc. Recommended Article This has been a guide to List Of ES6 Interview Questions and Answers so that the candidate can crackdown these ES6 Interview Questions easily. Here in this post, we have studied top ES6 Interview Questions which are often asked in interviews. You may also look at the following articles to learn more – - MySQL Interview Questions – Top and Most Asked - Pig Interview Questions - Redux Interview Questions- Useful Questions - Web Design Interview Questions - ES6 vs ES5: Differences - MySQL vs SQL Server: Features - MySQL vs MSSQL: Benefits - MySQL vs MongoDB: What are the Features - Best Guide on SQL Server Interview Questions
https://www.educba.com/es6-interview-questions/?source=leftnav
CC-MAIN-2021-04
refinedweb
1,294
55.84
You can subscribe to this list here. Showing 5 results of 5 Hi William and others. After banging my head for the past 4 three days I finally narrowed the C++0x hash tables feature to a few issues. The new unordered_ types use _Hashtable_iterator defined in /usr/include/c++/<version>/tr1_impl/hashtable. The problem is that the standard header defines the operator++() function, but not the operator--(). The SwigPyIterator defined in Lib/python/pyiterators.swg uses operator-- in decr() function, which results in compilation error. I see a few possibilities: 1. A slow and non-generic solution would be to do: if (dynamic_cast<_Hashtable_iterator>(base::current)) { return base::current; } else { return --base::current; } 2. Write a new copy of pycontainer.swg and pyiterators.swg specifically for the forward iterators. 3. Remove decr() function completely. Do we actually need it? Regards. -Matevž On 2009-07-21, Miklos Vajna <vmiklos@...> wrote: > On Mon, Jul 20, 2009 at 12:54:04PM +0100, Olly Betts <olly@...> wrot= > e: >> Can we just change the resource type name to match the name we want here? > > [...] > > In short, I don't think it's trivial how to move this to the C++ side, I > may even avoid doing so. But I'm open to do it if you really want, just > let's find out how to do it. It's not a blocker to do it in PHP, it's just that it would be more efficient to have the string we want already there rather than having to do string chopping in PHP. But it seems other code needs the string as it is, so this isn't just a trivial change liked I'd hoped. Cheers, Olly In libsequence, there're a few .tcc files which defines templates. I think I can just handle them as usual templates. That is , First parse the definition , then instantiate them using defined type. Today I tried to use Alignment.tcc. So I revised my interface file: ... %include *<*../../Alignment.tcc*>* ... %template() Sequence::Alignment::IsAlignment*<*Sequence::Fasta*>*; .... Everything looks fine until I successfully created the wrapping code and dynamic library. But when I want to import the dynamic library in python, error appeared: ... ImportError: dlopen(../libsequence/biolib/_libsequence.so, 2): Symbol not found: __ZN8Sequence9Alignment7GetDataINS_5FastaEEERSiRSt6vectorIT_SaIS5_EES3_ Referenced from: /Users/diavy/Documents/BioLib/biolib/src/mappings/swig/python/libsequence/biolib/_libsequence.so Expected in: flat namespace It seems like my instantiated template code haven't been complied into my dynamic library. Can anyone give me some advice? -- Xin Shuai (David) PhD of Complex System in School of Informatics Indiana University Bloomington 812-606-8019 Hi, This week I did the following: - Fixed bugs for proxy code generation for classes and global functions - Added support for global variables and member variables - Worked on test-suite and examples. Next week, I plan to work rigorously and complete the following: - Support for constants and enums - Constructors/Destructors - Test-suite and examples - Detailed plan for the second part of the program Thanks, Ashish On Sun, Jul 19, 2009 at 1:38 PM, Miklos Vajna <vmiklos@...>wrote: > Hi, > > > - Fixed. > > > ------------------------------------------------------------------------------ > Enter the BlackBerry Developer Challenge > This is your chance to win up to $100,000 in prizes! For a limited time, > vendors submitting new applications to BlackBerry App World(TM) will have > the opportunity to enter the BlackBerry Developer Challenge. See full prize > details at: > _______________________________________________ > Swig-devel mailing list > Swig-devel@... > > > On Mon, Jul 20, 2009 at 12:54:04PM +0100, Olly Betts <olly@...> wrote: >... Fixed. > @@ ... Ok, changed all NewString("") to NewStringEmpty(). > +...) Changed to use cap_module. > @@ . Removed. > @@ . Fixed. > @@ "); Fixed. > @@ ? For hi::A1, the following is defined (director_basic testcase): static swig_type_info _swigt__p_hi__A1 = {"_p_hi__A1", "hi::A1 *", 0, 0, (void*)0, 0}; Now if we want to change the resource type from "_p_hi__A1" to "A1" in the C++ wrapper code, I think it would be necessary to add a new member to the swig_type_info struct. Given that swig_type_info is not a PHP-specific structure, I think it's a bad idea to add a new member to it just because of PHP. Probably the easiest method would be to define a new structure with two members: one for the current ->clientdata content and one for the type name we want above. Sounds like possible to implement, but a bit overcomplicated. In short, I don't think it's trivial how to move this to the C++ side, I may even avoid doing so. But I'm open to do it if you really want, just let's find out how to do it. > +. Fixed. > > @@ . I do not get any warning with my code and -Wall, what extra warning flags are you using? OTOH, fixed. > @@ . Fixed 9 occurrences. > @@ . OK, changed !Cmp() to Cmp() == 0. (2 occurrences) > > + /* form complete return type */ > + return_type = Copy(type); > + { > + SwigType *t = Copy(decl); > + SwigType *f = 0; > + f = SwigType_pop_function(t); > > Why initialise f to 0 only to immediately assign a different value? I guess it's a result of an incompletely cleanup - fixed. > > + /* old style? caused segfaults without the p!=0 check > + in the for() condition, and seems dangerous in the > + while loop as well. > + while (Getattr(p, "tmap:ignore")) { > + p = Getattr(p, "tmap:ignore:next"); > + } > + */ > > This seems to just be copied from Python... Yes, removed. > > +); Right, fixed. I also added directorin typemaps for float and double as well. To sum up, I think I fixed all the issues you mentioned, except the "_p_Foo -> Foo, _p_ns__Bar -> Bar" one, but I'm unsure on how that should be improved if at all. Thanks for the review, Miklos
http://sourceforge.net/p/swig/mailman/swig-devel/?viewmonth=200907&viewday=21
CC-MAIN-2014-52
refinedweb
919
65.32
already know how Monte Carlo methods and barrier options work, you can skip the following sections. A barrier option is an exotic derivative, part of the set of path-dependent options, whose payoff depends not only on the underlying price at maturity but also on whether the price line hit a pre-determined level. There are different ways to determine this level and how the price can or cannot reach it. The first is the barrier level position in relation to the current underlying price (spot), so we have a first categorization "up" or "down". The second criterion can be "in" or "out", and it refers to what happens when the event "hit the level" is triggered. "In" means that the option starts to be active after having touched the barrier level. "Out" is the opposite, meaning that after triggering the event the option is no longer valid. Also, it could be "paired" with any kind of option. We could have a European option with barrier, as well as an American or an Asian one. Let's consider an example now. Suppose that we have a European option with a barrier. We can have any combination between call and put, in and out, up and down, which give us a total of $2^3 = 8$ different possible combinations, as we can see in the following table: Let's choose now a down-and-out call. That means that the barrier is currently lower than the spot price and our option is already active. As we can see in the following chart: The underlying price hits the barrier before the maturity making it invalid. Sometimes, as a kind of insurance, we can have a rebate price, which is a fixed amount of money, usually less than the option value, which we will receive in case our option expires due to hitting the barrier. Of course, this will also change the price of the option itself. In this article we will consider down-and-out barrier options without rebate, so that the payoff is given by:\begin{eqnarray} (S_T - K)_{+},\;\; \text{if}\; S_t > B \;\; \forall t \leq T \\ R = 0, \;\; \text{if}\; S_t \leq B \;\;\ \text{for at least one}\; t < T \end{eqnarray} where $R$ is the rebate price and $B$ the barrier level. The Monte Carlo method is a well-known method in finance, as it lets us compute difficult, if not impossible, expected values of complex stochastic functions. Mike has already discussed the method in several articles regarding option pricing, but a few recap lines can be helpful for those that are new to it. The Monte Carlo method was first introduced in the field of physics, for complex simulations, very likely by Enrico Fermi in the 1930s for studying neutron diffusion. It then became popular in the 1940s among physicists and mathematicians involved in creating bombs for the U.S. Army. The projects needed a code name, so John Von Neumann chose "Monte Carlo", referring to the famous Monte Carlo Casino. Since then, technology and especially computational power have increased dramatically, letting us use these methods for a large variety of problems. In finance the Monte Carlo method is mainly used for option pricing as, especially with exotic options, the payoff is sometimes too complex, if not impossible, to compute. The main idea behind it is quite simple: simulate the stochastic components in a formula and then average the results, leading to the expected value. Of course, the more simulations (paths) you make, the more accurate the result will be. A commonly accepted value for the minimum number of paths is $10^6$. That should give good results for most of the simulations. Otherwise, there are techniques that can reduce variance in order to make even more accurate predictions. Given the random nature of this process, variance reduction is not the only problem we can encounter. Another one, probably the most important, is how the random numbers are generated. There is an entire branch of mathematics talking about this and a detailed explanation is well beyond the purpose of this article, but we will see that CUDA can provide different efficient methods for generating random numbers by including the useful library curand. As the Monte Carlo method is basically a way to compute expected values by generating random scenarios and then averaging them, it is actually very efficient to parallelise. Moreover, with consumer CPUs on standard computers it is just not possible to reach the accuracy needed, as simulating over one million paths is usually very time consuming. With the GPU we can reduce this problem by parallelising the paths. That is, we can assign each path to a single thread, simulating thousands of them in parallel, with massive savings in computational power and time. At the end of this article I will show you the numerical results, making it quite obvious why it's better to run a Monte Carlo on a GPU. First, let's see what and how to parallelise. In option pricing, usually the only variable that can assume random values is the underlying, so we only have to write a kernel that can generate a simulated value for the underlying and then calculate the option price. That's it. Sounds easy, but actually we have to cope with a couple of issues that we could have avoided for the pricing of a path-independent option. That is, as the barrier can be hit at any point in time we have to simulate step by step the changes in the underlying price, significantly reducing the code speed. Why? Let's say that we want to run an accurate Monte Carlo, which means more than one million paths. And let's say that we also want to use a reasonable proxy for price changes, i.e. only simulate daily changes. This means that we will have to generate 365*10^6 random numbers as well as perform 365 price computations one million times! Also, for more complex derivatives or for purposes other than learning, daily changes will likely not have sufficient granularity. Before having a look at the code, let me give you the last theoretical basis you need (if you don't know it already) to fully understand this method. For simulating the underlying price, we must discretise the underlying's changes. In this article, I will make use of the Euler method, as it's very easy to understand (and code up) and, despite the fact that it isn't the best method, it's still a good approximation for our needs.\begin{eqnarray} dS_t = \mu S_t dt + \sigma S_t dW_t \end{eqnarray} Now, if we see this as a finite difference, we can rewrite everything in the following way:\begin{eqnarray} Y^{n+1} - Y^{n} = \mu Y^{n} \Delta t + \sigma Y^{n} \Delta W_t \end{eqnarray} where: Now we have to compute the changes. As you can see from the list above, the only random variable is $dW$. This variable is the only reason why we need to run a Monte Carlo simulation. Now we are ready to have a look at the code. First, in order to minimise the interruption of explaining the code, I would like to introduce this simple, yet effective, performance measurement tool. By typing: clock() You can get the number of clock ticks elapsed since the program started. This is a C function and, as it can be affected by many factors, it's better to never use it alone. Instead you can compute the difference between two times and then get the time (in seconds) of a given task or code portion. For receiving the time and not just the clock ticks, you can divide that number by the number of clocks per second that your CPU is able to perform. Again, you can use a C instruction called CLOCKS_PER_SEC and store the result in a variable, as in the following: double start_time = clock()/CLOCKS_PER_SEC; // routine double end_time = clock()/CLOCKS_PER_SEC; printf("Time elapsed: %d\n",end_time-start_time); This simple code will give you the exact time elapsed for the // routine part of the code. CUDA also provides a library for this purpose, but for now the C one is more than sufficient for us. CUDA provides efficient random number generators for a lot of different distributions via the library curand.h. In this case, as the Brownian motion evolves with normally distributed random steps, we will use the normal generator. The set of instructions is composed of at least four line of code, let's see them in detail: curandGenerator_t curandGenerator; This first one is just a variable declaration, in which we are creating the new generator as a variable of type curandGenerator_t, called curandGenerator. Then we have to decide what kind of generator we would like to use, calling the function curandCreateGenerator by passing as first argument our generator variable and the name of the generator method. In this case I used the Mersenne Twister algorithm, which you can choose by typing CURAND_RNG_PSEUDO_MTGP32 as the second argument, as in the following: curandCreateGenerator(&curandGenerator, CURAND_RNG_PSEUDO_MTGP32); Now we have to set the seed. Seeds are the "base" upon which the random series will be built, so depending on the seed you will have a different random number series. In this case I choose 1234ULL, which means that a very long unsigned integer number will be used as a seed: curandSetPseudoRandomGeneratorSeed(curandGenerator, 1234ULL); Now it's time to finally generate our normally distributed random numbers. We can do this by using the curand function curandGenerateNormal, which takes as inputs the curand generator, the output array (in which we want to store the numbers), the amount of numbers to generate, the mean of the distribution and its standard deviation. In this case, as we are talking about Brownian motion, we will need a normal distribution with mean 0 and variance $dt$. curandGenerateNormal(curandGenerator, d_normals.getData(), N_NORMALS, 0.0f, sqrdt); Finally, you can destroy the generator using the function: curandDestroyGenerator(curandGenerator); Now let's talk about the main part, looking at the code. At the end of this article you will find the complete code, so now I will explain it step by step. = 5000000;); This first part consists of including libraries and variable declaration, but it is useful to notice a few choices I made. First, the try instruction: this is an additional error checking line, as if we have any problem, the program won't crash but will return the error information (using the instruction catch at the end of the code). This is good practice for longer programs and therefore a good habit to develop. Regarding the parameters, you can see that I divided them into different blocks, reflecting their differing nature. In the first one we can find the "dimensional constants", or rather the lengths of our arrays and loops. N_PATHS specifies the number of paths (or runs) that the Monte Carlo method will perform. In this case we have $5.0 \times 10^6$, which is a reasonable number for having a good precision in the estimation. Then, as aforementioned, I decided to compute daily changes, setting N_STEPS = 365. Therefore the number of normals we will need is N_PATHS * N_STEPS, as we will need 365 random changes for $5.0 \times 10^6$ simulations. That is a huge constraint for our precision, as this big array will have to be allocated in the GPU memory. So, we can choose to increase the precision of a single run (by increasing N_STEPS) or the overall accuracy (by increasing N_PATHS), until reaching the size limit for device allocation, which depends solely on your GPU. In this case I decided that 365 was a reasonable approximation, then I maximized N_PATHS, but feel free to experiment, as usually is the best way to learn! The second and the third blocks represent our input parameters. More specifically, the second is for constant declaration, in which constants are "market parameters" necessary for computing the option price, while the third block is for derived variables. The fourth is for array declarations. s is the host array that receives the final prices after they will be computed by the GPU, d_s is exactly the same array but for the device (GPU), and the last one is the array that contains the random numbers. d_s and d_normals are declared using the class dev_array.h that I showed in my previous article. So, if you haven't read it already, it might be worth having a look at it, as it will be used several times for this script. mc_dao_call(d_s.getData(), T, K, B, S0, sigma, mu, r, dt, d_normals.getData(), N_STEPS, N_PATHS); After having declared our variables and constants, and having generated the random numbers (see above), we can now call the kernel function. As usual (see the vector addition article), I prefer to separate the .cu file with the kernel from the main. In this way, we can call this function, mc_dao_call, which will call the kernel in turn, after having specified its parameter, as we can see: ); } I decided to use 1024 threads per block, even if I didn't notice significant changes in the performance between setting BLOCK_SIZE=1024 and BLOCK_SIZE=256 but, as we will have a lot of threads working (one for each path!), 1024 is a reasonable choice. As you can see, this function, included in the script kernel.cu, only sets the grid parameters and then calls the actual kernel. As it's a different script, we need to create a header file kernel.h in which we specify the function's parameters as follows: #ifndef _KERNEL_CUH_ #define _KERNEL_CUH_ void mc_dao_call(float * d_s, float T, float K, float B, float S0, float sigma, float mu, float r, float dt, float* d_normals, unsigned N_STEPS, unsigned N_PATHS); #endif Now let's have a look at the most important part, the kernel. Here is the code that the GPU processes, so it's fundamental to understand how it works. This first part includes the header of the kernel function and the constant declaration regarding the positioning parameters: _; Then we initialise the indexes, one for getting the normally distributed numbers and one for our price array. For the latter it's quite easy as it can be immediately seen that having a single thread working on each path we will have exactly N_PATHS threads, so we only have to get the thread index for indexing our price vector d_s. For d_normals, we start indexing them in the same way, but we will upgrade its index later in the code. So now we have our indexes: int s_idx = tid + bid * bsz; int n_idx = tid + bid * bsz; Then we initialise the current price of the underlying at the spot price: float s_curr = S0; So that now we are ready to start with the actual Monte Carlo loop. First, we need to be sure that no undesired thread will access our price array. Before the loop we have to check that the array index is lower than the maximum number of threads by wrapping the loop in this if statement: if (s_idx<N_PATHS){ .. } Second, we have to write a do/while loop. That's a bit different from the usual Monte Carlo methods, which make use of a normal for loop but it reflects the path-dependent nature of the barrier option. In fact if we hit the barrier our down-and-out option will no longer be active, so continuing to simulate that path to maturity wouldn't make sense anymore. int n=0; do { s_curr = s_curr + mu*s_curr*dt + sigma*s_curr*d_normals[n_idx]; n_idx ++; n++; } while (n<N_STEPS && s_curr>B); You can see here there are two conditions for staying in the loop: the first one is that the number of steps already made is lower than the maximum number of steps (365 in this case) allowed, while the second one is that the current price is still higher than the barrier. We then update the price making use of the Euler discretisation and after that we update our indexes. That is, we first update the normal array index n_idx and then the loop index n, that states which "day" the loop is computing. Using only 365 steps we are missing the cases in which the price fell under the barrier during a certain day and then closed higher than the barrier at the end of the day: this reduces the accuracy of the price but, as I already said, it's part of the trade-off between the accuracy of the expected value and the simulated price path, with your GPU capability acting as your only constraint. When we finally have our final path price (either at maturity or at the barrier level) we can compute the option payoff in the following way: double payoff = (s_curr>K ? s_curr-K : 0.0); __syncthreads(); d_s[s_idx] = exp(-r*T) * payoff; Which is exactly the payoff of a plain vanilla call. Now we have to compute the expected value, averaging all the prices that we got from the kernel. First, we need to synchronize the device and to copy the prices from the device to the array. cudaDeviceSynchronize(); // copy results from device to host d_s.get(&s[0], N_PATHS); The first is the usual CUDA standard method for synchronizing, while d_s.get() is the dev_array function for copying data from device to host. What follows is the for loop for computing the price sum and, thus, our expected price value. double temp_sum=0.0; for(size_t i=0; i<N_PATHS; i++) { temp_sum +=s[i]; } temp_sum/=N_PATHS; Now we have the price of a down-and-out barrier option in CUDA computed via the Monte Carlo method. Notice that it can also compute a European call just by setting the barrier value to 0.0f! The script also has two further blocks of code, one for computing the price with the CPU (for comparison) and the last one for displaying the results. The CPU Monte Carlo simulation is exactly the same as the kernel one, as you can see: //; You can find the complete code, with the last part and the lines for displaying the output, at the end of this article. With these settings, and on my hardware, this is what I get: ****************** INFO ****************** Number of Paths: 5000000 Underlying Initial Price: 100 Strike: 100 Barrier: 95 Time to Maturity: 1 years Risk-free Interest Rate: 0.05% Annual drift: 0.1% Volatility: 0.2% ****************** PRICE ****************** Option Price (GPU): 8.52652 Option Price (CPU): 8.51663 ******************* TIME ***************** GPU Monte Carlo Computation: 25.1978ms CPU Monte Carlo Computation: 13530 ms ******************* END ***************** We can see that the GPU implementation was roughly 537x faster than the CPU one, including the memory allocation host to device. In future articles we will also talk about exploiting CUDA using different pricing methods, including multidimensional finite differences methods. = 100000;); // generate random numbers curandGenerator_t curandGenerator; curandCreateGenerator(&curandGenerator, CURAND_RNG_PSEUDO_MTGP32); curandSetPseudoRandomGeneratorSeed(curandGenerator, 1234ULL) ; curandGenerateNormal(curandGenerator, d_normals.getData(), N_NORMALS, 0.0f, sqrdt); double t2=double(clock())/CLOCKS_PER_SEC; // call the kernel mc_dao_call(d_s.getData(), T, K, B, S0, sigma, mu, r, dt, d_normals.getData(), N_STEPS, N_PATHS); cudaDeviceSynchronize(); // copy results from device to host d_s.get(&s[0], N_PATHS); // compute the payoff average double temp_sum=0.0; for(size_t i=0; i<N_PATHS; i++) { temp_sum +=s[i]; } temp_sum/=N_PATHS; double t4=double(clock())/CLOCKS_PER_SEC; //; double t5=double(clock())/CLOCKS_PER_SEC; cout<<"****************** INFO ******************\n"; cout<<"Number of Paths: " << N_PATHS << "\n"; cout<<"Underlying Initial Price: " << S0 << "\n"; cout<<"Strike: " << K << "\n"; cout<<"Barrier: " << B << "\n"; cout<<"Time to Maturity: " << T << " years\n"; cout<<"Risk-free Interest Rate: " << r << "%\n"; cout<<"Annual drift: " << mu << "%\n"; cout<<"Volatility: " << sigma << "%\n"; cout<<"****************** PRICE ******************\n"; cout<<"Option Price (GPU): " << temp_sum << "\n"; cout<<"Option Price (CPU): " << sum << "\n"; cout<<"******************* TIME *****************\n"; cout<<"GPU Monte Carlo Computation: " << (t3-t2)*1e3 << " ms\n"; cout<<"CPU Monte Carlo Computation: " << (t5-t4)*1e3 << " ms\n"; cout<<"******************* END *****************\n"; // destroy generator curandDestroyGenerator( curandGenerator ) ; } catch(exception& e) { cout<< "exception: " << e.what() << "\n"; } } #include "kernel.h" _; int s_idx = tid + bid * bsz; int n_idx = tid + bid * bsz; float s_curr = S0; if (s_idx<N_PATHS) { int n=0; do { s_curr = s_curr + mu*s_curr*dt + sigma*s_curr*d_normals[n_idx]; n_idx ++; n++; } while (n<N_STEPS && s_curr>B); double payoff = (s_curr>K ? s_curr-K : 0.0); __syncthreads(); d_s[s_idx] = exp(-r*T) * payoff; } }.
https://www.quantstart.com/articles/Monte-Carlo-Simulations-In-CUDA-Barrier-Option-Pricing
CC-MAIN-2017-30
refinedweb
3,399
57.81
Interface for ScummVM backends. More... #include <system.h> List of all members. In order to be able to display dialogs atop the game graphics, backends must provide an overlay mode. The overlay is currently forced at 16 bpp. For 'coolness' we usually want to have an overlay which is blended over the game graphics. On backends which support alpha blending, this is no issue; but on other systems. This is the lower level implementation as provided by the backends. The engines should use the Graphics::CursorManager class instead of using it directly. A feature in this context means an ability of the backend which can be either on or off.. !!! Below description not apply for ResidualVM !!!. Historically the overlay size had always been a multiple of the game resolution, for example when the game resolution was 320x200 and the user selected a 2x scaler and did not enable aspect ratio correction it had a size of 640x400. An exception was the aspect ratio correction, which did allow for non multiples of the vertical resolution of the game screen. Nowadays the overlay size does not need to have any relation to the game resolution though, for example the overlay resolution might be the same as the physical screen resolution. The overlay is forced to a 16bpp mode right now.. On a note for OSystem users here. We do not require our graphics to be thread safe and in fact most/all backends using OpenGL are not. So do *not* try to call any of these functions from a timer and/or audio callback (like readBuffer of AudioStreams). !!! Not used in ResidualVM !!!. For backend authors only, the following pointers (= "slots) to various subsystem managers / factories / etc. can and should be set to a suitable instance of the respective type. For some of the slots, a default instance is set if your backend does not do so. For details, please look at the documentation of each slot. A backend may setup slot values in its initBackend() method, its constructor or somewhere in between. But it must a slot's value no later than in its initBackend() implementation, because OSystem::initBackend() will create any default instances if none has been set yet (and for other slots, will verify that one has been set; if not, an error may be generated).. Definition at line 117 of file system.h. Definition at line 1352 of file system.h. Examples include: One has to distinguish between the *availability* of a feature, which can be checked using hasFeature(), and its *state*. For example, the SDL backend *has* the kFeatureFullscreenMode, so hasFeature returns true for it. On the other hand, fullscreen mode may be active or not; this can be determined by checking the state via getFeatureState(). Finally, to switch between fullscreen and windowed mode, use setFeatureState(). If supported, this feature flag can be used to switch between windowed and fullscreen mode.. If supported this flag can be used to switch between unfiltered and filtered graphics modes. Indicate if stretch modes are supported by the backend. Determine whether a virtual keyboard is to be shown or not. This would mostly be implemented by backends for hand held devices, like PocketPC, Palms, Symbian phones like the P800, Zaurus, etc. Backends supporting this feature allow specifying a custom palette for the cursor. The custom palette is used if the feature state is set to true by the client code via setFeatureState(). It is currently used only by some Macintosh versions of Humongous Entertainment games. If the backend doesn't implement this feature then the engine switches to b/w versions of cursors. The GUI also relies on this feature for mouse cursors. A backend have this feature if its overlay pixel format has an alpha channel which offers at least 3-4 bits of accuracy (as opposed to just a single alpha bit). This feature has no associated state. Client code can set the state of this feature to true in order to iconify the application window. If supported, this feature flag can be used to check if waiting for vertical sync before refreshing the screen to reduce tearing is enabled. ResidualVM specific When a backend supports this feature, it guarantees the graphics context is not destroyed when switching to and from fullscreen. For OpenGL that means the context is kept with all of its content: texture, programs... For TinyGL that means the backbuffer surface is kept. The presence of this feature indicates whether the displayLogFile() call is supported. The presence of this feature indicates whether the system clipboard is available. If this feature is not present, the hasTextInClipboard(), getTextFromClipboard() and setTextInClipboard() calls can still be used, however it should not be used in scenarios where the user is expected to copy data outside of the application. The presence of this feature indicates whether the openUrl() call is supported. show on-screen control mouse emulation mode swap menu and back buttons keyboard mouse and joystick mouse speed change analog joystick deadzone shaders Supports for using the native system file browser dialog through the DialogManager. For platforms that should not have a Quit button. Definition at line 301 of file system.h. This type is able to save the different errors which can happen while changing GFX config values inside GFX transactions. endGFXTransaction returns a ORed combination of the '*Failed' values if any problem occures, on success 0. Everything fine (use EQUAL check for this one!). Failed switching aspect ratio correction mode. Failed switching fullscreen mode. Failed switching the GFX graphics mode (setGraphicsMode). Failed switching the screen dimensions (initSize). Failed setting the color format. Failed setting the filtering mode. Failed setting the stretch mode. Definition at line 909 of file system.h. [protected] Definition at line 42 of file system.cpp. [protected, virtual] Definition at line 63 of file system.cpp. 0 [inline, virtual] Add system specific Common::Archive objects to the given SearchSet. E.g. on Unix the dir corresponding to DATA_PATH (if set), or on Mac OS X the 'Resource' dir in the app bundle. Reimplemented in OSystem_MacOSX, OSystem_POSIX, OSystem_SDL, and OSystem_Win32. Definition at line 1548 of file system.h. [inline] Return false if initBackend() has not yet been called and true otherwise. Some functionalities such as mutexes cannot be used until the backend is initialized. Definition at line 269 of file system.h.. Reimplemented in ModularGraphicsBackend. Definition at line 896 of file system.h. Clears the focus set by a call to setFocusRectangle(). This allows the engine to clear the focus during times when no particular area of the screen has the focus. Definition at line 1099 of file system.h. [pure virtual]. Implemented in ModularGraphicsBackend. [inline, protected, virtual] This allows derived classes to implement encoding conversion using platform specific API. This method shouldn't be called directly. Use Common::Encoding instead. Reimplemented in OSystem_SDL, and OSystem_Win32. Definition at line 1703 of file system.h. Blit a graphics buffer to the overlay. In a sense, this is the reverse of grabOverlay.. [virtual] Open the default config file for reading, by returning a suitable ReadStream instance. It is the callers responsiblity to delete the stream after use. Definition at line 204 of file system.cpp. Open the default config file for writing, by returning a suitable WriteStream instance. It is the callers responsiblity to delete the stream after use. May return 0 to indicate that writing to config file is not possible. Definition at line 209 of file system.cpp. Create a new mutex. Implemented in ModularMutexBackend. Delay/sleep for the specified amount of milliseconds. Implemented in OSystem_SDL. Delete the given mutex. Make sure the mutex is unlocked before you delete it. If you delete a locked mutex, the behavior is undefined, in particular, your program may crash. Destoy this OSystem instance. Definition at line 124 of file system.cpp.. Implemented in BaseBackend, and ModularGraphicsBackend. in OSystem_MacOSX, OSystem_POSIX, and OSystem_Win32. Definition at line 1612 of file system.h.. End (and thereby commit) the current GFX transaction. Definition at line 928 of file system.h. Allows the backend to perform engine specific de-init. Called after the engine finishes. Reimplemented in OSystem_SDL. Definition at line 281 of file system.h. Allows the backend to perform engine specific init. Called just before the engine is run. Definition at line 275 of file system.h. Signals that a fatal error inside the client code has happened. This should quit the application. Definition at line 194 of file system.cpp. Fills the screen with a given color value. Return the audio cd manager. For more information, refer to the AudioCDManager documentation. Definition at line 1410 of file system.h. Get the default file name (or even path) where the user configuration of ScummVM will be saved. Note that not all ports may use this. Reimplemented in OSystem_MacOSX, OSystem_POSIX, OSystem_PS3, OSystem_RISCOS, and OSystem_Win32. Definition at line 218 of file system.cpp. Return the ID of the 'default' graphics mode. What exactly this means is up to the backend. This mode is set by the client code when no user overrides are present (i.e. if no custom graphics mode is selected via the command line or a config file). Definition at line 604 of file system.h. Return the ID of the 'default' shader mode. What exactly this means is up to the backend. This mode is set by the client code when no user overrides are present (i.e. if no custom shader mode is selected via the command line or a config file). Definition at line 729 of file system.h. Return the ID of the 'default' stretch mode. What exactly this means is up to the backend. This mode is set by the client code when no user overrides are present (i.e. if no custom stretch mode is selected via the command line or a config file). Definition at line 782 of file system.h. Return the event manager singleton. For more information, refer to the EventManager documentation. Definition at line 1299 of file system.h. Query the state of the specified feature. For example, test whether fullscreen mode is active or not. Definition at line 480 of file system.h. Returns the FilesystemFactory object, depending on the current architecture. Definition at line 199 of file system.cpp. Return a platform-specific global keymap. The caller will use and delete the return object. See keymapper documentation for further reference. Definition at line 1321 of file system.h. Determine which graphics mode is currently active. Definition at line 637 of file system.h. Register hardware inputs with keymapper. Reimplemented in OSystem_PS3, and OSystem_SDL. Definition at line 1310 of file system.h. Returns the currently set virtual screen height. Return platform-specific default keybindings. Definition at line 1330 of file system.h. false Get the number of milliseconds since the program was started. Return the audio mixer. For more information, refer to the Audio::Mixer documentation. Implemented in ModularMixerBackend. Returns the pixel format description of the overlay. Return the height of the overlay. Return the width of the overlay. Return the palette manager singleton. For more information, refer to the PaletteManager documentation. Return the SaveFileManager, used to store and load savestates and other modifiable persistent game data. For more information, refer to the SaveFileManager documentation. Definition at line 235 of file system.cpp.). Definition at line 876 of file system.h. Determine the pixel format currently in use for screen rendering. Return a Graphics::PixelBuffer representing the framebuffer. The caller can then perform arbitrary graphics transformations on the framebuffer (blitting, scrolling, etc.). !!! ResidualVM specific method: !!! Determine which shader is currently active. Definition at line 760 of file system.h. Determine which stretch mode is currently active. Definition at line 809 of file system.h. !!! ResidualVM specific method !!! Retrieve a list of supported levels of anti-aliasting. Anti-aliasing only works when using one of the hardware accelerated renderers. An empty list means anti-aliasing is not supported. Definition at line 702 of file system.h.(). Definition at line 589 of file system.h. Retrieve a list of all hardware shaders supported by this backend. This can be only hardware shaders. it is completely up to the backend maintainer to decide what is appropriate here and what not. The list is terminated by an all-zero entry. Definition at line 716 of file system.h. Retrieve a list of all stretch modes supported by this backend. It is completely up to the backend maintainer to decide what is appropriate here and what not. The list is terminated by an all-zero entry. Definition at line 769 of file system in OSystem_MacOSX, OSystem_SDL, and OSystem_Win32. Definition at line 222 of file system.cpp. Returns clipboard contents as a String. The kFeatureClipboardSupport feature flag can be used to test whether this call has been implemented by the active backend. Reimplemented in OSystem_MacOSX. Definition at line 1634 of file system.h. Get the current time and date, in the local timezone. Corresponds on many systems to the combination of time() and localtime(). Return the timer manager singleton. For more information, refer to the TimerManager documentation. Definition at line 231 of file system.cpp. Returns the currently set virtual screen width. Copy the content of the overlay into a buffer provided by the caller. This is only used to implement fake alpha blending. Determine whether the backend supports the specified feature. Reimplemented in ModularGraphicsBackend, OSystem_MacOSX, OSystem_POSIX, OSystem_RISCOS, OSystem_SDL, and OSystem_Win32. Definition at line 468 of file system.h. Returns whether there is text available in the clipboard. Definition at line 1623 of file system.h. Deactivate the overlay mode. The following method should be called once, after g_system is created. Reimplemented in OSystem_AmigaOS, OSystem_MacOSX, OSystem_POSIX, OSystem_PS3, OSystem_RISCOS, OSystem_SDL, and OSystem_Win32. Definition at line 252 of file system.h. The following method is called once, from main.cpp, after all config data (including command line params etc. ) are fully loaded. Reimplemented in BaseBackend, OSystem_MacOSX, OSystem_POSIX, OSystem_PS3, OSystem_RISCOS, OSystem_SDL, and OSystem_Win32. Definition at line 100 of file system.cpp. nullptr Set the size and color format of the virtual screen. Typical sizes include:).. Send a list of graphics modes to the backend so it can make a decision about the best way to set up the display hardware. Engines that switch between different virtual screen sizes during a game should call this function prior to any call to initSize. Engines that use only a single screen size do not need to call this function. Definition at line 850 of file system.h. Returns whether connection's limited (if available on the target system). Returns true if connection seems limited. Definition at line 226 of file system.cpp. !!! ResidualVM specific method !!! Set the size of the launcher virtual screen. Lock or unlock the mouse cursor within the window. ResidualVM specific method Lock the given mutex. a surface with the pixel format described by getScreenFormat is returned. The returned surface must *not* be deleted by the client code.. Implemented in OSystem_RISCOS, OSystem_SDL, and OSystem_Win32. Open the given Url in the default browser (if available on the target system). url the URL to open Reimplemented in OSystem_MacOSX, OSystem_POSIX, OSystem_RISCOS, and OSystem_Win32. Definition at line 1659 of file system.h. Quit (exit) the application. Sets the graphics scale factor to x1. Games with large screen sizes reset the scale to x1 so the screen will not be too big when starting the game. Definition at line 646 of file system.h. !!! ResidualVM specific method !!! Instruct the backend to capture a screenshot of the current screen. The backend can persist it the way it considers appropriate. Definition at line 1107 of file system.h. Replace the specified range of cursor the palette with new colors. The palette entries from 'start' till (start+num-1) will be replaced - so a full palette update is accomplished via start=0, num=256. Backends which implement it should have kFeatureCursorPalette flag set Definition at line 1261 of file system.h. En-/disable the specified feature. For example, this may be used to enable fullscreen mode, or to deactivate aspect correction, etc. Definition at line 474 of file system.h.. Definition at line 1091 of file system.h. Switch to the specified graphics mode. If switching to the new mode failed, this method returns false. Definition at line 615 of file system.h. Switch to the graphics mode with the given name. If 'name' is unknown, or if switching to the new mode failed, this method returns false. Definition at line 130 of file system.cpp. Set the bitmap used for drawing the cursor. Switch to the shader mode with the given name. If 'name' is unknown, or if switching to the new mode failed, this method returns false. Definition at line 152 of file system.cpp. Switch to the specified shader mode. If switching to the new mode failed, this method returns false. Definition at line 740 of file system.h.. Switch to the stretch mode with the given name. If 'name' is unknown, or if switching to the new mode failed, this method returns false. Definition at line 173 of file system.cpp. Switch to the specified stretch mode. If switching to the new mode failed, this method returns false. Definition at line 791 of file system.h. Set the content of the clipboard to the given string. Definition at line 1645 of file system.h. Set the size of the screen. !!! ResidualVM specific method: !!! Set a window caption or any other comparable status display to the given value. The caption must be a pure ISO LATIN 1 string. Passing a string with a different encoding may lead to unexpected behavior, even crashes. Definition at line 1438 of file system.h. Show or hide the mouse cursor. Currently the backend is not required to immediately draw the mouse cursor on showMouse(true). TODO: We might want to reconsider this fact, check Graphics::CursorManager::showMouse for some details about this. Activate the overlay mode. Suggest textures to render at the side of the game window. This enables eg. Grim to render the game in a widescreen format. The system must take a copy of the Surfaces, as they will be free()d automatically. Definition at line 961 of file system.h. Unlock the given mutex. Unlock the screen framebuffer, and mark it as dirty (i.e. during the next updateScreen() call, the whole screen will be updated. Flush the whole screen, that is render the current content of the screen framebuffer to the display. This method could be called very often by engines. Backends are hence supposed to only perform any redrawing if it is necessary, and otherwise return immediately. See <> Move ("warp") the mouse cursor to the specified position in virtual screen coordinates. [friend] Definition at line 118 of file system.h. No default value is provided for _audiocdManager by OSystem. However, BaseBackend::initBackend() does set a default value if none has been set before. Definition at line 151 of file system.h. [private] Indicate if initBackend() has been called. Definition at line 237 of file system.h. Used by the default clipboard implementation, for backends that don't implement clipboard support. Definition at line 227 of file system.h. Definition at line 231 of file system.h. No default value is provided for _eventManager by OSystem. However, EventsBaseBackend::initBackend() does set a default value if none has been set before. Definition at line 160 of file system.h. No default value is provided for _fsFactory by OSystem. Note that _fsFactory is typically required very early on, so it usually should be set in the backends constructor or shortly thereafter, and before initBackend() is called. Definition at line 221 of file system.h. No default value is provided for _savefileManager by OSystem. Definition at line 174 of file system.h. No default value is provided for _timerManager by OSystem. Definition at line 167 of file system.h.
https://doxygen.residualvm.org/d9/df4/classOSystem.html
CC-MAIN-2020-40
refinedweb
3,309
61.33
How to add a jar file to an Eclipse project. This page shows how to add a jar file to an Eclipse project so they code in that project may use the code in the jar file. In this example the Eclipse project name is WatorWorld and the jar file is name A4.jar 1. Drag the jar file into the project folder in Eclipse. The jar file will now show up in the project. 2. Right click on the project after you have added the jar and select Properties. 3. In the window that pops up select Java Build Path. 4. Click on the Libraries tab and then click the Add JARs ... button. 5. In the window that pops up expand the project and select the A4.jar file and click the okay button. 6. After adding the jar the: 7. Close the properties window. You will now be able to reference any classes in the jar. If those classes are in a package you will have to include an import statement for that package. In the example the classes in the A4.jar file are part of the a4Shell package so the statement import a4Shell.*; will no longer cause a compile error.
http://www.cs.utexas.edu/~scottm/cs324e/Assignments/AddJarToEclipse.htm
CC-MAIN-2017-30
refinedweb
204
93.34
Talk:Accepted features/Smoothness Ok, I agree with the smoothness tag as proposed in you'r tab, because I need something like that for mountain track roads ( saying which vehicule you need at least to drive on it ) Sletuffe 16:28, 16 May 2008 (UTC) Even being new at OSM: from my view as a biker and inline-skater smoothness is a very practical solution in conjuntion with surface Pmurk65 27 May 2008 smoothness and surface I dislike the dependencies between the proposed smoothness and the surface key. If I read your list correctly, a way with surface=cobblestone and smoothness=bad is illegal? I'd certainly like to distinguish between various grades of cobblestoned road. In my opinion, smoothness without surface is pointless, hence I'd rather a smoothness key refined surface, so you get excellent or good or intermediate paved roads, good to catastrophic cobblestoned roads, etc. So how about a key smoothness=0 (default), +1, -1 to refine a base smoothness for the type of surface? Robx 07:11, 30 May 2008 (UTC) - This dependency was not my intention. The surface descriptions in the second column are EXAMPLES, not used for definition. The smoothness of a way should be assessed solely based on the usability of that way by the vehicles I mention, NOT based on the surface. This is my whole point: as a user of a certain road or path I am only interested wether I can drive on this road or not. If I sit on a racing bike, I am not interested wether the surface of a way is cobblestone or mud, just wether it is smooth enough to be used with a racing bike or not. I changed the proposal to make that clear (hopefully). With your proposal of a refined surface key, it gets very difficult to draw usage-specific maps (e.g. for racing bikes), since there is a potentially infinite number of surface values. Imagine a piste on a salt lake -- with the surface key it would read "surface=salt", which would have no meaning before the key is integrated into all the renderers and Garmin type files and whatever. With "smoothness=excellent", it would instantly show up everywhere as usable with a racing bike, which is my intention. --Chrischan 11:05, 1 June 2008 (UTC) - I'm beginning to like the proposal. It doesn't store all relevant information, but it's a good start, and appears to be clearly defined. I've started tagging some roads around here, the better cobblestoned roads with smoothness=intermediate and the awful ones with smoothness=bad. Also some really smooth paved roads with smoothness=excellent. I'd suggest adding some default values: A road should have a default of smoothness=good given its surface is paved or unspecified. A road with surface=cobblestone should default to smoothness=intermediate. A track should probably default to intermediate also. Robx 20:09, 2 June 2008 (UTC) - Perhaps an additional value of "unknown" would be best as a default? I've even been on an interstate highway (motorway) which is definitely smoothness=bad, or maybe smoothness=intermediate if you're feeling generous. Just anecdotal, but I think it's a bad idea to imply the smoothness based on the highway (or even surface) classification. --Hawke 21:26, 2 June 2008 (UTC) - I'm sure those exist, but they're certainly the exception. A default of unkown (or rather, no default), includes in the smoothness tag also the information whether the way has been surveyed for smoothness, which may be a good idea. But I'd rather not add thousands of smoothness=good tags and rather state somewhere that I've surveyed a given area for smoothness. Robx 18:37, 8 June 2008 (UTC) Couldn't this proposal been covered by surface=* to begin with??????????????? --Skippern 22:18, 2 December 2008 (UTC) - Many have tried hard, but surface as never been able to answer "what vehicle do I need to go on that road" As far as I know no renderer is able to take advantage of it, and routing program do only use surface=paved & surface=unpaved at most. Also please keep on reading this page wherever surface is mentionned, and you'll see the problem Sletuffe 22:52, 2 December 2008 (UTC) - If the tool is broken, fix it, don't make more that can break down! The problem isn't the tagging, but the renderers and the routing programs according to what you say. It will not make a difference for the routing program if you have smoothness tagged as well if it only differs between paved and unpaved. You should have focused with on getting the programs accept more surface alternatives from that WAY TOO LONG LIST of surfaces, than adding this IMO pointless feature. --Skippern 10:47, 3 December 2008 (UTC) Subjective I've never like subjective tags such as this. This is why tracktype=* never got anywhere, as it is not obvious what the difference between "bad" and "intermediate" is. For instance, the roads where I live are terrible, but saying as they're all like that, should it be smoothness=bad or smoothness=intermediate? Bruce89 14:19, 30 May 2008 (UTC) - I like it, as long as there are usable guidelines for how to tag. "suitable for roller skates" and "suitable for mountain bikes and 4-wheel-drive automobiles" is quite good, IMO. --Hawke 15:16, 30 May 2008 (UTC) - In my opinion, tracktype=* never got anywhere because it does not describe a singular property of a way, but a combination of properties. Smoothness, although as far as I know not being a standardized physical property, could even be measured physically (I think of a wheel of defined size, measuring the vertical deflection while being dragged along the way). Obviously, this would be very unpractical. But when you honestly try to classify the roads you know into that scheme (based on wether you would drive on it with the vehicles I mention), you will see that the classification is pretty unambiguous in *most* cases. But I think this is very similar to the width of a road: although it is a physical property, few people would actually bring a rule and measure the width, most people would guess. Still it is very good to know wether the width is 2m or 20m, or wether the smoothness is excellent or horrible. --Chrischan 11:36, 1 June 2008 (UTC) Catastrophic? I have to say that I'm not so sure about "catastrophic" for the lowest value, it doesn't seem to fit with the others. I suggest "horrible" as an alternative. I'd support the proposal though. --Hawke 15:20, 30 May 2008 (UTC) - - Hawke, why do you think "catastrophic" does not fit with the others? I actually do not care about the values at all, I just want the schema ;-). But maybe I should add Alvs idea to have one more tag essentially saying "no wheeled access possible" beyond the 4wd access value. --Chrischan 11:42, 1 June 2008 (UTC) - It just doesn't fit with the rest, in my mind. "How was that sandwich you ate today?" "Oh, it was catastrophic!" doesn't work. Or -- "Hey, I want to go for a ride on Foo Lane; how's the surface quality?" "Oh, I wouldn't ride there, it's catastrophic!". "Catastrophic" to me would give a degree of badness to something that was already bad ("I had a catastrophic accident on my bicycle today"). - I do like Alv's idea of a sixth grade beyond the 4wd level. Perhaps "impassable" would work, especially if this is intended to apply to wheeled vehicles only. Bipeds are quite good at navigating obstacles, and if it's impassable by them, we probably shouldn't be mapping it as any sort of routeable type.--Hawke 16:26, 2 June 2008 (UTC) - How about "very bad", then catastrophic as the lowest value. Otherwise it's too big a jump from grass to mountain tracks. --OliverLondon 16:28, 2 June 2008 (UTC) - I started mapping tracks as I was hiking this week end with the smoothness tag in addition of the highway=track tag, and it turns out that I mapped a lot of tracks with the lowest possible quality ( smoothness=catastrophic ). But I doubt any 4wd could pass the tracks I went to so I missused that tag because It lacks "above" (or below ;-) ) catastophic. So I wonder why those tracks were there If no 4 wheels vehicules can use them ? The answer to my question came 10 minutes later as we crossed their way : 2 differents 4 wheels vehicules, a tractor and a "Quad" ( in french ). So, I am in favour or adding a "horrible" or whatever we should call it level to increase to 6 the number of smoothness tags in the goal of mapping what can drive on after a 4wd. To my mind, Mountain Bike can drive where 4wd ( not the army ones) cannot, the "horrible" tag should fit for 4wd and the "catastrophic" tag for Mountain bike & Tractors & "quads" Sletuffe 13:34, 3 June 2008 (UTC) impassable ? ok this looks better because it's less subjective than catastophic, but I don't think it's ok either. Why ? Answer this : how could a track be impassable by 4 wheeled vehicules ? It cannot, by the fact that it was created as a track in the goal to make passing possible what's worse than horrible ? I'm not a native english speaker ? or could we insert a "very_bad" between bad and "horrible" ? Sletuffe 15:43, 4 June 2008 (UTC) - I think impassable wouldn't be applicable to tracks. On a footway, it would say that it wouldn't be passable by mountainbike. It's not a value that would be used much, mostly there for completeness. Robx Laterally varying smoothness - In fact, it doesn't need to be specified. The proposal is quite usable the way it is right now. I'd suggest voting on this as is, and then considering refinements such as smoothness=bad plus smoothness:left_border=good plus left_border:surface=painted_paving_stones. If you encounter a way that doesn't quite fit, add a note or invent some appropriate tag. Robx 18:32, 8 June 2008 (UTC) Vote? (and what about sand) Since discussion seems to have died down without major objections, how about taking this to vote? I did come across a minor problem: In the local forests, there's some deep sandy tracks (partly bridleways). Since they're barely passable by wheeled vehicles, I'd tag them smoothness=bad, but arguably they're really quite "smooth". Robx 07:42, 30 June 2008 (UTC) - Same as you, I'm using it for a while now, and would be sad to see it dropped ;-) - For your remark about "smooth sand" but passable ( only by 4wd ? then I would have tag it smoothness=horrible ), I forsee some confusion just because of the name "smoothness". If I understand this proposal correctly, and as I was saying here before Chrischan transformed it into a nice proposal, the real goal of it, as mentionned here in the proposal : The smoothness of a way should be assessed solely based on the usability of that way by the vehicles mentioned above, NOT based on the surface properties - In clear, even if it is a perfectly smooth surface such as a wall, because it isn't passable then it shouldn't be tagged with smoothness - Ok my example is bad because we don't tag walls, but I'm sure every one get the point Sletuffe Accessibility / Usability? I like the idea behind this proposal: "This is my whole point: as a user of a certain road or path I am only interested wether I can drive on this road or not." What I do not like are the names. If what you are after with with this tag is whether you can use a road with a particular type of vehicle and not how smooth the surface is (this is just a means to indicate whether you can use the road) than I think the name should be rather accessibility or usability. This is also why I proposed to extend the access tag to cover the semantics but it seems people prefer to reserve this tag for legal access restrictions. Something like accessibility=(car|hc|4wd|tractor) would work perfectly for motorized vehicles and is actually the way how it is done in most maps that I know. It has also the benefit of largely resolving the sand problem as well as the discussion about subjective scales (what precisely is the difference between bad and intermediate etc.). Above all the meaning will be clear for the users of the map (the meaning of accessability=HC is much more obvious than smoothness=intermediate). The only problem I see is that things like roller blades only interested in excellently smooth pavement will not be covered anymore. But such "vehicles" are really rather interested in the surface property and should be covered by the surface tag. Ukuester 15:58, 4 July 2008 (UTC) - I agree with you too, what we really need more than "is it made of grass, sand, cobblestone, stones, asphalt, smooth asphalt, asphalt ( that the surface tag can handle) is the usability of a way, and I feel that "smoothness" doesn't serve it well ( anyone comming very fast to this proposal would think it's intended for roller, skate or jogger ). Also I don't want to forget them, it's to my mind a secondary need. - You are saying it would bann "roller blades" why not ?, if I continue your idea, why not use accessibility=roller_blades ? - (by the way what is an HC ? ) - I would prefer usability rather than accessibility, and would propose something like : - When reading my table, I might be agreeing with you that the 2 first might well be dropped and returned to the surface tag. But not sure because maybe someone will imagine a different surface type than asphalt where roller could still go. - The only thing I am not happy with in this table is the fact that the tag refers to one and only one vehicule while I'd like to refer to a "group of" - example, my "car" would better, but longer, be "any_vehicule_group_that_can_drive_where_a_car_can_drive" - Usability Usability ! that what counts. - using surface=asphalt and saying rollers can use it will fail when later someone add à surface tag that is different but still usable. - Is it easy to see that I hate the surface tag, don't use it, and don't understand the need for it ? - My point of vue might also be transposed to the way the access tag is used. We should think in terms of "group of vehicule sharing some properties" and "group of surface type sharing some properties" or else a routing program ( isn't it what we want in the end ? ) is unable to take into account all tags and variation that are added all the time to those tags. - HUGH !, this is the friday thought Sletuffe 18:51, 4 July 2008 (UTC) - HC stands for "high clearance". For most tracks that a passenger car can not navigate you wouldn't need 4WD but simply a sufficient high clearance which some 2WD Jeeps have. The typical hierarchy for unpaved/dirt roads in the US (where this type of road is much more common than in Central Europe is "any passenger car can use" - "requires high clearance" - "requires four wheel drive" (example). I'm fine with using "usability" instead of "accessability" to make a more clear distinction to "access". I like your scale except that I would want to have hc added between car and 4wd. The fact that groups of vehicles are meant instead of particular vehicles should be made clear in the documentation of the tag. I would like to see a comment by Chrischan though. :-) Ukuester 11:58, 7 July 2008 (UTC) This sounds like a totally separate proposal from Smoothness. You might want to create a new proposal and move this discussion over to it. --Hawke 16:38, 7 July 2008 (UTC) - I disagree. According to the proposal the rationale behind smoothness is "This is my whole point: as a user of a certain road or path I am only interested wether I can drive on this road or not." I tried to make this more explicit than it was in the original proposal. Please explain why you think that this is totally separate. Right now we have a proposal surface, another proposal additional surface values, a third proposal tracktype, and a fourth proposal smoothness which are all closely related. I don't think a fifth proposal usability will make thinks any better. Ukuester 07:34, 8 July 2008 (UTC) - I was mostly referring to Sluteffe's table, which is effectively another proposal. Your "accessibility" tag is also another proposal. --Hawke 06:01, 10 July 2008 (UTC) - I also think this discussion should stay here, because indeed it is what I intended with this proposal. Actually something like this was one of my first thoughts. But then I decided to propose it the way I did, because I think "smoothness" is exactly what I want to describe. With the tagging scheme above, I see two problems: - as mentioned above, I would like to address the "smoothness" independent of a particular type of vehicle. Ofcourse it could be mentioned in the documentation that a way for racing bikes should be tagged as "sport_car", but people only into biking would probably not start using this tag. Likewise, people driving in cars would probably not start tagging something as "roller_blade", because they think this is something for the roller blade crowd. - More important, we get into conflict with other tags. Many people might imply that they can use a way with "Usability=sport_car" with their sports car, although it might be a road without car access ("access=no"). It would also be very strange to tag a 50cm wide path in the alps with "usability=4wd" (although it definitely can't be used by a 4wd), only because I want to make clear that I can use it with a mountain bike. -Chrischan 20:29, 8 July 2008 (UTC) - The 50cm 4WD path is a point well taken. Unfortunately, you can also turn this argument against your original proposal. How do you tag a 2,50m wide track which has two very smooth drive traces but requires HC because the cross cut profile of the track looks like this: __x^x__ (smooth traces left and right but a something in the middle that would cause every passenger car to hit the ground)? I'm lacking the proper English terms for this but such tracks are not uncommon. If you tag it with smoothness=bad people driving in cars will know they can't use it but people riding city bikes will assume they can't use it either, although they actually might be well able to do so. To me it looks as if usability by bikes and cars (not to speak about other types of vehicles) might actually require different scales. :-/ Ukuester 08:20, 9 July 2008 (UTC) - I agree with what Chrischan says, and disagree that you've made that argument against the original proposal. IMO That would call for another access tag (high_clearance=* or access:high_clearance=* perhaps? I think naming the values after particular modes of transport, such as accessibility=sports_car is nonsensical because of the complications that arise when you see a way tagged like that but which you can't take a sports car down. "bad" doesn't have this problem, and as long as objective standards are used for deciding what a "bad" or "good" smoothness is, it doesn't have the ambiguity that the original post was concerned with. --Hawke 06:01, 10 July 2008 (UTC) - The question the proposed tag is supposed to answer is whether I will be able to use a particular road/track/path with a particular vehicle. Now how do you use smoothness to tag the track described by me above and make clear that it can be used by pretty much any type of bicycle but only by cars that posess high clearance. According to the table on the definition scale its impossible (the reason is that there is no complete ordering among vehicle types such that one vehicle can use all tracks usable by a "larger" vehicle). Of course a car specific tag clearance=* would do the job but the need of an additional tag suggests that the proposal is unable to really answer the question it is supposed to answer. It seems to me that usability by roller skates and racing bikes (and probably trecking bikes) could be handled resonably well by the surface=* as well as the smoothness=* tag. To know whether I can use a footpath with my mountain bike I would need to know the maximum steepness (not covered by neither smoothness=* nore surface=*) and the amount/existence of "steps", big rocks etc. (somewhat covered by smoothness=* but rather not by surface=*). Actually, for mountain bikes some scale denoting the technical difficulty similar to the proposed hiking scale might be usefull. For cars I need to now whether I need 4WD (related to the steepness and the surface) and whether I need HC (related to the existence of clefts, rocks, etc.). Both is not fully covered by neither smoothness=* nor surface=*. To me it seems that all these aspects cannot be squeezed into a single tag because the question of usability is multidimensional. The question now is, whether we are better of with smoothness=* (and some additional tags) or with usability=* with multiple values listing the vehicles able to use a road/path or with splitting all the information about a highway in multiple tags as proposed below. I agree that in any case we should and would not tag a smooth footpath with usability=sportscar and that we would not list all vehicles able to use a particular highway but make reasonable defaults/assumptions (e.g. any highway usable by a passenger car can be used by a trecking bike). Ukuester 10:02, 10 July 2008 (UTC) - The argument here seems to be that the proposed smoothness=* isn't enough to tell whether a given way is usable by a car with a certain amount of ground clearance. My proposed solution: - Reword the definition of smoothness=* so people don't think it's the be-all and end-all in usability-tagging. It just says whether a way is smooth enough to drive with a given class of wheeled vehicle. - Propose a separate tag clearance=* or whatever that states how much ground clearance a four-or-more-wheeled vehicle needs to use the given way. - In my opinion, smoothness=* is well-defined as is, providing a nice balance between detail and simplicity. It's a usable tag (I've been using it a lot already), and if there's some special cases it doesn't cover, so be it. Robx 10:53, 14 July 2008 (UTC) - Ok then, we have to move forward. I'm ok with the name "smoothness" also I'm still scared about confusion, but a nice description might do the work. ( I also suggest to remove the "surface examples" colum to minimise confusion ). - Ok also not to use "vehicule centric" tags and stay with excellent/good/intermediate/bad/horrible - I also accept that we cannot "as is" deal with left/center/right changing smoothness, but other tags might be created for that purpose - If the global idea is ok for most people here, I think we could move to voting - I however d'like to point some refinement : Sletuffe 15:53, 15 July 2008 (UTC) Missing vehicules Also I'm globaly happy with the main table I want to add refinement in the goal of not forgetting some vehicles while keeping actual compatibility. - Has Ukuester mentionned a car with High clearance cannot fit in any tags but is able to pass ways where normal car cannot while it is not able to pass where a 4wd can. - I also think tractors/quads/Trials are not taken into account and we might loose, in the mountains, special usability ( maybe also contributors from forest managers ) ONF (france ) Here is my proposal : - I still have problem understanding what impassable will be used for - I think mountain bikes can go where 4wd have to stop ( dispending on pilote's legs ! ) Sletuffe 15:53, 15 July 2008 (UTC) - I guess impassable would mean no vehicles. I added a lot of example pictures (that I would like to see how they would be tagged) and one of them cannot be navigated even on a mountain bike. If you are very good, you might be able to go it down (although it's pretty tough) but certainly not up. Ukuester 18:33, 20 July 2008 (UTC) I don't think this tag alone describe the surface better than the other tags for surface and tracktype. This may fit for wheeled vehicles somehow, but why use the subjective keys and don't use directly the size of wheels that works on this surface? I suggest to use a combination of tags to describe the surface. Some of the tag may even be subjective. The usability tag above is a start. We may extend the surface tag from paved/unpaved to describe better if it's sand, asphalt, concrete, stone, grass. - example: An old shabby residential road highway=residential, width=5, surface=asphalt, smoothness=coarse, usability=bike, clefts=yes, minwheelsize=25cm - example: A narrow track with paved surface in good condition highway=track, width=3, surface=paved, smoothness=fine, usability=roller, clefts=no, minwheelsize=5cm Of course you don't need all those tags for each road. You can assume some defaults. The last example don't need the usability tag, it should be clear from other tags that the surface is usable for skates --Andy 14:20, 9 July 2008 (UTC) - Nobody's claiming that smoothness=* alone describes the surface of a way completely. It can be used independently of the current tracktype=*. You're free to propose additional tags for capturing the type of surface more exactly. Robx 10:57, 14 July 2008 (UTC) - Ok, see, this is maybe a case where someone missunderstood the smoothness=* tag. smoothness=* is not intended to describe the surface of a way. It's just only about usability. - I however note that your idea about a tag called minwheelsize=* + using width=* could maybe solve our problem - But I am not completly sure that size of weels is enough. Maybe a F1 with big wheels while not be able to drive on a track. Adding the surface would help, but then we would loose the easy use of smoothness=* describing usability in one tag Sletuffe 16:05, 15 July 2008 (UTC) - Most of the vehicles mentioned in the table above (sports cars, racing bikes, mountain bikes, 4WD cars, ...) have the same wheel size. Thus, I don't think wheel size is going to help much. But your comment "smoothness is not intended to describe the surface of a way. It's just only about usability" highlights that surface is what people think when they read smoothness. :-/ Ukuester 18:24, 19 July 2008 (UTC) I agree we really need a more general tag describing the surface conditions of the highways like this smoothness. - I would preffer, if it would deprecate the tracktype. Would be a mapping reasonable like grade1->good ... grade5->impassable? - I'd like to deprecate tracktype too, but I'am scared there is no mapping at all between smoothness & tracktype and not the same goal in the end. - I don't personnaly understand the usage of tracktype, and it seams to me many are not using it the way it was intended to be used by using it as a scale to describe how hard is it to drive on a track. Usage which should be better covered by the smoothness tag. - If you look closely at the describtion, you'll find grade1 is duplicate of highway=unclassified - and that grade3 to grade5 is very vague with many terms like "A mixture of", "quite compact", "tire marks" compared to "subtle tire marks". All that seams very confusing and subjective to me. - For exemple, should I tag a track with grade4 in winter and then grade5 in summer when grass has grown ? - For me, tracktype is an "in between" surface tag and smoothness tag Sletuffe 11:19, 10 August 2008 (UTC) - What about the hiking tag? Shouldn't there be only one tag describing the usabillity for wheeled vehicles and for use by foot? - I don't think so, we shouldn't bother people who don't care about hiking by creating a single global tag Sletuffe 11:19, 10 August 2008 (UTC) - But tracks are quite often used by vehicles and by foot. So you need two different tags for describing the same condition of the same way. I would preferre a mapping of the hinking values to the smoothness and probably extend the smoothness for ways where riding is not possible any more but where we can still make a difference for usage by foot.--De muur 08:41, 11 August 2008 (UTC) - And what default value shall be assumed, if no smoothness tag is set? Default value for surface is paved, so it could be either Excellent or Good.--De muur 11:39, 7 August 2008 (UTC) - I suppose something like "bad" for a track, "good" for other highway and "excelent" for cycleway should be enough Sletuffe 11:19, 10 August 2008 (UTC) Examples Some examples to discuss and illustrate the taggings. Another proposal I think the original proposal has not enough values. And for non-english speaking people it is hard to find the difference. I'm very interested in this probosal, because our car has a very hard suspension, and it would be nice to find a route with good streets. I travel to ukraine sometimes, and there it can be really horrible if you choose a bad route. In germany we have some streets which have a very good asphalt surface, and it looks like an excelent road. But with the car they are very uncomfortable, because the asphalt is on top of a very old cobblestone road. (after reunion of germany they tried to repair the roads in east germany very fast) This roads could be good with skates, but horrible with cars. I think for skates the surface material is an information which is more useful. Here is my proposal : Please say what you are thinking about this proposal.. --TEL0000 23:36, 8 August 2008 (UTC) - I don't like the numbers, as they are harder to remember. The "level 8" and "level 9" are pointless, at this point it's not a road (9 is a joke?). It also is very subjective, more so than the original proposal. e.g. "feels uncomfortable" depends a lot on the person and indeed the car. --Hawke 00:18, 9 August 2008 (UTC) - For me only 1 to 7 are important, because i'm driving in car. For me the numbers are more easy to remember, than the english names, because my english is very bad. I agree with you, that it depends a lot on the person, and the car, but i don't know how i can explain the smoothness better. --TEL0000 22:38, 9 August 2008 (UTC) - I don't like numbers either, because we cannot extend it later if we find a need between 2 and 3 ( 2.5 ? ;-) ) 1 and 2 ? are german road uncomfortable ? - for the rest, you want to distuinguish the comfort of a road, then the surface tag is made for that - because smoothness cares about the usability of a road Sletuffe 11:34, 10 August 2008 (UTC) - I agree with you, it is hard to extend it later. So maybe words are really better. But anyway we need more words, than the original proposal. :) The most german roads are comfortable, but in east germany there are still many uncomfortable roads. And in Berlin they can't repair the roads enough fast... - You are right, i was thinking about the comfort of the roads. I thought smoothness is the right tag for it. I think surface is for the material of the surface (cobblestone, concrete, asphalt, dirt). But cobblestones can be comfortable, or very uncomfortable, depending on the quality. The same with concrete or asphalt. --TEL0000 19:31, 10 August 2008 (UTC) Moving to vote period ? As no one has raised comment to improve or refute the original proposal updated by my and Ukuester's version. I'd like to propose moving to a vote period. Starting it the 1st september ( to let people come back from holydays :-) ) Sletuffe 12:39, 13 August 2008 (UTC) Moved from another page - quantizing status A fella with bad speling kindly advised me to move over here, so here I copy myself from there, which would apply to smoothness. The significance of my copy is that (there) I tried to define the meaning of the - abovementioned subjective - terms. We definitely need this, even if it's not consistent to the exact level all over the world, because route planning could put this variable in good use. This is not a final design, just trying to show how to quantize a bit more general than telling "you can go on this way by 3 wheeled yellow skateboards if you are medium experienced", whatever that should mean. ;-) Others tried to mention other "possibilities", but please realise that most of them seems to be designed for tracks (cycleway, footway) and not highways. If I have repeated old arguments, apologies. If I offended someone, apologies. Generally forgive me for being existant. :-) But comments are welcome nevertheless. --grin ✎ 10:54, 23 August 2008 (UTC) - Maybe what you want in the end is, like it was said near the end of : Proposed_features/Smoothness#Another Proposal is to describe the "comfort" of the road. What (I think) we want here, is the "usability" or "passability" of a road. Even if I need to drive at 5km/h to go with my car, that's a possibility my routing program should take into account. - I like this new proposal. But if this page is about the usability or passability, is there any other proposal-page for the comfort of the road? There are so many resembling proposals now, that i don't want to open a new proposal again... --TEL0000 02:33, 24 August 2008 (UTC) - Same issue from a roller-blading point of view. A road with 'excellent' smoothness would be great (a fun place to go to especially for skating perhaps), but then a road with 'good' smoothness might just be more uncomfortable on roller-blades. Seems like just a problem with the descriptions. Maybe 'uncomfortable for type x' bits should be added the description. -- Harry Wood 15:39, 22 September 2008 (UTC) - If we introduce a concept of "uncomfort" then It would become even more subjective, and I don't like that, however your point is interesting, good and excelent are too close in description, and it's quite clear that you can be roller-blading where a racing bike can drive. Maybe we should drop excellent by merging it with good. Sletuffe 21:41, 22 September 2008 (UTC) - In you'r proposal, the advantage I see for routing is to decide between different roads wich is faster, then you'r "maxqspeed" could do the work Sletuffe 00:45, 24 August 2008 (UTC) Oh, And this should be relative to the material of the road. So if the road's made of dirt (is there a material tag?) or unpaved then "good" means a good unpaved road, even if it's not "good" for a Porsche. --grin ✎ 10:56, 23 August 2008 (UTC) - I hope the surface=* tag will evolve to take many other "surface values" into account - 'relative to material' Mmmm, sounds a pain for routing algorithms Sletuffe 00:45, 24 August 2008 (UTC) And the most important may be not obvious: this should work for highway=motorway, highway=primary, highway=secondary, highway=residential, etc. too! --grin ✎ 11:02, 23 August 2008 (UTC) - Yes it does ! "Apply to linear" so any way can get the smoothness tag. But a reasonnable defaut for all ways should be choosen to avoid "over tagging" - By the way, sorry for "inserting" my comments inside yours, but it was quite long and I wanted to multi-part comment ;-) Sletuffe 00:46, 24 August 2008 (UTC) Weather conditions Reading this one could think that all your tracks are inside a mall. We need a system that considers dry, wet, snowy and frozen ground differences. For instance some kinds of paved ground can be very slippery when wet for inline skates. Other ways turn impassable when muddy. We should not start a new system that does not consider weather conditions. We have enough systems that don't care for the weather. --Lulu-Ann 15:03, 22 September 2008 (UTC) - I don't agree, for now we have NO system that deal with usability at all. So even if that proposal doesn't deal with wet/snowy condition that's still a step in the good direction, we could later increase it with a system like : smoothness:wet=very_bad or smoothness:snowy=impassable. But even then, that would become complicate, will you map every possible snow thickness between 1 and 20 cm ? Sletuffe 21:52, 22 September 2008 (UTC) Mountain bikes vs. tractors I'd imagine that a mountain bike is normally less able than a atv or a tractor. Naturally some sporty people might do "parkour on bike" just like they even compete with trial bike, but I wouldn't consider that "usable for travel". Factors limiting travel by tractor and mountain bike are (approximations here, feel free to adjust and add what's missing) Alv 09:08, 4 November 2008 (UTC) early approval and last unilateral modification This Proposal has been Approved by majority (18:6 on 2008-11-02) - Created Key:smoothness - Removed very_* because no-one can guess the difference between horrible and very_horrible. - Instead of impassable access=no should be used! --Phobie 15:26, 2 November 2008 (UTC) - Hey ??? how can you take such unilateral decision of that kind without discussing it first on the talk page ?? I'm moving it to the talk page and undoing your changes Sletuffe 17:16, 2 November 2008 (UTC) - Let's talk about it first if you wish : - Approval, ok, if no-one is voting on it anymore we could move it to approved features - remove very_* : "no-one can guess" and so what ? is the feature page at all guessable ? no. There are descriptions made for that - access=no Instead of impassable : well, then you didn't understood this proposal or didn't read it. smoothness is intended to be a physical propertie, while access is a right propertie. nothing forbids a way from being impassable AND access=yes Sletuffe 17:23, 2 November 2008 (UTC) - Other than perhaps common sense. A right of way that is impassable is by definition not a right of way. Chriscf 09:33, 3 November 2008 (UTC) - Other countries might not and don't have a concept of a right of way, in the sense used above. Alv 10:04, 3 November 2008 (UTC) - This is moot. It's generally accepted that a right you cannot exercise is no right at all. access=no for ways that are impassable at all times makes sense. Remember that highway=steps already implies motorcar=no, which equivalent. Chriscf 14:03, 3 November 2008 (UTC) - Well we don't have a such rights at all, we have the freedom to travel, so claiming that anything with highway=* requires a "right of way" is just not valid worldwide. (Here only building a road on others' properties is a right that can be given, bought or acquired.) Alv 09:08, 4 November 2008 (UTC) - Impassable = access=no. End of discussion. Chriscf 11:04, 4 November 2008 (UTC) - (I haven't been pursuing the tag nor the value impassable, my comment was solely on that right-of-way remark...) - As the definition used in the proposal now is and has been, admittable. Probably what made me refrain from voting, was just the implications and the lack of intertwining this with access definitions. Now anything with smoothness=very_bad to very_horrible could imply motorcar=no but it even doesn't... If I were to want to find where access is only physically restricted or difficult but not forbidden (say, to find best places to propose that the city takes measures to improve the connectivity), they'd all be motorcar=no when I'd benefit from some of them being motorcar=obstructed or the others being motorcar=forbidden. Or I wanted to make a routing software for situations justifiable by necessity, I'd need to know what is just forbidden but faster and what is a physical dead end. But it's not (yet) in my interest to pursue such changes. Alv 12:10, 4 November 2008 (UTC) - Approval: Normal votes takes 2 weeks and vote-time gets extended if you get too few votes. This vote was set to 12 weeks! After 6 weeks acceptance by the community was more than obvious... - Remove very_*: Yes, this was a arbitrary effort to create "key" which is goot for OSM. I will add those senseless values to Key:smoothness if you need that. - I read everything here. While the key has been approved, the values impassable and very_* seems not to get a clear approval. Since smoothness is a generic key only minefields and active volcanos are impassible by all kinds of vehicles, horses and passers-by! Things like motorcar=no has always been used for ways which are impassible by cars. It would make more sense to use motorcar=impassible and have a vehicle-specific value than using smoothness for that! - --Phobie 00:48, 4 November 2008 (UTC) - no problem for approval for me - very_* : yeah, thanks, I'll do it myself - As you said earlier, there are 24 votes on the proposal which include very_* and impassable. Don't take a shortcut saying it was not clearly approved while it was. I won't say impassable will be useful, and I personnaly would have dropped it and won't use it, but HERE, we respected a democratic process, and because the guys who added impassable have their reasons I ignore, I respect the process and will keep impassable. Create a proposal deprecation of very_* and impassable if you which, but don't change the content of this proposal after the vote. Sletuffe 09:11, 4 November 2008 (UTC) - I personally didn't even vote on this because I still plan to have a stack of photos to classify by several different surface criteria and only then make up my mind about the relevant factors. But since this is likely to be used, I think that it should be with values that offer reasonable benefits over the old tracktype=*: without the very_* it's impossible to differentiate between - tracks that have gone bad enough that a normal modern day car is likely to scrape it's undercarriage but where an older car is very much usable from tracks where both are usable. Yet getting a rickshaw over the bumps of the worse class can be most difficult. - tracks that are very much usable by an old and slow car with high clearance - or some SUV's - and other's that require a Jeep with raised suspension, off road tires and lockable differentials - say a road to a remote village in the jungle. Tractors are on a par with ATV's but much more able than any non-off-road-equipped car and that difference is easy to spot. Alv 09:08, 4 November 2008 (UTC) - And as to impassable, I think that it would be usable later when a tagging for seasonal variations is agreed upon; say smoothness=horrible + surface=sand + seasonal:spring:surface=mud + seasonal:spring:smoothness=impassable. Alv 09:08, 4 November 2008 (UTC) - Alv ! You enlighted my mind ! I now know for what purpose impassable could be used for : In france we have (a quite special case) a tertiary road that is exactly 1 meter above see level. Due to [tides] this road is usable only 12 hours per day and the 12 other hours it is under 1 meter of water and so unpraticable by any wheeled vehicule. While we don't have the time variation smoothness, I'll certainly tag it with impassable Sletuffe 10:01, 4 November 2008 (UTC) - Democratic? I read OSM was meant to be anarchic! All those proposals are only there to create a best practice guide. But still everyone can use his own tagging scheme. If you really think smoothness=impassible is usable it should be kept. But keeping it because of some wikilogins posting {{yes}}-tags (without comment and without adding anything to the discussion) is not the best idea! I think motorcar=impassable and motorcar=forbidden is a much better idea! --Phobie 20:11, 5 November 2008 (UTC) elaborate on 4wd - Somebody please elaborate on the meaning of "4wd" as used in the tag definition: a 4wd Audi all-road & high clearance Subaru Forester (4wd) - stock 4wd pickup - stock 4wd Jeep - 4wd Jeep with raised suspension, off-road tires, limited slip differentials etc.? Alv 09:08, 4 November 2008 (UTC) - This is a very clever question ! thanks for asking it ;-) And the problem is not that simple, the definition asks for an "image" we have in our head of a 4wd, and unfortunetly, there are so many on the market, that my basic 2 traction car is sometimes better at going on a track than a 4wd Panda "plastic toy" is. However, since the proposal talks about a scale, we have to assume by reading it that a 4wd is "better" at going on crappy roads than any other transport means listed before. So I would say a 4wd in this proposal is something like that : [4wd in snow] or [in mud] Sletuffe 09:19, 4 November 2008 (UTC) - These two pictures appear to be the same. :-) Certainly a better name than "4wd" is needed, since this is a specific technical term that refers to the drivetrain of a vehicle, meaning only that all four wheels are powered. This includes standard road vehicles such as the Audi A4 and the Ford Mondeo. Chriscf 09:51, 4 November 2008 (UTC) - Yeah, clearly the same, because in my mind, there is only one type of 4wd, but that's because in french we call a 4x4 a car that is able to drive on very crapy roads. And we almost dropped it's original meaning of having four powered wheels. The Audi A4 is, to my mind not a 4wd while unfortunetly, it is.... I then agree 4wd is unclear... what else could we use ? All terain vehicule ?Sletuffe 10:12, 4 November 2008 (UTC) Talks about default values At the beginning of this proposal, their was no default values so, in the final accepted one, there still are no defaults values. However, could some be supposed in many case to ease the pain of mappers ? I would propose : - Without a smoothness values, - highway tags are supposed to be tagged smoothness=good - except track that is supposed to be tagged smoothness=bad Sletuffe 09:41, 4 November 2008 (UTC) - I think default values are a stupid idea, because the tagging in OSM is typically incomplete. Rigth now we have many thousand ways without a smoothness tag. Assuming one single default value for these ways is just senseless. - And when you define a default value, there is no way to differentiate, whether a tag is still missing or whether someone omitted the tag, because it is already covered by the default. - --De muur 11:50, 4 November 2008 (UTC) - That might be a "stupid" idea, but that's allready in use in many case. Either we have to define a new way to tell something is missing, or not mapped (I'm working on it if you want to help : see Proposed features/internal informations between mappers or using defaults until that. - Wether or not we explicitly say there are no defaults, there will be in the developper's mind that makes a navigation software and that's allready the case for other cases. Sletuffe 12:12, 4 November 2008 (UTC) - Without a default value, a missing smoothness tags means, that we do not know the smoothness of the object. And for all the existing items in the data base this is the only correct assumption. - Since in reality each object has a smoothness, there is no mixing between not present and not known for this tag. So you do not need default values and you do not need to define mark for a missing smoothness tag. - --De muur 12:00, 5 November 2008 (UTC) - We are talking about that on the talk@ list, and as I am constructing my mind, I now think that defaults, for any kind of feature is bad juste because, like you said, we cannot tell for sure, wether the mappers decided not to set one because he doesn't know or because he knows the default was enough. I'm ok to drop defaults on this feature, renderers and routing software will decide on themself Sletuffe 14:50, 5 November 2008 (UTC) Next step : deprecation of tracktype ? I fear there's gone a be a lot of opposition, that's why we didn't mentionned that in this proposal, but that's the next step I think we need to take. The tracktype tag has many problems I mentionned on the surface and tracktype page, and I think people are notmiss-using it because it's not clear and not efficient enough. Only future will tell, but I have great hope that people will find the smoothness advantage over tracktype. So I'm going to start a separte page ont this idea of deprecating it Sletuffe 11:15, 4 November 2008 (UTC) - When you have objective criteria and a less stupid value set. Not before. Chriscf 11:30, 4 November 2008 (UTC) - Have you thought of better tag values yet? It remains the case that we cannot have the values listed here in Map Features. They're subjective, and don't tell people anything useful. Most importantly, new mappers can't learn anything from it. They see a road tagged with "name" and "ref" tags, they can guess what they need to tag in their own ways - they can't do that with this. Any scheme for this property must be intuitive. Chriscf 17:35, 20 November 2008 (UTC) - "We" most definitively can have, it's not in your power to tell those bastards that voted on this that they cannot have it. Alv 18:02, 20 November 2008 (UTC) - It clearly is in my power, because I just did it. The existence of a vote does not bind us to stupid outcomes. Chriscf 12:25, 21 November 2008 (UTC) - Usage will tell if people find the Tag useful, having them in the Map Features is just one step towards wider usage. Concerning the subjectivity: Unless someone proposes better values and definitions, I find it a rather useful compromise. It's just pretty hard to define an objective tag describing the surface quality, since judging the surface quality is already subjective. Or how could you do it, aside from counting every bump? --Driver2 20:07, 20 November 2008 (UTC) - I must admit you are quite right, yeah those values are not quite intuitive, but we have all search for, and no one found any better. Because, probably, like Driver2 said, it is a bit subjective, but just a bit : If you are using rollers, then no chance for you to drive on a mountain track. But any how, we have come to a point that we thought (at least those who voted yes) that having it was better than not. And in regard to tracktype=* gradeX are not much intuitive, but more than that, to me at least, the description is not intuitive either. And guys from the surface=* have tried hard to cover all possible case of the nature of a track or road without being able to answer what many people wants to know : "Can I go there with my car". I don't say smoothness=* answers this perfectly, because where someone would stop by fear of damaging his car, some other, with the exact same car, will try and perhaps manage to do it. I would end by saying that not only does a tag can't solve it, but not any explanation of anyone will either, so we try to keep in this tag the maximum description to what people await from a "passable by passenger car" while still knowing that so many other indescriptible factors will probably make it fail. Sletuffe 01:25, 21 November 2008 (UTC) - "Least worst" is hardly a justification. If you can't define the values for this tag objectively, we can't map it. Mapping is a process of recording facts, after all. - I didn't say we haven't define this tag objectively, neither I said it was subjective, this is not binary, I would say this tag is "quite objective" or, if you prefer "a bit subjective". If I take a track with very_horrible example for instance, this is near 100% objective to say that my racing bike cannot drive on it, and that is an usefull information. The description is not 100% objective in smoothess, because we can't extand it to cover every vehicules in the world. But If I follow your "Mapping is a process of recording facts", then I suppose you agree to deprecate tracktype right ? Many tag in osm have always a bit of subjectivity, tertiary VS secondary ? width ( did you take a rule to measure it ? ) and many others, so mapping is not, for me, of recording only 100% objective facts, because 90% of objectivity (even if figures cannot be applied to objectivity) is sometimes good enought to get an information from something. Sletuffe 13:46, 21 November 2008 (UTC) - We have ca. 300.000 tracks in the OSM data base of Europe and ca. 200.000 times the tag tracktype is used. I think this is quite a good quota, and I don't expect smoothness to reach such a level in the foreseable future. - tracktype, smoothness and surface all describe different factors of the same way. They are somehow linked to each other, but no one can substitude for the other ones. - --De muur 12:12, 4 November 2008 (UTC) - Maybe not in the near futur, but I bet a bear with you it will ;-))) Sletuffe 12:17, 4 November 2008 (UTC) - I predict that well see lot's of values besides the ones listed: entermediate, great, smooth, horible, horryble, verysmooth, verybad, veryexcellent, bad-, bumpy, gravel, ... But well see. Alv 12:22, 4 November 2008 (UTC) - Thats the case with every single Tag out there. There are always a handful values being used that are not documented. Either because people think more values are needed, just mix them up with something else or simply spell them wrong. Presets in popular editors can prevent many of these. --Driver2 20:07, 20 November 2008 (UTC) - You are not the first person who proposed a tag, saying nothing about deprecating existing similar tags or minimizing the risks of conflicts or confusion, got a positive vote from 15 people and try to impose the result to thousands users. The same happens with highway=path supporters which are now trying to deprecate footway, cycleway and bridleway. But when such activism leaves the wiki and comes to a wider public like the ML and renderers developers, the opposition is much stronger. So, please, leave existings tags, watch the statistics and wait 6 months. If your tag is really better, it will be voted by its popularity. -- Pieren 10:27, 21 November 2008 (UTC) - I have changed my mind about writing a proposal to depracate tractype, I think it would deserve smoothness as I won't be objective about it, and it will look just too much a propaganda. So I'll let usage make it's away. But still showing, whenever someone need it, that it exists. However usage is not only a matter of quality, If no one knows something exists, it won't be used, even if better ; so hiding it like chrisfc tries is not IMHO a solution either. Whenever a newcommer want to tag something he will use what is in the JOSM presets or will look at the map features. And then, he also watch at the renderers to see if his work is used. And wether they want it or not, as I said on the talk list, developers (of renderers and editors) have the power to influence mappers and they might be tempted to do so based on their own belief, and I belive that is bad. Yes it's a last security against bad tags, but refusing the wiki approach or any other means of communication is just somehow considering that their ideas are better than other's. I'll stop here or else I might well put another page of text that is outside the scope of this talk page. Ugh ! yeah, it's friday ! Sletuffe 13:04, 21 November 2008 (UTC) - As of the "path" example you gave, I have first voted no to it because It would mean I have to change my way of tagging and I am lazy. Then I came across many case where "path" was much better, then I revert my vote to yes and still no to deprecation. And after 6 month of usage, and at last mapnik of osm rendering it, I will now revert my vote and say yes to "path" and yes to deprecation. Time helps things. Sletuffe 13:15, 21 November 2008 (UTC) I would support deprecation of tracktype. I think its values were extremely poorly thought out. Chriscf has concerns that the values for smoothness are too subjective, but tracktype is far worse in this regard. --Hawke 13:49, 21 November 2008 (UTC) - Which is not a valid argument for this scale. We can't include this on Map Features - it's a really, really, poorly thought-out idea, and if it goes on Map Features people will start using it without understanding it. So, for now, it will be hidden on Map Features until such time as someone sorts the damn thing out. This is not a voting process, it is an approval process, of which voting is one part. It's also not binding until there is empirical evidence that it's a good idea. People not knowing and not tagging is infinitely superior than people not understanding and tagging inaccurately. Valid concerns were raised, which were ignored and not addressed. Chriscf 15:10, 21 November 2008 (UTC) - Looks like we are going nowhere, you talk about "Valid concerns were raised" but which ones ? have you read what I said ? can you tell me what's wrong with my point of vew ? have you anything else in your bag that "stupid tags, stupid ideas, poorly" ? Sletuffe 15:20, 21 November 2008 (UTC) - It's not a valid argument for this scale, but it's a valid argument for deprecation of tracktype, which is what this section is about. Your valid concerns were addressed: - smoothness=impassible is the same as access=no -> No it's not. - "4wd" is not a good term. -> Changed to "off-road vehicle" instead. - If you had other valid concerns, you did not raise them. --Hawke 16:08, 21 November 2008 (UTC) - [2] [3] [4] [5] [6] [7] [8] [9] Chriscf 09:45, 24 November 2008 (UTC) - You are also citing me and my valid concerns, but did you read it? I talked about anarchy, the philosophy of doing good things without having laws. The editwar you started on Template:Map_Features:smoothness is not one of those good things! --Phobie 04:10, 29 November 2008 (UTC) - Heh. Almost none of those are objections. The actual objections are here [10]. They consist of: - It would be better to improve tracktype=* than use this: If tracktype=* is improved to the point where it covers what this does, we can drop this one and use it instead. Of course, that'd entail finding another replacement for (since tracktype=* is bad just because it only covers highway=track and not other highway=* tags. - It doesn't cover varying weather conditions. It's not meant to, and would complicate things excessively to try. Basically, this is not the place for that. - All highway=* should be smoothness=excellent, everything else can be inferred from "gradetype tracks", whatever that is. No idea what "gradetype tracks" are, but it's clearly the case that not all highways=* are suitable for, say, inline skates. - Here's your objection, chriscf (and the only one you linked to in your list which was actually an objection): "the lack of criteria for differentiating between the different classes". Sorry, but the criteria are pretty clear: "usable by (vehicle type)" where usability is defined at smoothness=*. - Then there are a couple of opposing votes with no reasons given. None of them are showstoppers, and nothing has happened to give you (or anyone) veto power over the tag approval process. So please, just stop. --Hawke 23:54, 29 November 2008 (UTC) - You evidently understand neither the objections nor the process. Chriscf 17:35, 1 December 2008 (UTC) - I understand both. It is clearly you who doesn't understand the objections, when the people who made them (see Phobie, above) object to you citing them! The only serious objection in the list that you cited is subjectivity. That one is a matter of opinion, not a clear-cut problem. In any case, repeatedly hiding a feature which was approved in accordance with the process is not a part of the process. --Hawke 19:32, 1 December 2008 (UTC) - If you keep talking about "approved in accordance with the process", you evidently do not understand the process. For one, the official process does not depend on a majority vote. I'm not prepared to repeat myself again, so you can expect me to stop removing broken features from Map Features when idiots stop adding them, and not before. Chriscf 09:36, 2 December 2008 (UTC) - The Approval process says "8 unanimous approval votes or 15 total votes with a majority approval". No part of the process is "Chriscf approves it". You fail at understanding the process. --Hawke 21:09, 2 December 2008 (UTC) - Hawke, my dear, I am so sad to see you spend your time in vain against such a stubborn guy. We'd better spend our time on new proposal that are very hard to solve, such as the new access namespace you proposed. He is pointless, without arguments, without new ideas. Let's keep undoing his changes until some administrator takes the approprivate measures. After reading much on the mailing list (on which he didn't want to take part), people raised rather good comments (not too much objections) on which you answered perfectly well. I start thinking that if people want to tag perfectly and not subjectively a track or ice_ring, or else, they do as they want, they can propose if they wish 20 additionnals tags to smoothness to try to reach perfection. The result is obvious, noone will (except chriscf here present, and 5 other brave guys ) use it. In the end, smoothness will impose itself as beeing better, not perfect, but better to mappers. - We are on the bright side of the force Sletuffe 16:58, 2 December 2008 (UTC) Confucius say: man who cannot spell "deprecation" should not propose it. --Richard 10:02, 24 November 2008 (UTC) - No Confucius says: Man who cannot spell "deprecation" could probably spell it in his mother language. Let's change the default speech of the wiki to Spanish! --Phobie 03:45, 29 November 2008 (UTC) Limit Smoothness to road vehicles? Let me give some use cases to say why I don't think smoothness is usable for other means of moving. Considering a snowmobile. Any way if there is no snow will be unusable. If there is 1m of snow, most places will become passable, however for some places maybe there is a need for 2-3m of snow until it's possible to go on a snowmobile. Clearly, for a snowmobile this specification would not work at all. For snowmobiles other factors would become important, like snowdepth, temperature, avalanche danger, etc.... For a skier it's not so drastic but also clearly unusable. I think for both cases there is clear agreement that another classification must be setup. --Extremecarver 00:58, 20 November 2008 (UTC) - smoothness is clearly not for snowmobile, ski or hiking, the proposal talks about wheeled vehicule only and if you need it, create a new proposal for them Sletuffe 14:28, 20 November 2008 (UTC) - I don't need them (yet), but just wanted to give it as an example.--Extremecarver 14:57, 20 November 2008 (UTC) So let's come to mountainbiking that is included in the proposal for now, but had voices in the talk page above about inability to transmit all important information. The biggest differentiation must be made between uphill and downhill. While on uphill my technical riding level will matter to a certain extent, this extent is not as big at all as for going downhill. Therefore there are systems setup for mountainbikers, notably the IMBA in the english speeking world, and the singletrack skala in the German speeking world, maybe other language regions usually use even other classification systems, using such a classification, a much better differentiation can be achieved and will be asked for by participants of the sport. I see this as a chance for OSM to be able to cater for a wide range of different expectations, not only people who look for a streetmap.--Extremecarver 00:58, 20 November 2008 (UTC) - I clearly agree with you here, the mtb part of smoothness might not be well suited, there are talks somewhere I'll move to help creating a mtb scale Sletuffe 14:28, 20 November 2008 (UTC) I would not see the key smoothness as bad, but I think diversification should be held up more than simplification. In the end there exists no acces=no or impassable, it's just about the means you need to use the way. If many sports develop their own tagging scheme, after a while renderers will be able to see the similarities and use it for the better. There is a myriad of different tags related only to cardriving, other means of transport shall describe the ways they need for their needs with the same scrutiny. I support the smoothness approach for vehicles with 4 wheels, but I don't think it will be successful, because the needs are to different to put into one bag.--Extremecarver 00:58, 20 November 2008 (UTC) - I clearly agree once more, we "could" depracate the mtb part of smoothness and stay with motorized vehicules or with 4 wheeled vehicules. and create alternative scale for any sports - BUT ! I don't necessarly see it bad to include a thought in smoothness about mtb because, think of that : who will take care of setting tags for mountain bike only ? well, easy answer : mtb users only. And that is some loss of information : I am personnaly tagging with smothness in the goal of tagging for 4 wheeled vehicules and I don't care that much about mtb (well, at list for now, 'cause I have just bought one ;-) ) - The final result you are expecting by removing the mtb part of smoothness will probably end with the opposite : less informations added about mtb by people who don't care much about mtb. - smoothness=horrible or very_horrible is a very poor information for mtb, I admit that, but it might be added by people who don't care about mtb and in such, give information to mtb users. - If you want more precision, there is no problems in adding a mtb scale, but fewer people will contribute to that scale than to the smoothness tag, keep this in mind. So, in the end, I don't see problems in smoothness being somehow a sub-set of the mtb_scale but still independant. Sletuffe 14:28, 20 November 2008 (UTC) - I can accept that point of view, as long it is made clear on the front page, that for hiking, mtbiking etc there too exists more specific tags. For a non mtbiker the picture that a way is usable with a mtb, quad etc, might help in deciding which smoothness grade to give.--Extremecarver 14:57, 20 November 2008 (UTC) To my mind, the smoothness of a way would have to be set with reference to the primary traffic type of the way - so for a highway=primary,secondary,residential et al, the reference point would be a car. For a cycle track, the reference point would have to be a bike. Ditto for a footway (person) and a bridleway (horse). That would substantially reduce the list of possibilities when tagging the smoothness. If you are tagging a highway=tertiary the options pretty much come down to 'smooth' (all standard vehicles), 'bumpy' or 'rough/4WD' (or your choice of term for a proper 4WD, by which I mean a high clearance vehicle supporting either centre diff lock and/or low range gears). Pretty much every other possibility in between is really covered more by the surface tag (grass/cobbles implies you might need a decent clearance, sand implies smooth but still really only for 4WDs). - Mmm, your "pretty much come down to" looks a bit too restricted to me, what, if, in my country, there is a very smooth like glass tertiary road ? do you expect me to tag it with surface ? how do I say roller would be more than happy to roll on it ? - What is there to gain to drop to just 3 values ? ( use smoothnes++ smoothness-- or smoothness== ? ) appart from lazyness ? and missing the capture of some rare case ? Sletuffe 12:58, 27 November 2008 (UTC) - It is deliberately restricted to a small number, because I feel the fewer the number of options, the less subjectivity involved. You could have seven levels like the current proposal, but then you're basically back to square one with regards to subjectivity. A "smooth like glass" road and a very smooth road (but perhaps with a higher stone vs tarmac content) are in real use identical for the purposes of a passenger car/track/4WD. Your roller blade requirement is a secondary concern, as roller blades are NOT the primary use of highway=secondary. If you want to tag the way with reference to smoothness for a roller blade, then use something like smoothness:rollerblade=smooth. That way the primary vehicle type is applied for the smoothness tag, and other vehicle types (rollerblades, bikes, skateboards, segways and snowmobiles) can be tagged sparately as a relevant smoothness. -- gaffa 14:03, 27 November 2008 (AEST) For a bike path, then you might have 'smooth', 'bumpy' (ok, it's a bad word for it) and 'rough'. Same words, different meaning, but correctly referenced to the track type it refers to. Smooth works well for road cycles, bumpy means your probably need an MTB, and rough means you actually have to be competent on the MTB. Again, same for walking track - 'smooth', 'bumpy' and 'rough'. It's all still valid when you are walking, and again the surface tag (rocks, grass, marsh) adds the additional meaning, while still allowing the individual smoothness tags to actually be meaningful withoput necessarily having the surface tag. Trying to come up with a single list of values for smoothness grades for all track types and all modes of travel in one set makes it pretty complex. I agreed with the track type deprecation - the tag values are meaningless. As a fairly competent 4WD driver, what I regard as a grade 3 track, others might regard a grade 5 (or vice versa). Personally, I think most drivers could discern the difference between smooth, bumpy and rough (or whatever terms, but with as smaller set of options as possible). Given that the majority of maps I have have two "grades" - 'normal' and '4WD', with the surface type as a separate value, I reckon we could get away with a set of three suitably named values for smoothness, as long as the reference is the to the primary traffic type. --gaffa 23:15, 27 November 2008 (AEST) - Overall, I don't get you tagging idea, it looks quite well but I don't see... HOW ? can you drop a real life example ? and the tags you expect ? Sletuffe 12:58, 27 November 2008 (UTC) - I think the tags need to be both limited and easily to differentiate between. They should also definitely ONLY be in relation to the primary vehicle type designated for that way. Use sub tags (smoothness:skateboard=bumpy) to handle alternative vehicle types (and that way when someone says "but what about my tractor? It can go on impassable roads", it's easily to say, "well tag the bloody thing with "smoothness:tractor=whatever". Everybody is happy - the standard smoothness value represents the smoothness for the default vehicle, but rollerbladers, skaters, snowmobilers and tractor drivers can all have their own set. - In terms of real world examples, using the photos posted further up this talk page, I would tag them as (in the order that they appear): smooth, smooth, bumpy, smooth, bumpy, rough, rough, bumpy, rough, rough - personal preference obviously. The reason for those values is that from the photos, that is the kind of ride in a car you would get from those roads. The surface (grass, dirt, stones) would have an additional impact, but the combination of the two would allow for reasonable determination by a user as to whether that road was suitable for whatever vehicle they were currently driving. -- gaffa 14:03, 27 November 2008 (AEST) Lack of criteria The value of this proposal was in that no objective criteria is needed for tagging and the that the value does not tell anything of the criteria used. It is sufficient for common navigating users, a traveler in any of the mentioned classes, that the mapper has thought that the way is usable by "class N and all below". Assessing the suitability for those mentioned in the proposal seems hardly a challenge. To me that means that detailed criteria is then not needed. Deducing any (exact) physical qualities of the road is impossible from the smoothness=* and never was meant to be possible, as a track can be unsuitable for sports cars for any of many reasons: high median (undercarriage damage), sharp humps (front or rear skirt damage), potholes (wheel damage) or other reasons. If such deductions are wanted, that would have to be some another tag. Alv 15:45, 21 November 2008 (UTC) - How precisely do you define "passable" or "usable"? There are certainly roads near me which are "passable" and "usable" by car, but that I wouldn't advocate actually using. According to the scale given here, it would be anywhere between "intermediate" and "very horrible". You could certainly get a wheelchair down it, provided it has brakes, and it stuck to the pavement. Chriscf 16:39, 21 November 2008 (UTC) - I read it to mean something along the lines of: If you'd say to a person asking directions "you can drive that road" or "I'd drive that road if I were you". A skilled or upset rollerblader can get forward on a cobblestone street but it's not usable, a racing bike rider can slow to a crawl on a non-usable street. Any user might get through on a road of a worse smoothness than indicated, but it's not fast, likely, guaranteed nor fast.Alv 17:33, 21 November 2008 (UTC) Trying to stop an Edit war 2nd round Looks like me (and apprently now some other) and User:Chriscf do not agree about the smoothness=* page, after 3 successive undo, I think it's time for help from others third party. My arguments : - That key was voted on - That template is shown on the map feature and I don't see problems - Might the result be to remove it from the Map Features, there are no reasons to comment it out completly on this page Waiting for his arguments : ( Edit , they are all up here ) - Chriscf is in the wrong: smoothness=* applies only to wheeled vehicles. access=no means that no one at all is allowed to use it, even ped- or equestrians. --Hawke 16:22, 20 November 2008 (UTC) - Looks like, my dear Hawke, that this is what you and I think. But not him. We are now at a point where, after I have undone his commented out twice and that you seams to have commented out his stuff n times we are on a dead end. - Either we let him win and all that is gone, and we'll go to it later (say month) once the tag is much used, but I does not appear to me as democratic. - Either he stops, but it looks unlikely to happen - Or we let that commented out for now, ask support from others, let him ask support for others and cast for a new vote on wish we all agree that the issue will determin the final result we choose. - Sletuffe 17:28, 21 November 2008 (UTC) - IMHO Users not liking smoothness as a tag shall start a proposal for deletion of smoothness and depreciation against something else. If there is then a positive vote smoothness has to go. Until that point however smoothness has to stay in map:features and is the officially proposed way of tagging. If he can't accept that than we should ask for his account to be deleted and his IP blocked (that will temporarily help) as well as asking some moderators on the talk list to block tag|smoothness on the map:features page.--Extremecarver 17:45, 21 November 2008 (UTC) The vote is irrelevant. Valid concerns were raised, and not addressed, so the vote is a rogue result. There is nothing anywhere which says we have to accept the result of a vote, especially when it contradicts the result of any discussion. This tag is broken, and nobody has volunteered any means of fixing it, so until it is, it cannot be shown on Map Features, otherwise people will use it, which would be a Bad Thing. Since there is nothing which defines whether a way is "passable", users have no way of figuring out how to tag something. Your definition of whether something is "passable" will not always match everyone else's. Of course, the easy way to end this is to stop adding broken tags to Map Features. Chriscf 09:06, 24 November 2008 (UTC) - Come on Chris! If you disagree, open another vote to have it removed instead of this stupid edit war. --JLS 16:24, 25 November 2008 (UTC) - Please feel free to describe these non-existant "valid concerns" that were raised. The concerns you raised were: - * Impassable = access=no -> This is not correct, as smoothness is only relevant to wheeled vehicles, and not the legal access restrictions. - * The term "4wd" is not good. This has been changed. - So, please describe how this tag is broken beyond "Chriscf doesn't like it". Or at least point to some actual valid concerns that weren't addressed. --Hawke 21:52, 26 November 2008 (UTC) - He posted some concerns at Next step : deprecation of tracktype ? --Phobie 04:22, 29 November 2008 (UTC) Please try to find an agreement on how to find a solution on this edit war. Use the mailing list talk@openstreetmap.org where I raised a thread about your conflict which happens since 7 days now (title is "Edit war on the wiki "map features"". -- Pieren 16:31, 25 November 2008 (UTC) Be constructive! Try to find good alternatives to smoothness! first alternative After I mentioned the edit-war and read all comments, I came to the conclusion that we need measurable values for smoothness. Smoothness combines bunch of attributes which can also be tagged separately. From all those values a user can estimate the smoothness for his vehicle and personal capabilities. If a mapper wants to give a general hint he would use smoothness and if he wants to be more specific we offer him the keys needed. Now lets try to find all attributes used by smoothness. - width=max:* (in meters) - height=max:* (in meters) - weight=max:*;min:* (in kilogram) - surface:plasticity=*;wet:* (how to get useful values?) - surface:frictional_resistance=*;wet:* (how to get useful values?) - surface:particle_size=0,* (in meters, yes always stick to SI!) - surface:glyph_depth=0,* (in meters, results into a minimum ground clearance) - surface:centre_distance=max:*;min:* (in meters, means distance between axis) - surface:incline=* (in meter rise per 100 meter horizontal) - surface:defects=* (yes/no/refitted) Please improve my proposal or make a better one! I only want to see constructive comments! --Phobie 05:53, 29 November 2008 (UTC) - Please remove mine if you don't find it constructive : This is a solution I have thought of but abandoned since it won't we used by anyone because too complicate. - You could add almost-infinite number of things to describe a track (see my mail on the list recently) : - Max depth of holes on the track/road (it will express the chance you have to hit the ground) - Min lenght between holes (it express the chance to hit ground on resonance speed. - Roots mean and max size - max steepness - Possible water stream across the way - Autumn foliage on the ground - Mud's max depth in water conditions Sletuffe 12:41, 29 November 2008 (UTC) - I read your mail. Some people might find those complex keys useful. We should just offer a default way on how to tag them. It is perfectly ok for me to see a way tagged with smoothness=3 surface=asphalt incline=20 weight=max:5000 surface:defects=yes but smoothness without other surface description keys will be unsatisfactory for many mappers. Mappers decide which keys to tag and coders decide which keys to implement. --Phobie 06:30, 30 November 2008 (UTC) - Doh ! I mis-read you then, I am in no way against overtagging, I think that if some people needs it, they can propose it and I'll vote yes on it. But I am not in favor of replacing smoothness by ~10 tags or so as it would lead to not tagging. I have no problem for example to use (rather long list) surface=* in conjonction with smoothness=* but I am against to say it has to be used with. Sletuffe 11:24, 30 November 2008 (UTC) second alternative Since it is hard to impossible to fit the different vehicles into the 7 (8) categories of this smoothness it would be better to set the usability by vehicle or by vehicle group. I would name that key severity and let it have much less than 8 categories. If there are many categories it would be hard to distinguish between them. - 0 effortless/easy - 1 intermediate - 2 hard - 3 unusable (by average users) Example: - severity=default:1;four-wheeled:3;pedestrian:0 unusable is sometimes better than access=no because bicycle=no implies mtb=no and severity=bicycle:3 only conveys severity=mtb:2 See Proposed_features/Any_moving_thing_grouping_system for some ideas about how to group-objects. --Phobie 07:45, 30 November 2008 (UTC) Option 23,754 OK, another variation on the theme for recording road surface/smoothness/tracktype. I'm trying to cut out the subjectivity issues as much as possible. This approach doesn't solve the variable vehicle type issues (although I'm leaning towards some sort of access/usable tag such as usable:skate_inline=yes/difficult/no for anything that isn;t the primary vehicle type for that road/path etc. So here goes. Basic theory is to define the surface condition and surface type separately (given they are distinct things). Using the existing surface=* as a starting point, define the surface as paved/unpaved (no change from current usage). When required/known, add a surface_condition=* and a surface_type=* to indicate what kind of surface it actually is. For surface=paved, one basically assumes surface_type=asphalt. Possible values for surface_condition=*: Once you've nailed down the condition or quality of the road, you can move on to surface type. Obviously (before anyone jumps up and down), surface_type=* could be absorbed into surface=* very easily, although what the surface_type=unpaved values get converted to is a matter of debate) Possible values for surface_type=*: Lastly, one thing that no one has really discussed (that I've found) is the variability of the road surface over the length of the road. For short roads, it's not a huge issue as the surface type and state tend to be the same for the full length of the road, but for longer roads, it's possible, and in Australia, common, for the road to change surface types and states quite regularly. It's obviously possible to break the road up into sections with a different surface type and state in each section, but that might mean having multiple 100m sections on a road that is kilometres long. So, I would add a best and worst qualifier for roads where the state changes: surface_state:best=uneven and surface_state:worst=rutted. -- Gaffa 10:36, 3 December 2008 (UTC) - Made some changes: Changed the surface_state to be surface_condition, which is a better tag (thanks Phobie). Also added concrete as a surface type (for the tank drivers out there). Lastly, I change the surface_condition from "potholed" to "degraded". Still not sold on "degraded" as a term though (but it's slightly better than potholed) -- Gaffa 12:17, 4 December 2008 (UTC) - I started a (yet unfinished) proposal draft some time ago which mostly looks like your idea! - See Proposed_features/surface_unification! - The keys looks pretty good but I would rename them: - surface:type to surface:material, because type can be easily misinterpreted. - surface:state to surface:quality or surface:condition - There seems to be no problem if you split all ways into 100m segments, so the best/worst is not needed. - Perhaps you could help me to bring my draft in a usable form... - --Phobie 13:09, 3 December 2008 (UTC) - That looks quite good. We definitely have to add pictures to it, otherwise non native English speakers will have problems understanding. Also I think there needs to be tags for tracks and ways that are left open and dissappering as nature fights back their terrain. I would add another category above maintained for asphalt, something like very fine granularity. There are roads that may be well maintained but for inlineskates or skateboards they may nevertheless be not optimal, because the granularity of the surface is not fine enough. On the other hand some potholes don't matter. This proposal should also be used for sidewalks (often sidewalks are differing in quality from the street).--Extremecarver 14:41, 3 December 2008 (UTC) - All this looks full of promises, sound very hard to find all tags needed, but still looks interesting. I strongly suggest you to start a new proposal about this, with a first set (like this one) list of tags envolved or proposed. Anyhow, I'm scared that overtagging will scare some people, but it's worth trying. In the end, I doublt it could replace smoothness, not because it is worst, (it allready look more objective and precise) but because mappers do need different schema of complexity to tag things, I think both can live together without problem, at a low cost of redondancy. It will probably just end like footway=* against path=*+foot=designated+bicycle=no (something like a shortcut)Sletuffe - Added most of your proposal into Proposed_features/surface_unification --Phobie 14:27, 5 December 2008 (UTC) What about opening our eyes on what other have done ? Instead of just fighting in the dark, I propose we find how professional map makers have solved the case, year and years of experience might well give us a clue. IGN, the french map maker, with dozen years of experience, which map mountains, roads, tracks, footpath, etc. has a legend wich is : - Regularly maintained is either paved and well suited for passenger car. - Not regularly maintained is rarely paved, or quite bumpy mostly suited for passenger car at low speed. But might also not be used without car dammage - Cart track is definetly not usable by passenger car, for an off road vehicle, it might or might not be usable. But for agricultural use or forest management it is usable by tractors or special 4 wheeled equipement. Sletuffe 13:16, 29 November 2008 (UTC) - I don't believe that IGN puts all values of their map-database on the legend. --Phobie 06:05, 30 November 2008 (UTC) Planograph see also cc by Maybe in two years OSM mappers will have laser planographs on their cars. Breaking a system This tag is actually breaking a system. - highway=trunk surface=dirt smoothness=horrible - highway=unclassified surface=cobblestone smoothness=good - highway=secondary surface=gravel smoothness=bad Usually the smoothness tag will follow the surface tag (I admit that it might exist exemptions) and therefor absolutely not necessary to tag. I have heard one reason for adding this tag was that routing software only took surface paved/unpaved into account when panning a route, but adding another tag doesn't solve that. There are more than enough values of surface to actually tag whichever smoothness level you like, you only need your planning software to calculate with more values than paved/unpaved. Besides, if your road have a lower quality than indicated by your surface tag, why not add a caution or hazard indication? Especially when you have a high quality road (trunk+asphalt) with loads of potholes and damages. As I see it, the purpose of the smoothness tag is only to get more data to put into the system, there is no real purpose of this tag. --Skippern 14:49, 3 December 2008 (UTC) - In my personnal case, I'm not using surface=* at all with smoothness. What I tag is : - highway=track + smoothness=horrible to say that it's not possible to go there with a passanger car, and strong engine is needed, so only off roads vehicles can use it. I don't want to bother with surface because it will need me something like 5 tags to say the same thing. With still the ambiguity : - highway=track surface=gravel surface2=roots potholes=huge steepness=40% -> does this mean a passenger car is not able to drive here ? I'm not sure, but that is the only information I want to give Sletuffe 15:06, 3 December 2008 (UTC) - So you are saying that you are even contributing to the problem rather than solving the problem. If lack of usage of surface=* makes routing software not give you the desired result, than how would adding more factors for the routing software solve the problem? If you are thinking about specific types of trails and tracks, why not use scales together with the existing surface? We have an approved sac_scale=* and I am sure you know of the mtb scale as I have seen your name in the discussion. Adding a secondary surface tag is also pointless as the dominant surface is the only needed/used by any renderer or routing software. --Skippern 15:13, 3 December 2008 (UTC) - I'm not trying to solve, neither I am trying to contribute to the problem, I'm just tagging what I think to be usefull. And surface isn't usefull for me. I don't say it is not usefull, but noone will ever force me to tag things I don't care about, or not willing to tag. I've been tagging smoothness for 6 month now, and I find it easy AND usefull and suiting my needs. "By tagging you become a tagger". I wonder who as made usage of surface here and got something usable out of it. If yes, I have no problem with that. If no, then I propose something to increase informations on tracks and path. - The "scales for everything" you are talking about is discussed somewhere else, also I am absolutely not against, I not in favor of it replacing smoothness for now. sac_scale is very usefull, because not covered by smoothness (and smoothness is not able to cover it) so I'm using it a lot on path and footway. mtb:scale (S1 and more) is not convered by smoothness, so I'm using it also. I use smoothness to split S0 in fact so that I can give information for trekking bike, off road vehicules and mountain motocycle in just one tag. - "One surface to rule them all, and in the useless, bind them" are you saying we should spit tracks in pieces of different surface ? are you saying that a track should be tagged with the "worst" surface found ? what's "worst" ? what about potholes ? mud ? a stream crossing the way ? tree branches on the way ? those are common to different vehicles, I won't tag a track with 8 differents scales to say the same thing. If somone wants, please do ! don't try to force people to do it, they probably won't. So give them a choice : "a rough guess"=smoothness and /or "20 differents tags/scales" Sletuffe 16:23, 3 December 2008 (UTC) - Much of what you are implying should rather be covered as hazard=* than giving a series of confusing tags. If there are dangerous potholes in a road than I would like to have a warning sign telling me about it, I do not need to grade the potholes to see if it is a danger to a lamburgini but not to my ford. BTW: hazard have been proposed. (and here --Skippern 16:41, 3 December 2008 (UTC) Another way : reduce the list and think "wheel" The main concerns about the original proposal is the names of values and their subjectivity. Altough I think personnaly that it will be almost impossible to find a good solution satisfying everybody, I'll try to make this one. First, I think that the amount of values must be reduced, minimizing the questions when the tag is adopted. Second, if the aim is to identify which type of wheeled vehicules may use the road or not, I suggest that wheeled vehicules are categorized in three groups, each group represented by a smoothness value. Third, we have to be carefull that smoothness does not deprecated the well established tag surface=*. The risk is high that confusion is made between surface and smothness. The table is ordered by usability from best to worst. It means that a vehicle listed in one category cannot use the roads tagged with values of lower quality. (please english speakers, improve my poor sentence) -- Pieren 17:03, 3 December 2008 (UTC) - We are allready thinking "wheels" ! "physical usability of a way for wheeled vehicles " is the wording for smoothness. - your table looks really like the very first we proposed, on which we have later added values. I have been fighting long to merge "excellent" and "good" but roller blade users have raised a good remark about their ability to make distinction about a "usual asfalt" and "very smooth asfalt for roller/skate". Since I don't use rollers or skate, it was not my power to impose those tags to be removed. - As of "offroad, offhighways" things, I consider myself being quite aware of that, since I use every week end, in the alps, tracks to reach paragliding take off, hiking trail starts, and even moutain biking trails. And belive me, there are differences that are hard to express, but my saxo is really unable to reach points where some of my friend do well with their non-city-non-plastic 4wd. For management and taking care of our takeoff, we need some times to carry huge wood sticks and sand and cement on places we usuly use our foots to go. In those case, no usual vehicles can drive on where we go. We then rent some special equipement to carry all that Sletuffe - I like it. Yes, it is like the early smoothness draft (which has been made worse). Like written before I would call it surface:evenness instead of smoothness! The different interest-groups should invent there own scales. While scale:mtb is already usable for bicycle and motorbike, there is need for a scale for vehicle with three or more wheels i.e. scale:car. --Phobie 17:52, 3 December 2008 (UTC) - Another remark is that the word "smoothness" is, what I think, a very bad word for discribing what we try to, and maybe much concerns are about that while not clear. I proposed earlier "usability", but I don't remember why, but it was refused. Since words doesn't matter that much to me. I accepted like that. - usability=roller / usability=bike / usability=car / usability=high_clearance / usability=offroad / usability=offhighways would have been my choice. But some have raise rather good objections that "car" is very centric and might suppose that "moutain bike" can't, while this proposal wants too. You'r pneumatic word is rather a very good idea... but might be hard to "feel" Sletuffe 17:47, 3 December 2008 (UTC) - Subjectivity: How are these any less subjective than the existing smoothness=* values? smoothness=skate in your example is in principle the same as smoothness=excellent. There's no change at all in how subjective it is -- in either case, you're deciding, "is this usable by an inline skater, or not?" - Number of options: While seven passable options is perhaps too many, three is definitely too few. "pneumatic" is not really helpful: There's a big difference between roads that can be used by, say, a Lamborghini, and those which can be used by an ordinary sedan/saloon (the latter can travel on many roads which would severely damage the former). Perhaps five passable options would work: - perfect: suitable for any vehicle (perfectly smooth) (equivalent to current smoothness=excellent and your proposed smoothness=skate). - suitable for sports cars, racing bikes, wheelchair. - suitable for ordinary cars, "comfort bikes", etc. Most surface=gravel roads would be here. - suitable for "light" off-road vehicles: ordinary 4wd/awd cars with high clearance, mountain bikes, etc. - suitable for "heavy duty" offroad vehicles incl. ATV, tank, tractor, etc. - impassable: useless for any vehicle - This gives one value at each extreme end (perfect, impassable), and two "high-quality road" and two "low-quality road" options. I think this is exactly the right number. Naming them is another problem though, see below. - It seems to me with this scale that, in general, it works out that a vehicle can go one step below where it's intended, but with some risk (of getting stuck, losing parts of the undercarriage, etc.) -- "proceed with caution, skill, and luck, and you'll probably make it" - Terminology: Having tag values which refer to specific transport modes is a bad idea, IMO. On the other hand, numbers are not very helpful for communicating the scale of something, unless you know where both extremes are. a "grade 3" road means something completely different when the scale goes from zero to three, than when it goes from zero to 100. Unless someone else has a brilliant idea, this leaves words like "perfect, excellent, good, bad, horrible, impassable". This problem seems to by why smoothness=* uses the values that it does. - --Hawke 21:54, 3 December 2008 (UTC) - Forget the names I gave for the three categories, I'm sure that native english speakers can find better words. We almost agree : keep the two extremes and only one for the middle. This will significantly reduce the risk of subjectivity, not totally but far better than the 6 or 7 values. Ask yourself which applications needs so many levels. We need tags that are self-understandable. -- Pieren 22:26, 3 December 2008 (UTC) - Reducing it to only three values total completely defeats the purpose of the tag -- the values would be so broad as to be useless. You'd have "perfect" and "impassable" and "something inbetween", which doesn't tell you anything about how smooth the roads are. That's as useful as counting things with "one, two, a bunch". --Hawke 22:40, 3 December 2008 (UTC) - Just a note that on a forest track there could be sections where a ordinary 4wd/awd (Say a Honda CR-V, Audi Q7, luxury Jeeps) can go further but some older high clearance 2wd vehicles need to stop only because of the lack of both ends being powered. And the latter can still go much further than some modern "normal" cars as they might have even more ground clearance than the modern day SUV's. But such distinction might be better left for some minimum_qc=*... And if it's lack of engine power, incline=* might suffice. Alv 08:17, 4 December 2008 (UTC) - I can't help but think that most of the problem is that we are effectively trying to combine two separate concepts into one tag, or alternatively only have one tag when two are required. To my mind (as I've sort of said above), without getting down to the nitty gritty, a road has a surface type and a surface condition. While they are inter-related concepts, they are describe completely different attributes of the road. - The problem IMO with using something like smoothness=pneumatic is that you aren't describing the surface type or condition, but the requirements to navigate that surface. That's fine, but I think in tagging just that, we've jumped a step and missed out on tagging what the road actually is (which seems to me like a critical failing of the process). I reckon that we should start with some sort of objective road surface and condition tags, and from that tags like smoothness (with regard to various vehicle types) can be added or partially inferred. smoothness=skate says absolutely nothing about the actual surface (it can be assumed, but it can't be inferred). smoothness=pneumatic doesn't indicate if the surface is asphalt, grass or sand, nor does it tell me what kind of state that surface is in. smoothness=skate allows me to assume that the surface is probably asphalt, but could just as easily be concrete, or planks (as in those that sometimes are used in small bridges). -- Gaffa 12:08, 4 December 2008 (UTC) - Here I see that I forgot to mention something important : in my point of view, the tag smoothness=* has to be combined with surface=*. I add it in the proposal. -- Pieren 12:26, 4 December 2008 (UTC) - To my point of view smoothness could be combined with surface=* and mtb:scale=* and (potholes, hazard, incline). I don't think we should try to force anyone to tag the way we'd like him to tag. We should stay with words like could be might be or would have advantage if. Many (implied) proposal we have here are related to smoothness and should really be proposed to increase the knowlege of ways. But I don't think it should replace it or we might well end with people tagging nothing. As an exemple, it has been suggested that once the mtb:scale=* is finished, we should give a word on the smoothness page such as "For mountain bikers, you should also be more specific by giving the difficulty of the trail with mtb:scale=* Sletuffe 13:05, 4 December 2008 (UTC) New simplified version of smoothness Based on some last comments (pieren and hawke) I'm trying to simplify a bit the numbers of values, try to make it much like a "vehicle scale" and return smoothness2 to it's true meaning : "not really be about smoothness" : Proposed features/usability . Comments have been explicitly said that it could be used in conjunction with other tags to increase knowledge of the road/track/trail. But it still keep the same idea in mind What vehicle do I need to go there Sletuffe 01:25, 6 December 2008 (UTC) - I've just read through this page and it took a long time and resulted in a long responice to it, so I've stuck it elsewhere so as not to consume the page. I've stuck it here. I map tracks frequently, so the standadisation of this tag will make a huge difference so I've dicided to contribute my opinions...hope it is in someway helpful. Ben 21:46, 7 December 2008 (UTC) Rejected? Why was this moved to the rejected features? Just because the second round of voting didn't go on as scheduled? --Eimai 18:12, 14 January 2009 (UTC) - Because it's widely agreed outside the small world of a handful of users here that the tag as proposed was irreparably broken. I suspect what usage there is at the moment comes from either these users, or from new users that have misunderstood it. I'd happily put money on the tag usage being inconsistent if the odds weren't so short. Chriscf 18:31, 14 January 2009 (UTC) - Case-in-point: use of "smoothness=bad": [11]. Apparently this is for tracktype values of 2, 3, 4 and 5. Clearly, one of the two is broken, and the tracktype=* values are based on objective, factual observations, and therefore unlikely to be the culprit. Chriscf 18:36, 14 January 2009 (UTC) - So it is for tracktype 2 to 5, what does that have to do with it? Smoothness is independent from tracktype. And note I'm not arguing in favour or against having a smoothness tag. All I see is that the tag is being used so there is some need for it, so this basically has to be kept as de facto approved until a better proposal comes along where all the ones tagged with this can be moved to. --Eimai 19:09, 14 January 2009 (UTC) - Chriscf, Smoothness=x doesn't = tracktype=y. There not related. +1 on Eimai's point. A grass track may be unusable to the degree that it's classed as 'bad' and a gravel track may be unusable to the degree that its classed as 'bad'. I can't see much with this criticism, although in general I see sense in what you say. The criticism I would have with 'bad' is not knowing where in the order of good-worst it stands. For tracktype:grade3 for example it's clear that it's between 1 and 5. The lack of selfdescriptivness to the word 'bad' isn't such an issue though. It's a side effect of making tags that are practical to use. "Because it's widely agreed outside the small world of a handful of users here" Would these people like to add there opinions? firstly it's not a democracy, so I couldn't care if it's 99 against 1, if the 99 all chant the same weak point. Secondly, I haven't seen this wide agreement, thirdly, the majority of users do 1% of the work, the minority do 99%, and fourthly, I wouldn't define it as a small world, since I have seen multiple names on this subject who are far from ignorant on mapping routes where this applies, and discussing it in general. I agree with your critism's on voting, but you seem to now be against adapting it in relation to points made within that vote, and these points, pro or not, are what need to be thought about, and used to make an adaption of the previous proposal. If usability is the spin off, this may as well just be rejected, but why it needs a whole new start rather than an adaptation I don't know. Ben 20:01, 20 January 2009 (UTC) User point of view So much debate on some tags with so few declared users. I'm contributing for one of these users, the "motorcycle map of Romania" (see description in wiki), getting reports from riders, estimating the parameters, playing with them almost daily. For me is obvious that a change must be done, this is how I see a working combination with minimal change in fact. Rootcause I think that smoothness was defined with users in mind, and this is against the OSM policy of "don't map for renderer". highway=track, very useful, as a distinction should exist between agricultural/forest roads and normal roads(tertiary and so on) tracktype=grade1,2,3,4,5 - It is well defined in wiki as the visual persistence of the road given by the frequency of use, lack of vegetation destroyed by wheels. Tracktype does not deal with the surface, but this should be more clarified in wiki as it seems many users think so. We might think that grade5 is in bad shape, but it's not like that it can be usead easily or might be bumpy but it means you must search for it, almost cannot see it in the land. From my point of view, this grades are ok, not to be changed. surface(=paved,asphalt...) it's the cover material, can be used for all type of highways, tracks included. Not much to change also on this parameter. Some might argue that ground/earth turns to mud in rainy weather, but as wheater changes are not recorded in OSM, this should be computed on the spot by the user-software that has the weather parameter active. smoothness. Here I support fully the idea in "Option 23,754" with the surface_condition instead of smoothness, because an usable smoothness or travel feeling then can be easily computed at the moment of use from the combination of(surface,surface_condition, type of wheel/vehicle/user). We already generate different map for each type of motorbike(user parameter) using (surface, smoothness) combination. A general argument like "highway=trunk" means automatically something smooth because in Germany it's so, it's not a general rule. Let's not forget that the terms highway= trunk/primary/secondary depicts the administrative category of the road, and not the quality of the work done or the smoothness of surface. If in Germany it might be so, but believe me, in Romania it's not the case, and in the rest of the world the situation is specific to each country. With today's parameters, it's very complicated to depict the difference between the following two roads - (highway=track, tracktype=grade1, surface=gravel, smoothness="best that can be obtained using gravel") and (highway=track, tracktype=grade1, surface=gravel, smoothness="bumpy, hard to use" ) For the first one, cannot use "excellent" or "good", I should use "bad" bud it's not bad at all for a gravel, quite excellent in fact. Different type of wheel sizes react differently on the same road, for example blade-roller on sand(digs in) and truck wheels still ok. Therefore the smoothness of the road should not be defined starting from wheel or user types. This is now, and it's ok only for few types of surfaces. Compared to the actual "smoothness", "surface_condition=well maintained/maintained/degraded..." is also easier to transmit verbally, or as a report. Reporting is important to consider, because we will get the most of information from verbal reports, not from accelerometers. Let's think globally, every contributor has eyes, can speak/write, but planographs are non-existent even compared to the number of GPS units. As we give to volunteers the ability to contribute with POIs, descriptions, corrections even if they don't have a GPS, let's keep this philosophy also for state of the road. If we go to a remote place and ask local people about the state of the road, we get mostly useful description of the way even if it's also subjective. I use to get reports like "It is a track, so well maintained, gravel, it was excellent and could ride with 40km/h" or "broken asphalt, speed 70km/h, so shaky I lost some screws" So I'm supporting this way of using the parameters since they do not depend on rendering capability, vehicle type or wheel type and size. --owene 20:52, 3 August 2011 (BST) Renaming current values From this long discussion I've felt that many people find the naming of smoothness=* values inadequate. I think that replacing its values with the suggestions in the text (as I've copied below) would make this tag much more popular and very useful. --Fernando Trebien (talk) 18:56, 20 March 2014 (UTC) - Please move your suggestion to Talk:Key:smoothness. The proposal is only kept around for historical value and should not be changed anymore. --Tordanik 16:37, 22 March 2014 (UTC)
https://wiki.openstreetmap.org/wiki/Talk:Proposed_features/Smoothness
CC-MAIN-2021-49
refinedweb
19,043
66.98
How does same field represents two different values here?below o.a==a class Alpha{ //fields int a,b; //constructor Alpha(int x,int y){ a=x; b=y; } //Method boolean equalTo(Alpha aph){ if(aph.a==a && aph.b==b)return true; //this is the question else return false; } //Method void guess(Alpha o){ if(o.a==a)System.out.println("correct"); //this is the question else System.out.println("wrong"); } } enter image description herepublic class exp { public static void main(String[] args) { enter code here Alpha ob1=new Alpha(12,60); //alpha.a,alpha.b Alpha ob2=new Alpha(12,60); //alpha.a,alpha.b Alpha ob3=new Alpha(5,0); System.out.println(ob1==ob2); System.out.println("ob1==ob2 : "+ob1.equalTo(ob2)); System.out.println(); ob1.guess(ob2); __________________________________________________________________ output: false ob1==ob2 : true correct wrong The "==" operator when used with primitives compares the value. However, when dealing with objects, the "==" operator compares the memory address. Foo a = new Foo(); Foo b = new Foo(); System.out.println(a == b); // this will be false since they are different instances Foo c = new Foo(); Foo d = c; System.out.println(c == d); // this will be true since they are the same instance The method equals(Object obj) (which is defined on the Object obj and by default uses the same logic as "==") should be overridden by any object that wants to implement some value type comparison. But even if you override the equals method, it doesn't change the behavior of "==". Whenever you compare to objects for equality, ALWAYS use the equals method unless you really do want to check not the content of the objects but if they are the same instance. FYI : your equals method is kind of broken (e.g. won't work the way you expect). If for instance you put an Alpha instance in a data structure and then asked if the same object was in it, it would reply as false. This is because you didn't override the Object equals method. What you really want to do is this: @Override public boolean equals(Object obj) { if (obj instanceof Alpha) { // Safe to cast since this will only execute if obj is an alpha Alpha other = (Alpha) obj; // the values are primitives so you can use the "==" operator on them return this.a == other.a && this.b == other.b; } return false; } Also ... if you override equals, always, always, ALWAYS override hashCode or you can't use any hash data structures (think HashMap, HashSet, etc).
https://codedump.io/share/U4V4d7L14ml9/1/undertsnding-object-as-a-parameter
CC-MAIN-2016-44
refinedweb
421
63.19
IRC log of rdfa on 2011-10-13 Timestamps are in UTC.:48:42 [ShaneM] ShaneM has joined #rdfa 13:54:32 [SebastianGermesin] SebastianGermesin has joined #rdfa 13:54:40 [bergie] hi 13:54:55 [bergie] unfortunately I think I can only join IRC today... another meeting overlapping with this one 13:56:19 [bergie] was supposed to end at this hour, but we're at item 1/7 now :-P... because it has no effect in the current spec. 14:11:40 [manu1] ack niklasl 14:12:10 [scor] niklasl: the idea was that @rev might be usable to make a link from the list itself 14:12:34 [scor] ... it might introduce problems: can only make links with literals 14:13:02 [scor] manu1: Ivan has implemented something, but there are issue with how to interpret that with other RDFa attributes? 14:13:22 [scor] gkellogg: not a proposal, it's the existing behavior. question is: do we want to keep it that way? 14:13:34 [niklasl] q+ 14:13:42 [scor] ... if we don't have an advocate for @inlist we can't make much progress 14:14:02 [scor] manu1: Ivan would be that advocate, though he said he didn't really like what it did. 14:14:17 [scor] manu1: danger is we have an attar which does not do what we expect it to do 14:14:50 [scor] manu1: one can argue it's an advanced feature, and should only be used for advanced use cases 14:14:56 [manu1] ack niklasl 14:15:09 [scor] niklasl: I agree. haven't seen any use case for using the list as a subject 14:16:27 [scor] manu1: anyone disagree? 14:17:00 [scor] manu1: opposed to making a decision on this call today - let's wait a week to make a resolution 14:17:15 [scor] ... until Toby and Ivan are on the call 14:17:18 [SebastianGermesin] ok, for waiting 14:17:52 [scor] Shane: proposal to take effect in 7 days if nobody obejcts 14:18:15 [scor] Shane: the values specified by HTML5 14:21:01 [scor] manu1: initial list could be the same as the XHTML values, and wait until the new values are standardized to add them 14:21:25 [scor] manu1: only tweak about the proposal would be to remove stylesheet, not really useful and people don't like it. 14:21:40 [gkellogg] The May Microdata spec removed alternate and stylesheet and replaced them with ALTERNATE-STYLESHEET 14:21:42 [scor] manu1: maybe also remove alternate as it's not used the way we would expect it in RDF 14:22:47 [scor] Shane: alternate: <muffled> 14:23:20 [gkellogg] q+ 14:23:40 [scor] Shane: alternate has a specific use in the wild today (e.g. RSS) 14:23:49 [manu1] ack gkellogg 14:24:35 [scor] gkellogg: micro data used to do in an earlier version of the spec: use ALTERNATE-STYLESHEET to remove them 14:25:05 [scor] Shane: we don't care about the RDF generated by stylesheet 14:26:06 [scor] manu1: hold off alternate or stylesheet until the processer would have processed all @rel to decide what value should be generated 14:26:35 [scor] manu1: we want to generate useful triples for people on the semantic web. stylesheet and alternative are usually not useful. 14:26:54 [scor] ... people who need these would not use RDF for the purpose of alternative and stylesheet? would be surprised if there was any 14:29:11 [scor] niklasl: I think there is a potential for it, I would probably use dc:hasFormat for that use case though 14:29:31 [scor] manu1: since RDFa has been around 2008, if today there is no use case today, we could remove it 14:29:49 [scor] manu1: in the vast majority of the use case, it generates wrong triples was to happen 14:31:42 [scor] ... that's all we can do 14:33:47 [scor] manu1: the only thing we're talking about is the removal of stylesheet and alternate 14:33:55 [scor] manu1: any disagree? or want to add something? 14:34:02 [scor] s/any/anyone:Contact" and then the skos namespace would become the default @vocab. 14:39:12 [gkellogg] q+ 14:39:20 [manu1] ack gkellogg 14:39:20 [scor] s/skos:Contact/skos:Concept. 14:53:12 [manu1] ack manu1 14:53:16 [manu1] ack scor 14:53:36 [manu1] scor: I agree if you know that @vocab exists, but if you don't know it exists - then it's difficult to learn that new thing. 14:53:51 [manu1] scor: However, with this, it's not as confusing. 14:54:03 [manu1] scor:. 14:57:02 [manu1] scor: RDFa has a mixture of attributes to be added to markup - in Microdata you just have @itemtype... in RDFa you have @vocab and @typeof.] +1 15:01:08 [manu1] -1 15:01:49 [manu1] RESOLVED: Add functionality to @typeof where if the first token is an IRI, that sets the default vocabulary for processing. 15:02:07 [gkellogg] s/Add/Do not add/ 15:02:15 [scor] 15:08:40 [Zakim] -McCarron 15:08:44 [Zakim] -scor 15:08:45 [Zakim] -manu1 15:08:45 [Zakim] -gkellogg 15:08:46 [Zakim] -SebastianGermesin 15:08:50 [Zakim] -Knud 15:08:51 [Zakim] -niklasl 15:08:51 [Zakim] SW_RDFa()10:00AM has ended 15:08:52 [Zakim] Attendees were gkellogg, +1.540.961.aaaa, manu1, McCarron, niklasl, Knud, +68185775aabb, SebastianGermesin, scor 15:09:55 [Knud] Knud has left #rdfa 15:16:07 [ShaneM] ShaneM has left #rdfa 15:43:30 [niklasl_] niklasl_ has joined #rdfa 15:51:46 [niklasl] niklasl has left #rdfa 16:18:26 [MacTed] MacTed has joined #rdfa 17:01:03 [Zakim] Zakim has left #rdfa 17:05:25 [ShaneM] ShaneM has joined #rdfa 17:08:35 [ShaneM] ShaneM has left #rdfa 18:24:48 [tomayac] tomayac has joined #rdfa 20:04:35 [manu] trackbot, bye 20:04:35 [trackbot] trackbot has left #rdfa 21:19:56 [tomayac] tomayac has joined #rdfa 21:33:05 [ShaneM] ShaneM has joined #rdfa 22:05:24 [MacTed] MacTed has joined #rdfa 22:36:20 [ShaneM] ShaneM has joined #rdfa 22:46:08 [ShaneM] ShaneM has left #rdfa 22:49:25 [ShaneM] ShaneM has joined #rdfa
http://www.w3.org/2011/10/13-rdfa-irc
CC-MAIN-2016-26
refinedweb
1,066
68.54
Please consider this code: #include <iostream> template<typename T> void f(T x) { std::cout << sizeof(T) << '\n'; } int main() { int array[27]; f(array); f<decltype(array)>(array); } Editor's Note: the original code used typeof(array), however that is a GCC extension. This will print 8 (or 4) 108 In the first case, the array obviously decays to a pointer and T becomes int*. In the second case, T is forced to int[27]. Is the order of decay/substitution implementation defined? Is there a more elegant way to force the type to int[27]? Besides using std::vector? Use the reference type for the parameter template<typename T> void f(const T& x) { std::cout << sizeof(T); } in which case the array type will not decay. Similarly, you can also prevent decay in your original version of f if you explicitly specify the template agument T as a reference-to-array type f<int (&)[27]>(array); In your original code sample, forcing the argument T to have the array type (i.e. non-reference array type, by using typeof or by specifying the type explicitly), will not prevent array type decay. While T itself will stand for array type (as you observed), the parameter x will still be declared as a pointer and sizeof x will still evaluate to pointer size. The behaviour of this code is explained by C++14 [temp.deduct.call]: Deducing template arguments from a function call Template argument deduction is done by comparing each function template parameter type (call it P) with the type of the corresponding argument of the call (call it A) as described below and then below: If Pis not a reference type: - If Ais an array type, the pointer type produced by the array-to-pointer standard conversion (4.2) is used in place of Afor type deduction; For the call f(array);, we have A = int[27]. A is an array type. So the deduced type T is int *, according to this last bullet point. We can see from the qualifier "If P is not a reference type" that this behaviour could perhaps be avoided by making P a reference type. For the code: template<typename T, size_t N> void f(T (&x)[N]) the symbol P means T(&)[N], which is a reference type; and it turns out that there are no conversions applied here. T is deduced to int, with the type of x being int(&)[N]. Note that this only applies to function templates where the type is deduced from the argument. The behaviour is covered by separate parts of the specification for explicitly-provided function template parameters, and class templates. You can also use templates like the following: template <typename T, std::size_t N> inline std::size_t number_of_elements(T (&ary)[N]) { return N; } This little trick will cause compile errors if the function is used on a non-array type. Depending on your use case, you can work around that using references: template<typename T> void f(const T& x) { std::cout << sizeof(T); } char a[27]; f(a); That prints 27, as desired.
http://m.dlxedu.com/m/askdetail/3/f7073be42a72b69f621f25a0ec76514a.html
CC-MAIN-2019-26
refinedweb
521
58.21
05 December 2008 08:13 [Source: ICIS news] By Chow Bee Lin SINGAPORE (ICIS news)--Chinese petrochemical majors Sinopec and PetroChina have lodged a complaint with the Ministry of Commerce against South Korean exports, seeking an anti-dumping (AD) investigation on a range of petrochemical products, a Sinopec source said on Friday. “The complaint is directed at a range of Korean products, including polymers and aromatics,” the source said. He declined to reveal the full list of products implicated. ?xml:namespace> In 2007, “It’s possible that an investigation will be initiated and subsequently implemented, as both the companies are major suppliers in But the news has sparked concerns among some Chinese importers whose main supply comes from “This is not good news for the importers,” said a second east China-based trader of toluene and mixed xylenes. “This would obviously have a big impact on our businesses,” he added. Chinese purified terephthalic acid (PTA) producers such as Sinopec, Hualian Sunshine Petrochemical, Xiang Lu Petrochemical and Yisheng Petrochemical have earlier lodged a similar complaint against Korean PTA imports as prices fell sharply in a span of just about five months. PTA prices were at $570/tonne (€450/tonne) CFR (cost and freight) Investigations are understood to be ongoing with no clear verdict. Paraxylene, the feedstock for PTA, was not included in any anti-dumping complaints, said a Sinopec source. ($1 = €0.79) Mahua Chakravarty and Salmon Aidan Lee contribued to this article. For more on PE, PP, toluene, xylene, benzene, PX,
http://www.icis.com/Articles/2008/12/05/9177075/sinopec-petrochina-seek-ad-probe-on-korea-chems.html
CC-MAIN-2014-52
refinedweb
251
55.47
Web Forms :: Search Filter GridView Records Based On TextBox?Oct 9, 2012 i want to get data from database using text box . when i enter id in text box it should fetch all the record related to that id ?View 1 Replies i want to get data from database using text box . when i enter id in text box it should fetch all the record related to that id ?View 1 Replies need to get selected value from dropdownlist,textbox and bind in gridView have a gridview which I am binding through code behind, I want to filter the gridview based on the value given by the user in textbox. It would be great if I'll be able to filter the gridview without any postback.View 3 Replies [URL] .... I Need to search record from GridView by using the textbox but not want to configure this with SQLDataSource Manually (Front End) therefore how to filter gridview from Codebehind.View 1 Replies? how i can filter gridview coloumns data based on textbox event ONKEYUP....View 15 Replies]... I want to search crystal report from text box .. for id , name , designation ,... When I pass value in crystal report it should display the data .. how can I do this process ..View 1 Replies I need to filter data based on a date range. My table has a field Process date. I need to filter the records and display those in the range FromDate to ToDate.View 2 Replies My question is I have multiple Checkbox Lists and i want to compare it and Filter Datalist records on Checkbox list checked event.. (I want filtering something like [URL] using System; using System.Collections.Generic; using System.Linq; [Code]..... My problem is If first checkbox list is checked and user clicks on second checkbox list then i want to compare both checkboxes and populate result based on both checkboxes. want to display all the items existing in database for ex: If i enter just book. All the items with book work should get displayed Example in google search as soon as we enter one word related all things get displayed. I am not talking about auto completion I want to filter a grid at server side based on the value typed in a text box. And the filter should happen as the user types in text box. Since there is no server side event like keypress on a textbox, I decided to do use the client side onkeypress event and call a server side code using PageMethod. But then ran out with the limitation of PageMethod being static and I can't access grid from server side].... I have a database of cars manufacturers and their car models. I want to have buttons above the GridView, each button listing a manufacture. When the button is clicked, the Gridview will filter the data to only show the models by the manufacturer clicked. I don't want to use a listbox or combo box, it has to be 3 rows of individual buttons or links. I am using VB.net and I was able to do this with the dropdown box, but it is not as clean as having a row of buttons. want to filter gridview with date. I have bound date in dropdown list from database.View 1 Replies how to use a multiline text box that i could copy data into. Lets say addresses one on each line and then click submit and have it display those records in the database (SQL) in a gridview?View 7] .....
https://asp.net.bigresource.com/Web-Forms-Search-Filter-GridView-Records-based-on-TextBox--NH0LC.html
CC-MAIN-2021-31
refinedweb
594
81.83
I'm creating a script for use with the Ducky USB stick from Hak5 for a college assessment. For anyone not familiar with Ducky, its a usb stick which runs a payload when you press the button on top of it. The script is meant to highlight the need for I have JSON documents stored in Postgres under the JSON data type (Postgres 9.3) and I need to recursively collect the key names down the tree. For example, given this JSON tree { "files": { "folder": { "file1": { "prope Everyone i am using the following code to recursively call through ajax. function ajax_pay(i) { var opt=document.getElementById("fpayee").options; payid=opt[i].value; alert(i); if(payid==""){return;} alert(payid); if (window.XMLHttpRequest) { / Can any body please give me an iterative solution for the tower of hanoi I understand this recursive code public class MainClass { public static void main(String[] args) { int nDisks = 3; doTowers(nDisks, 'A', 'B', 'C'); } public static void doTowers I would like to find the product of two permutations in Prolog (in cycle form) and I'm having problems with it (mostly because I can't even imagine, what it will look like). I thought about changing these permutations into another representation, but This question is an exact duplicate of: recursive function matlab decimal to binary conversion 1 answer I am writing a function in Matlab that converts a decimal number to binary and every time I try to run it, it tells me that I am in a infinite loo i am trying to create funcion for creating decision tree with state of game in every node in game (doesnt matter what game). I wrote recursive function (DFS) like this: function makeTree(anchor,count,player){ var subTree=null; var nodes=[]; if(player I have a problem with my SQL-Statement. I want to add the Top Parent of each object to each row. I tried a few things but I have to say that I'm pretty much a SQL beginner. For example: Object A: ID 2, ParentID NULL Object B: ID 10, ParentID 2 Object I would like to recursively access the id field and libelle field to fill my database. I tried the following script I fill only the first level of id and libelle.(where idTypeCaategorie = 0). It's just a part of my array. I want fill just two field i Recursion is not happening? Can anyone point out why? function a() { console.log("xx"); console.log(this); a(); } var a2 = new a(); --------------Solutions------------- Answer to the updated question: Your update to the question completely chang I have seen many posts that address how to convert an Oracle "connect by prior" statement to a SQL Server common table expression. However, I have an Oracle "connect by prior" statement that has a "start with fieldname in ('value,'ve been coding in C/C++ for a few years, and I just started Java recently. In one of the projects I've done, I was doing tail-recursion on a big data set (I apologize for not providing the code because I can't find it...). I realized an obvious per I am writing a "clean" method for a "Time" class. The clean method would take a Time object and would make sure that the number of seconds and minutes is between 0 and 59. I am running into an error with recursion. Here is what I have I am trying to write a method that will calculate the largest amount of edges taken to get from the root to the furthest node. public static int depth(Tree t) { if(t == null) return 0; else return 1 + Math.max(depth(t.left), depth(t.right)); } The me The following recursive code is used to compute how many different possible ways that could sum a given number. Input:4 Output: 1111 112 121 112 22 13 31 4 There are 8 (2^(n-1)) different ways to get 4. I wanna know what's the Big O complexity of thi i have a question for recursion in C++,i read a lot of posts,but i still can't get the logic in this exam i have.If you please help me what is the exact logic and if it possible to become easier i would be gratefull. If i enter N=3 and R=2 the answer Hi I am using matlab and need to write a function that works out the number of numbers in a vector that are greater or equal to k. It should return 0 if there are none. So far this is what I have done: function totalnumb = numbgreater(v,k) if any(v
http://www.dskims.com/tag/recursion/
CC-MAIN-2018-22
refinedweb
784
66.67
Compiler: Dev-Cpp Question: How do I title my program? By title, I mean change the text in the blue bar at the top of every program to something like "Example" instead of it being the path file for the application. Thanks in advance, GS Printable View Compiler: Dev-Cpp Question: How do I title my program? By title, I mean change the text in the blue bar at the top of every program to something like "Example" instead of it being the path file for the application. Thanks in advance, GS Platform specific. I'm new to the forums and C++, so I'm not quite sure what you're talking about... If you're talking about what platform this is for it's just a simple beginner's program I want to be titled when I run on my laptop. > Platform specific. Exactly. What OS do you use? If it's windows, the API is the answer. Code: #include <windows.h> #include <cstdlib> #include <iostream> int main() { if( !SetConsoleTitle("Example Console 1.0") ) { std::cerr << "SetConsoleTitle error: " << GetLastError() << "\n"; std::exit(EXIT_SUCCESS); } std::cin.get(); return 0; } I'm new to C++, so I may be wrong, but aren't .h files for C programming, not C++? Anyways, I'm using std and I declared that under the includes so I'd just remove std::, correct? Don't bother yourself with these things, take a good C++ book and go on with it. Walk before you run, and crawl before you walk. Check out the tutorials on the site. You could use system("title X"), where X is the title of your game window. It's a very bigginer way to do it because the system() function is inefficent. Platform specific. As stated earlier. This title-changing thing is not C++. You can do it from C++, but it is not C++. You have to rely on the platform (eg. operating systems, drivers etc) to do it, and different computers may well have different platforms! You have a long way to go. You may learn 32-bit API programming at some point of your programming career. That's when you can change the title, clear the screen etc etc and have non-standard-C++ fun. There are heaps of tutorials/articles on how to title your console window. Just please show some effort and actually do a search on google before posting your question.
https://cboard.cprogramming.com/cplusplus-programming/81761-how-do-i-title-my-program-printable-thread.html
CC-MAIN-2017-22
refinedweb
406
76.11
A short introduction and example of building a face-detecting mobile application. Facial recognition — once the stuff of sci-fi novels — is now a widely used technology. In this post, I will I will show you how to develop a basic face-detecting mobile app with React Native and Expo. React Native is a fast and easy tool to develop cross-platform mobile apps. Expo makes React Native development even faster by providing a whole host of out-of-the-box features to get your app up and running quickly. Lets get started! Building with React Native? Scaffold and deploy React Native apps with quality-assured templates for free in the Crowdbotics app builder. Check it out. First, you have to install Expo CLI (preferably as global) in your system. To do this, run the following command in the command prompt at the location where you want to save your project. ( You’ll need to have Node.js (version 6 or newer) installed on your computer to run this command. Download the latest version of Node.js.) npm install -g expo-cli Now run this next command to start your project. Name it whatever you would like. expo init <your-project-name> Start coding in your working file. By default it is App.js . Import the things you want to use in your project. import { Permissions, Camera, FaceDetector, } from ‘expo’; First, get permission from the use their camera when the app starts. async componentWillMount() { const { status } =await Permissions.askAsync(Permissions.CAMERA); this.setState({hasCameraPermission:status==='granted'}); } Now, if the user gives permission to use the camera, use the camera component where you want to open the camera. return ( <View style={styles.container}> <Camera style={styles.camera} type={'front'} onFacesDetected={this.handleFacesDetected} faceDetectorSettings={{ mode: FaceDetector.Constants.Mode.fast, detectLandmarks: FaceDetector.Constants.Mode.none, runClassifications: FaceDetector.Constants.Mode.none }}> </Camera> </View> ); If a face is detected, the ‘handleFacesDetected’ function will be triggered. handleFacesDetected = ({ faces }) => { if(faces.length > 0){ this.setState({ faces }); } }; I am adding ‘ref’ attribute and a button to the camera component so that when we press the button it will send our image to the recognization process to evaluate whether to enroll or to recognize it. <Camera style={styles.camera} type={'front'} ref={ref => { this.camera = ref; }} onFacesDetected={this.handleFacesDetected} faceDetectorSettings={{ mode: FaceDetector.Constants.Mode.fast, detectLandmarks: FaceDetector.Constants.Mode.none, runClassifications: FaceDetector.Constants.Mode.none, }}> <TouchableOpacity style={{ flex: 1, flexDirection: 'row', alignSelf: 'flex-end', alignItems: 'flex-end', }} onPress={() => this.snap(false)}> <Text style={{ fontSize: 18, marginBottom: 10, color: 'white' }}> {' '}Enroll{' '} </Text> </TouchableOpacity> <TouchableOpacity style={{ flex: 1, flexDirection: 'row', alignSelf: 'flex-end', alignItems: 'flex-end', }} onPress={() => this.snap(true)}> <Text style={{ fontSize: 18, marginBottom: 10, color: 'white' }}> {' '}Recognize{' '} </Text> </TouchableOpacity> </Camera> </View> ); //where, snap = async (recognize) => { try { if (this.camera) { let photo = await this.camera.takePictureAsync({ base64: true }); if(!faceDetected) { alert('No face detected!'); return; } const userId = makeId(); const { base64 } = photo; this[recognize ? 'recognize' : 'enroll']({ userId, base64 }); } } catch (e) { console.log('error on snap: ', e) } }; We are able to detect faces on camera.Our next objective is to recognize the faces. To achieve this goal we will use Kairos. To use Kairos, you have to visit and sign up as a developer. Once you sign up, you will get your App Key and App ID. These are the two things that would make sure that you are able to access the server at Kairos in order to be able to process your images. It is the key to your face being recognized. Next, configure your app with these credentials const BASE_URL = ''; const HEADERS = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'app_id': '<your-app-id>', 'app_key': '<you-app-key>' } You can use different APIs by using base URL like this: etc. Create your functions by using these APIs. Examples of the enrolling and recognizing functions are as follows: //Enroll Method const enroll = async ({userId, base64}) => { const rawResponse = await fetch(`${BASE_URL}enroll`, { method: 'POST', headers: HEADERS, body: JSON.stringify({ "image": base64, "subject_id": `MySocial_${userId}`, "gallery_name": "MyGallery" }) }); const content = await rawResponse.json(); return content; } //Recognize Method const recognize = async (base64) => { const rawResponse = await fetch(`${BASE_URL}recognize`, { method: 'POST', headers: HEADERS, body: JSON.stringify({ "image": base64, "gallery_name": "MyGallery" }) }); const content = await rawResponse.json(); return content; } Where, - image => Publicly accessible URL, file upload or Base64 encoded photo. - subject_id => (can be a random) key for your image (defined by you) is used as an identifier for the face. - gallery_name => is the folder name where your photos will be saved (defined by you) is used to identify the gallery. A successful response of ‘recognize’ API should be like this: And, here you go! In ‘images,’ you have candidate lists that include the matching face ids. This is a brief introduction to face recognition. You can also check Kairos docs for more details. Thanks for reading! :-) If you make a cool facial recognition app with React Native, Kairos, or Expo, drop a link in the comments. I’d love to check it out.
https://blog.crowdbotics.com/how-to-build-a-facial-recognition-mobile-app-with-react-native-expo-and-kairos/
CC-MAIN-2021-17
refinedweb
825
52.05
Print mtouch log information. #include <input/mtouch_log.h> void mtouch_log(int severity, const char *devname, const char *format,...) Severity of the condition that triggered the log. For more information on severity levels, see slogf() in the QNX C Library Reference. All log severities are defined in <sys/slog.h> Name of device driver. String that specifies the format of the log. The formatting string determines what additional arguments you need to provide. Variable-length argument list that correponds to that which is specified in format. This is a variadic function. If NDEBUG is defined, the information is sent as a message to the system logger (slogger). Otherwise, the log is simply directed to stderr. The mtouch_log() output format is: devname[severity]: formatted argument list. Nothing.
http://www.qnx.com/developers/docs/6.6.0_anm11_wf10/com.qnx.doc.inputevents/topic/mtouch_log.html
CC-MAIN-2018-43
refinedweb
125
53.78
00001 /* 00002 * Controllable.hpp 00003 * 00004 * Copyright (c) 2000, 2011,_CONTROLLABLE_HPP 00017 #define COH_CONTROLLABLE_HPP 00018 00019 #include "coherence/lang.ns" 00020 00021 #include "coherence/run/xml/XmlElement.hpp" 00022 00023 COH_OPEN_NAMESPACE2(coherence,util) 00024 00025 using coherence::run::xml::XmlElement; 00026 00027 00028 /** 00029 * The Controllable interface represents a configurable dameon-like object, 00030 * quite oftenly referred to as a <i>service</i>, that usually operates on its 00031 * own thread and has a controllable life cycle. 00032 * 00033 * @author jh 2007.12.12 00034 */ 00035 class COH_EXPORT Controllable 00036 : public interface_spec<Controllable> 00037 { 00038 // ----- Controllable interface ----------------------------------------- 00039 00040 public: 00041 /** 00042 * Configure the controllable service. 00043 * 00044 * This method can only be called before the controllable 00045 * service is started. 00046 * 00047 * @param vXml an XmlElement carrying configuration information 00048 * specific to the Controllable object 00049 * 00050 * virtual void IllegalStateException thrown if the service is 00051 * already running 00052 * virtual void IllegalArgumentException thrown if the configuration 00053 * information is invalid 00054 */ 00055 virtual void configure(XmlElement::View vXml) = 0; 00056 00057 /** 00058 * Determine whether or not the controllable service is running. 00059 * This method returns false before a service is started, while 00060 * the service is starting, while a service is shutting down and 00061 * after the service has stopped. It only returns true after 00062 * completing its start processing and before beginning its 00063 * shutdown processing. 00064 * 00065 * @return true if the service is running; false otherwise 00066 */ 00067 virtual bool isRunning() const = 0; 00068 00069 /** 00070 * Start the controllable service. 00071 * 00072 * This method should only be called once per the life cycle 00073 * of the Controllable service. This method has no affect if the 00074 * service is already running. 00075 * 00076 * virtual void IllegalStateException thrown if a service does not 00077 * support being re-started, and the service was 00078 * already started and subsequently stopped and then 00079 * an attempt is made to start the service again; also 00080 * thrown if the Controllable service has not been 00081 * configured 00082 */ 00083 virtual void start() = 0; 00084 00085 /** 00086 * Stop the controllable service. This is a controlled shut-down, 00087 * and is preferred to the {@link #stop()} method. 00088 * 00089 * This method should only be called once per the life cycle of the 00090 * controllable service. Calling this method for a service that has 00091 * already stopped has no effect. 00092 */ 00093 virtual void shutdown() = 0; 00094 00095 /** 00096 * Hard-stop the controllable service. Use {@link #shutdown()} 00097 * for normal service termination. Calling this method for a service 00098 * that has already stopped has no effect. 00099 */ 00100 virtual void stop() = 0; 00101 }; 00102 00103 COH_CLOSE_NAMESPACE2 00104 00105 #endif // COH_CONTROLLABLE_HPP
http://docs.oracle.com/cd/E24290_01/coh.371/e22845/_controllable_8hpp-source.html
CC-MAIN-2016-40
refinedweb
443
51.18
Description A note of warning: Start work on assignments as soon as they are given. Do not underestimate the demanding nature of this course. Expect the system to crash the night before your program is due. Aim to have it done the day before. Submit the assignment on slate. Do not email me assignments after due date. It will not be accepted in any case. Students are required to submit actual content written in MS word or Pdf. Hand written/ Scanned assignments will not be accepted. Compiling and Visualizing Results for Approximating Value of Pi Your objective will be to run the following C-code that approximates the value of Pi. #include <stdio.h> #include <math.h> #include <stdlib.h> int main() { int STEPS = 100; // Number of Steps int i, count = 0; double x, y, z, pi; for (i = 0; i <= STEPS; i++) { = rand()/(double)RAND_MAX; = rand()/(double)RAND_MAX; = x*x + y*y; if (z <= 1) count++; } pi = (double)count/STEPS*4; printf(“N = %d\t”, STEPS); printf(“Pi = %.20f\n”, pi); } Your objective would be to: Modify the code above so that the program is able to (a) obtain the “STEPS” variable from the shell, and (2) show the overall execution time of the program. Prepare a shell script that runs the above program a number of times (for increasing sizes of STEPS). The output from the shell script should be in the following columns: [N], [Time], [Absolute Error], [Absolute Relative Error] The first two columns (N, Time) are reported from within the program. The last two columns should be computed using AWK as: [Absolute Error] = | pi – acos(-1) | [Absolute Relative Error] = | pi – acos(-1) | / | acos(-1) | The above output should be passed by the shell script to GNUPLOT utility for plotting. two plots Plot Execution Time (y-axis) vs Steps (X-axis) Plot Absolute and Relative Error (y-axis) vs Steps (X-axis) (Warning: May exhaust your available RAM, so consider choosing STEPS sizes of multiples of 10, 100, 1000, etc.): Deliverable: The name of the shell-script should be your roll-number (e.g. 1512345.sh). Submit the shell script file to me on slate. Best of Luck
https://edulissy.com/shop/solved/assignment-1-solution-168/
CC-MAIN-2021-17
refinedweb
361
63.8
03 September 2012 04:32 [Source: ICIS news] SINGAPORE (ICIS)--China National Offshore Oil Corp (CNOOC) started construction of a 4m tonne/year liquefied natural gas (LNG) terminal at Shenzhen in ?xml:namespace> The terminal will come on stream in 2015, CNOOC said in a statement. Four LNG tanks – each with a storage capacity of 160,000 cubic metres (cbm) – and a berth with an 80,000-266,000cbm capacity will also be built as supporting facilities at the terminal, it said. The entire project, which is a 70:30 joint venture between CNOOC Oil & Gas and Shenzhen Energy, will cost about yuan (CNY) 8bn ($1.3bn) to build, the company
http://www.icis.com/Articles/2012/09/03/9591949/chinas-cnooc-starts-construction-of-shenzhen-lng-terminal.html
CC-MAIN-2015-22
refinedweb
111
59.43
How to make a custom search using seam components?Oussama SOUABNI Aug 18, 2009 11:29 AM I’m developing an application using as framework JBoss Seam and I encountered a problem that I couldn’t solve since a week. I hope I can find a solution in this group. First, I was using the totoList.xhtml, totoList.java session and the toto entity as it is generated by Seam-Gen. But, this could work only for a classic list search that means when the attributes are those present in the entity. This allows me to search for any attribute using toto.attribute in the inputText normally when the type is a string or to be modified for other types like int. But, my situation is more complicated: This is the first entity: Demande |@Entity @Table(name = "DEMANDE", schema = "SIMM_SYS") @javax.persistence.SequenceGenerator(name = "SEQ_DEMANDE", sequenceName = "SEQ_DEMANDE", allocationSize = 1) public class Demande implements java.io.Serializable { private int id; private Navire navire; private String nomdemandeur; private String prenomdemandeur; … @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "REFNAVIRE") public Navire getNavire() { return this.navire; } public void setNavire(Navire navire) { this.navire = navire; } … }| This is the second entity: Navire @Entity @Table(name = "NAVIRE", schema = "SIMM_SYS") @javax.persistence.SequenceGenerator(name = "SEQ_NAVIRE", sequenceName = "SEQ_NAVIRE", allocationSize = 1) public class Navire implements java.io.Serializable { private int id; private String matricule; … @OneToMany(fetch = FetchType.LAZY, mappedBy = "navire") public List<Demande> getDemandes() { return demandes; } … } In the demandeList.xhtml page it works only when I use it for the classic one (same thing for the navireList.xhtml). The problem start when I wanted to make a search for an attribute from the navire entity in the demandeList.xhtml (or from the demande entity in the navireList.xhyml) in order to get a search for attributes that exit in the two entities. Example: when I made a search for the attribute navire.matricule in the demandeList.xhtml like this: <s:decorate <ui:defineN° Enregistrement</ui:define> <h:inputText </h:inputText> </s:decorate> And I added the parameter in the page demandeList.page.xml: <param name="demande.navire.id" value="#{demandeList.demande.navire.id}"/> And I added this line in the demandeList.java session as a restriction: "demande.navire.id = #{demandeList.demande.navire.id}", I received this error: Exception during request processing: Caused by javax.servlet.ServletException with message: "/DemandeList.xhtml @43,73 value="#{demandeList.demande.navire.id}": Target Unreachable, 'navire' returned null on …entities.demande … Caused by javax.el.PropertyNotFoundException with message: "/DemandeList.xhtml @43,73 value="#{demandeList.demande.navire.id}": Target Unreachable, 'navire' returned null on the …entities.demande I hope I can find a solution. Thanks a lot. 1. Re: How to make a custom search using seam components?Leo van den berg Aug 18, 2009 1:21 PM (in response to Oussama SOUABNI) The restriction can only result in a null, because the thing you doing now is to navigate the object-tree from a collection to a single entity, to another entity, to an attribute. That works with many-to-one, or a reference to a single object in the collection (with an index), but not by referencing the whole collection. 2. Re: How to make a custom search using seam components?Oussama SOUABNI Aug 18, 2009 1:46 PM (in response to Oussama SOUABNI) I tried to make the search for the value demandeList.demande.navire.id in the demandeList.xhtml page and for the value navireList.navire.demande.id in the navireList.xhtml page and I come out with the same error target unreachable. In the case of demandeList.demande.navire.id I'm using the many-to-one and as I said it doesn't work. Thank you for your response. 3. Re: How to make a custom search using seam components?Anitha Raj May 24, 2010 2:00 PM (in response to Oussama SOUABNI)HI, I'm new to seam and i'm facing a similar kind of issue. I have two tables Site and Location. Site ia at a higher level. Both the tables are related. site id is being used as a foreign key in location table. Now i want to have location name as a field in the Site search filter. While searching, if the user enters the location name then the site associated with the entered location should be displayed else it should display all sites. This is my site.java @Entity @Table(name = "site", catalog = "custinfodb") public class Site implements java.io.Serializable { private Set<Location> locations = new HashSet<Location>(0); @OneToMany(fetch = FetchType.LAZY, mappedBy = "site") public Set<Location> getLocations() { return this.locations; } public void setLocations(Set<Location> locations) { this.locations = locations; } } How should i write the query inorder to accomplish this task? Please explain me in detail
https://developer.jboss.org/thread/189296
CC-MAIN-2019-18
refinedweb
791
52.36
(LOB) applications. These include data management (DataForm), scheduling (Calendar), navigation (RadialMenu), data visualization (Chart), and more. Actually, the list itself is rather long. Have a look: Not bad, eh? In this article, I'll walk you through the source code and show you how to build an application using the Grid and Chart controls as an example. The source code for Telerik UI for UWP is published on GitHub and is structured as follows: BuildTools: contains scripts and configs for building Telerik UI for UWP as a local NuGet package Controls: contains source files for Telerik UI for UWP Drawing.UWP/DrawingUWP: Direct2D/C++ project used by the map component for rendering shapes SDKExamples.UWP: contains over 190 examples of the Telerik UI for UWP control suite UnitTests/UAP.Tests: contains unit tests for controls like the Chart and Grid The repository has two solution files, UWPControls.sln and UWPMap.sln. These contain the source files of the control suite and map component. There's also a project file, SDKExamples.UWP.csproj that contains the SDK examples. I'd recommend walking through the XAML and C# source files. They contain many examples to help you understand how the controls operate. Before you start getting your hands dirty with Telerik UI for UWP, it's important that you have the required software installed to build UWP applications. If you don't, Visual Studio will get angry and take the ball home (so-to-speak). Please note that both Visual Studio 2015 and Visual Studio 2017 are supported. That stated, I'd recommend using Visual Studio 2017 due to the recent improvements that have been added to the IDE. It's always best more fun on the latest and greatest anyway. The easiest way to build the source of Telerik UI for UWP is to open the file, UWPControls.sln in Visual Studio and compile the solution from there. Under its default configuration, Visual Studio will restore the NuGet packages that are used by Telerik UI for UWP during this process. The same procedure should be followed for building the map component. This is located in the solution, UWPMap.sln. In both cases, assemblies (along with PDBs and compiled resource files) will be created in a folder labelled, Binaries after the build process completes. You may encounter an error when attempting to build the source with Visual Studio: The following workaround will resolve this behaviour: Credit to Hrvoje Matić for discovering this workaround, which was posted to the NuGet issues list back in September 2016. Telerik UI for UWP is available as a package on NuGet and can be incorporated into a new or existing product through Visual Studio: You can add this package to a project through the Package Manager Console or the Solution Explorer: Once added, controls can be added and qualified in XAML pages through prefixes and namespaces. Here's an example using the RadialGauge control: <Page xmlns: ... <telerik:RadRadialGauge> ... </telerik:RadRadialGauge> </Page> At the time of this writing, we don't have an installer to place the Telerik UI for UWP controls into the Visual Studio Toolbox. However, you can do this yourself by following these steps: Telerik.UI.for.UniversalWindowsPlatformNuGet package to your application C:\Users\%USERNAME%\.nuget\packages\telerik.ui.for.universalwindowsplatform Choose the folder name matching the version you have installed (i.e. 1.0.0.4), navigate to the lib\uap10.0 sub-folder and select the following files: Telerik.UI.Xaml.Chart.UWP.dll Telerik.UI.Xaml.Grid.UWP.dll Telerik.UI.Xaml.Input.UWP.dll Telerik.UI.Xaml.Primitives.UWP.dll Telerik.UI.Xaml.Map.UWP.dll(located in the x86/ x64sub-folder) Once added, these controls will be able in the Toolbox window of Visual Studio. This will allow you to drag & drag them onto the visual design surface of the XAML pages in your UWP application. Now, the fun begins: building an application that uses the Chart and Grid controls. These controls are well understood by developers so this is a good place to start. The Chart control is versatile charting component that you can use to visualize data in many different ways. Here, I'm going to build an application that uses it to represent a set of arbitrary data. I'll start by creating a new UWP application in Visual Studio and add the Telerik UI for UWP NuGet package to the solution: From here, I'll open up MainPage.xaml and add a RadCartesianChart element to the page: > </Grid> </Page> Running this application will display the chart with the following messages: These messages are displayed by the Chart control if you don't define its horizontal and vertical axis. They are required (along with a series definition) to render the data that's associated with the chart at runtime. The next task is to bind some underlying data and define the horizontal and vertical axis that will be used to display it. I'll define a model that will generate a collection of random values for Australian city names to which I can bind the chart: public class City { public string Name { get; set; } public double) }); } return cities; } } Next, I'll add to the chart declaration to include the axis and a line series: :LineSeries <telerik:LineSeries.ValueBinding> <telerik:PropertyNameDataPointBinding </telerik:LineSeries.ValueBinding> <telerik:LineSeries.CategoryBinding> <telerik:PropertyNameDataPointBinding </telerik:LineSeries.CategoryBinding> </telerik:LineSeries> </telerik:RadCartesianChart> </Grid> </Page> In the XAML (above), I've defined a CategoricalAxis for the horizontal axis. This displays a range of categories whose values are displayed in the order defined by the underlying collection that's bound to the chart. The vertical axis uses a LinearAxis which represents a sequential list of numerical values. Other axis types for date/time values and logarithmic sequences are also supported. I've also indicated that I've like to generate a line chart based on the LineSeries that's declared. Notice that I've bound the value and category values to properties found on the City class I defined earlier. Other options to binding data are available, such as specifying the data points in the XAML directly: <telerik:RadCartesianChart <telerik:RadCartesianChart.Series> <telerik:LineSeries> <telerik:LineSeries.DataPoints> <telerik:CategoricalDataPoint <telerik:CategoricalDataPoint <telerik:CategoricalDataPoint <telerik:CategoricalDataPoint <telerik:CategoricalDataPoint </telerik:LineSeries.DataPoints> </telerik:LineSeries> </telerik:RadCartesianChart.Series> <!-- markup removed for brevity --> </telerik:RadCartesianChart> The final step is to bind the chart to the data that's generated by the CityManager class in the constructor of the page: public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); this.DataContext = CityManager.GetCities(); } } Running this application will display the chart of the data that's randomly generated: It's important to note that the Chart control is highly customizable. There are a number of properties that I can target that will modify the chart that's generated. For example, I can add the following XAML to my chart declaration to draw lines for the major axis points: <telerik:RadCartesianChart <telerik:RadCartesianChart.Grid> <telerik:CartesianChartGrid </telerik:RadCartesianChart.Grid> <!-- markup removed for brevity --> </telerik:RadCartesianChart> This change will display the chart with the X and Y-axis major lines drawn: From here, you can modify the XAML used to generate a chart to display an area chart: <telerik:RadCartesianChart <telerik:AreaSeries <telerik:AreaSeries.ValueBinding> <telerik:PropertyNameDataPointBinding </telerik:AreaSeries.ValueBinding> <telerik:AreaSeries.CategoryBinding> <telerik:PropertyNameDataPointBinding </telerik:AreaSeries.CategoryBinding> </telerik:AreaSeries> <!-- markup removed for brevity --> </telerik:RadCartesianChart> Running the application with this change will generate an area chart a different set of random data: As you delve into the specifics of the Chart control from Telerik UI for UWP, you'll discover that it has many built-in features. You can read more about these features on the for the Chart control in our documentation. Now, let's see an example of the Grid in Telerik UI for UWP using the same underlying data. The Grid control enables you to display and manipulate vast amounts of data in a control that's fast, fluid, and responsive. It's also highly customizable for operations like filtering, paging, sorting, and grouping. Let's see how to get a Grid control up and running in my existing UWP application. I'll start by making a few modifications to the XAML I defined earlier: <Page x: <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <!-- added: column definitions for layout --> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <!-- I'll add the grid here --> <!-- added: specified column location --> > In the XAML (above), I've made a couple of changes. First, I've changed the namespace prefix, telerik to telerikChart. I'll soon add another namespace for the Grid control and I want a better naming convention to identify my controls. And second, I've specified the layout of the grid used to contain my controls to include a couple of row definitions. Essentially, I want the Grid control to sit above the existing Chart control on my page. Running this code displays our application with a modified layout: Now let's add the Grid control. As it turns out, this is a pretty simple task: <telerikGrid:RadDataGrid Grid. </telerikGrid:RadDataGrid> This is all that's required to add to our existing markup in order to have a Grid control added to our existing application. Here's how the page looks with this change: <Page x: <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <telerikGrid:RadDataGrid Grid. </telerikGrid:RadDataGrid> > You can start to appreciate just how powerful these controls are when you run the application: By default, the Grid auto-generates the columns based on the object that it's bound to. This includes built-in filtering, which you can use to drill down into the data. Furthermore, the Grid control has grouping enabled by default. This allows me to combine rows that have equal column values. Let's modify the code that's used to generate this data to see how this works: public class City { public string Name { get; set; } public double Value { get; set; } public bool), Question = random.Next(0, 2) == 0 }); } return cities; } } Here, I've added a Boolean property to the City class that I've given an arbitrary name. Its value will be randomly generated to be either true or false. When we run our application, notice that this new property is automatically displayed by the Grid control: The Grid control knows that this new column's type is a Boolean so it also uses a checkbox to display its value. This is also reflected in the filter drop-down menu in the column header: The Grid control has support built-in for primitives types (i.e. Boolean) for operations like filtering, sorting, and grouping. When binding to complex types, you can control how values are displayed and navigated through these operations as well. If left undefined, the Grid control will display the type name for complex types by default. With grouping enabled by default, we can drag and drop a column header to the grouping area and have the rows grouped by the new property I've added: Even when grouping is enabled, operations such as paging, filtering, and sorting remain intact. As you've seen, incorporating Telerik UI for UWP into a UWP project is a manual process. Developers looking for a guided approach towards building applications with Telerik UI for UWP should check out Windows Template Studio: This extension for Visual Studio will generate a UWP application through templates. The goal is to get you up and running quickly with a project structure and source files that can be modified afterward. Recently, Windows Template Studio added templates for the Chart and Grid controls from Telerik UI for UWP: Selecting either of those controls will generate pages will the necessary XAML and code needed to display them: Telerik UI for UWP provides a suite of powerful controls that you can use in your UWP applications. These controls address common UI requirements in line-of-business (LOB) applications. You can find the source code (Apache License v2.0) and the documentation on GitHub. Getting started is easy. You can build the source code yourself or pull down the bits from NuGet. Once downloaded, controls like the Chart and Grid can be easily incorporated and bound to data from underlying sources. If you have feedback, please let us know through the Telerik UI for UWP issues list on GitHub or the Telerik UI for UWP Feedback Portal. In the meantime, I encourage you to check the controls, build a prototype, and/or start incorporating them into your UWP apps today! Pingback: Dew Drop - August 2, 2017 (#2533) - Morning Dew()
http://developer.telerik.com/content-types/tutorials/getting-started-with-telerik-ui-for-uwp/
CC-MAIN-2017-34
refinedweb
2,101
54.12
# Kernel Queue: The Complete Guide On The Most Essential Technology For High-Performance I/O When talking about high-performance software we probably think of server software (such as nginx) which processes millions requests from thousands clients in parallel. Surely, what makes server software work so fast is high-end CPU running with huge amount of memory and a very fast network link. But even then, the software must utilize these hardware resources at maximum efficiency level, otherwise it will end up wasting the most of the valuable CPU power for unnecessary kernel-user context switching or while waiting for slow I/O operations to complete. Thankfully, the Operating Systems have a solution to this problem, and it's called *kernel event queue*. Server software and OS kernel use this mechanism together to achieve minimum latency and maximum scalability (when serving a very large number of clients in parallel). In this article we are going to talk about **FreeBSD, macOS and kqueue**, **Linux and epoll**, **Windows and I/O Completion Ports**. They all have their similarities and differences which we're going to discuss here. The goal of this article is for you to understand the whole mechanism behind kernel queues and to understand how to work with each API. *I assume you are already familiar with socket programming and with asynchronous operations, but anyway, in case you think there's something I should define or explain in more detail - send me a message, I'll try to update the article.* *Although I tried to keep this article clean of any unnecessary sentences (it's not a novel, after all), I sometimes can't stop myself from expressing my thoughts about something I like or dislike.* Contents: * [What is kernel queue?](#what-is-kernel-queue) + [API Principles](#api-principles) * [FreeBSD/macOS and kqueue](#freebsdmacos-and-kqueue) + [Accepting socket connections with kqueue](#accepting-socket-connections-with-kqueue) + [Creating and closing kqueue object](#creating-and-closing-kqueue-object) + [Attaching socket descriptor to kqueue](#attaching-socket-descriptor-to-kqueue) + [Receiving events from kqueue](#receiving-events-from-kqueue) + [Processing received events from kqueue](#processing-received-events-from-kqueue) + [Establishing TCP connection with kqueue](#establishing-tcp-connection-with-kqueue) + [Processing stale cached events](#processing-stale-cached-events) + [User-triggered events with kqueue](#user-triggered-events-with-kqueue) + [System timer events with kqueue](#system-timer-events-with-kqueue) + [UNIX signals from kqueue](#unix-signals-from-kqueue) + [Asynchronous file I/O with kqueue](#asynchronous-file-io-with-kqueue) * [Linux and epoll](#linux-and-epoll) + [Accepting socket connections with epoll](#accepting-socket-connections-with-epoll) + [Creating and closing epoll object](#creating-and-closing-epoll-object) + [Attaching socket descriptor to epoll](#attaching-socket-descriptor-to-epoll) + [Receiving events from epoll](#receiving-events-from-epoll) + [Processing received events from epoll](#processing-received-events-from-epoll) + [Establishing TCP connection with epoll](#establishing-tcp-connection-with-epoll) + [User-triggered events with epoll](#user-triggered-events-with-epoll) + [System timer events with epoll](#system-timer-events-with-epoll) + [UNIX signals from epoll](#unix-signals-from-epoll) + [Asynchronous file I/O with epoll](#asynchronous-file-io-with-epoll) * [Windows and I/O Completion Ports](#windows-and-i-o-completion-ports) + [Accepting connections to a named pipe with IOCP](#accepting-connections-to-a-named-pipe-with-iocp) + [Creating and closing IOCP object](#creating-and-closing-iocp-object) + [Attaching file descriptor to IOCP](#attaching-socket-descriptor-to-iocp) + [Receiving events from IOCP](#receiving-events-from-iocp) + [Processing received events from IOCP](#processing-received-events-from-iocp) + [User-triggered events with IOCP](#user-triggered-events-with-iocp) + [Establishing TCP connection with IOCP](#establishing-tcp-connection-with-iocp) + [Writing data to a TCP socket with IOCP](#writing-data-to-a-tcp-socket-with-iocp) + [Reading data from a TCP socket with IOCP](#reading-data-from-a-tcp-socket-with-iocp) + [Reading and writing data from/to a UDP socket with IOCP](#reading-and-writing-data-fromto-a-udp-socket-with-iocp) + [I/O Cancellation with IOCP](#io-cancellation-with-iocp) + [Accepting socket connections with IOCP](#accepting-socket-connections-with-iocp) + [System timer events with IOCP](#system-timer-events-with-iocp) + [Asynchronous file I/O with IOCP](#asynchronous-file-io-with-iocp) ### What is kernel queue? Kernel event queue (which I'm gonna call KQ from now on) is a **fast signal-delivery mechanism** which allows server software to process events from OS in a very effective way. KQ is a bunch of data living in kernel memory and a bunch of kernel code that operates with this data to notify a user-level application about various system events. A user app can't access KQ data directly (it's managed by kernel) and so it operates with KQ via the API that OS provides. There are 3 different API we're going to use here: kqueue, epoll, IOCP. However, this section describes kernel queues in general so the API doesn't matter for now. Because the main purpose of KQ is to deliver notifications from network sockets, let me formulate the key idea in a different way: > A user application wants to be notified when any of its sockets is ready to read or write some data, and the OS kernel serves this purpose by maintaining the list of all registered and signalled events. > > #### Use-case N1 What an application achieves through KQ technology is that the app is notified about an I/O signal such as when a **network packet is received**. For example: 0. Suppose some user app created a UDP socket and registered it with a KQ along with some app-defined data (i.e. cookie). 1. At some point the last chunk of a UDP packet is received by network device. 2. OS now has a complete UDP packet and is ready to notify the user process as soon as it calls the KQ waiting function. 3. At some time the user app calls KQ waiting function which tells the kernel: `Give me something new`. 4. OS responds with `Got a READ event from the socket associated with your cookie`. 5. This cookie is the object pointer which the app then uses to handle the signal - *read a message from UDP socket*, in our case. > Note that neither the opening of a socket, neither reading from a socket after the signal is received isn't normally the part of KQ mechanism. On UNIX we always use conventional socket functions and we use KQ functions to receive events associated with sockets. However, IOCP on Windows is different. There, I/O functions and their associated events are a part of a single mechanism. Anyway, we'll deal with IOCP later, so for now just don't bother with it - let us always think by default that KQ just delivers signals. > > #### Use-case N2 Consider the next example where the user app receives a **notification after a TCP socket connects to its peer**: 0. User app creates a TCP socket and registers it with a KQ along with some app-defined data (i.e. cookie). 1. Now the app begins the procedure to connect to a remote host. Obviously, this operation can't finish immediately most of the time, because it takes some time to transmit 2 TCP packets needed for TCP connection. Moreover, what if the network link is very busy and the packets get dropped? Needless to say that TCP connection may take a long time to finish. Because of that, OS returns the control back to the app with the result `Can't finish the operation immediately`. While packets are being sent and received, the app keeps doing some other stuff, relying on OS to do its best to complete the connection procedure. 2. Finally, a `SYN+ACK` TCP packet is received from the remote host, which means it's willing to establish a TCP connection with our app. Now OS is ready to signal the app as soon as the latter becomes ready. 3. At some point the user app calls the KQ waiting function which tells the kernel: `Give me something new`. 4. OS responds with `Got a WRITE event from the socket associated with your cookie`. 5. This cookie is the object pointer which the app then uses to handle the signal - *write some data to the TCP socket*, in our case. Although the primary use of KQ is I/O event notifications, it also can be used for other purposes, for example KQ can notify when a child process signals its parent (i.e. **UNIX signals delivery**), or KQ can be used to receive **notifications from a system timer**. I also explain these use-cases and show the example code in this article. #### Internal representation example Let's see a diagram with an example of how KQ may look like internally after a user app has registered 6 different events there (user-triggered event, I/O events, system timer), 3 of which have signalled already. ``` KQ table example ================================= Event | Descriptor | Signalled? ---------+------------+----------- USER | #789 | READ | #1 | READ | #2 | yes WRITE | #2 | yes WRITE | #3 | TIMER | #456 | yes ``` In this example, both READ and WRITE events for socket #2 are in signalled state which means we can read and write data from/to this socket. And the timer event is in signalled state too which means the system timer interval has expired. The signalled flag also means that after a user app calls the function to receive events from KQ, it will receive an array of these 3 signalled events so it can process them. The kernel then may clear the signalled flag so that it won't deliver the same signals over and over again unless necessary. Of course in reality KQ is much more complex but we don't need to know exactly how the KQ is implemented internally - we need just to understand what and when it delivers to us and how me may use it effectively. I'm not a kernel developer so I don't know much about how it's implemented inside - you have to read some Linux/FreeBSD kernel manuals and epoll/kqueue code if you are interested in this subject. #### API Principles Now let's talk about what features all those API provide us with. In general, working with a KQ API consists of 4 steps: 1. **Create KQ object**. It's the easiest part, where we just call a function which returns the descriptor for our new KQ. We may create KQ objects as many as we want, but I don't see the point of creating more than 1 per process or thread. 2. **Attach file/socket descriptor** along with opaque user data to KQ. We have to tell the OS that we want it to notify us about any particular descriptor through a particular KQ object. How else the kernel should know what to notify us about? Here we also associate some data with the descriptor, which is usually a pointer to some kind of a structure object. How else are we going to handle the received signal? The attachment is needed only once for each descriptor, usually it's done right after the descriptor is configured and ready for I/O operations (though we can delay that until absolutely necessary to probably save a context switch). The detachment procedure usually is not needed (with the right design), so we won't even talk about it here. 3. **Wait for incoming events from KQ**. When the user app has nothing more important to do, it calls a KQ waiting function. We specify the output array of events and timeout value as parameters when calling this function. It fills our array with the information about which events signalled and how they signalled. By using an array of events rather than a single event we save CPU time on somewhat costly kernel-userspace context switches. By using timeout value we control how much time this KQ function can block internally. If we specify a positive value, then the function will block for this amount of time in case it has no events to give us. If we specify 0, it won't block at all and return immediately. > Some people use a small timeout value for KQ waiting functions so that they can check for some flags and variables and probably exit the waiting loop if some condition is met. But when using a small timeout value, like 50ms, they waste a lot of context switches unnecessarily. In this case OS periodically wakes up their process, even if it has nothing to do except calling the same KQ waiting function again in the next loop iteration. If you use this technique, it's most likely that there's something you do wrong. All normal software should use inifinite timeout, so the process wakes only when it is necessary. > > 4. **Destroy KQ object**. When we don't need a KQ object anymore, we close it so the OS can free all associated memory. Obviously, after KQ object is closed, you won't be able to receive any notifications for the file descriptors attached to it. What I like the most about this whole KQ idea is that user code is very clear and straightforward. I think the OS must deliver a nice, clear and convenient API for their users - the API which everybody understands how it works. And the way I understand it, a canonical KQ mechanism shouldn't do or require users to do anything else except registering an event inside KQ and delivering this event from KQ to the user once it signals. There is one single promise to the user: `When an event you care about signals, I will notify you about it`. It allows the user code to be very flexible and free to do whatever it wants. Let's see an example with pseudo code which proves my point. #### Pseudo code example ``` // Pseudo code for an asynchronous HTTP/1 client func do_logic(kq) { conn := new conn.socket = socket(TCP, NONBLOCK) kq.attach(conn.socket, conn) // attach our socket along with the object pointer to KQ conn.connect_to_peer() } func connect_to_peer(conn) { addr := "1.2.3.4:80" result := conn.socket.connect_async(addr) // initiate connection or get the result of the previously initiated connection procedure if result == EINPROGRESS { conn.write_handler = connect_to_peer return } print("connected to %1", addr) conn.write_data() } func write_data(conn) { data[] := "GET / HTTP/1.1\r\nHost: hostname\r\n\r\n" result := conn.socket.send(data) if result == EAGAIN { conn.write_handler = write_data return } print("written %1 bytes to socket", result) conn.read_data() } func read_data(conn) { data[], result := conn.socket.receive() if result == EAGAIN { conn.read_handler = read_data return } print("received %1 bytes from socket: %2", result, data) } func worker(kq) { for { events[] := kq_wait(kq) for ev := events { conn := ev.user_data if ev.event == READ { conn.read_handler() } if ev.event == WRITE { conn.write_handler() } } } } ``` Here we have 3 operations: connect, socket write, socket read. All 3 may block with a normal socket descriptor, so we set a non-blocking flag when creating the socket. Then we attach our socket to KQ along with the pointer to our object `conn`. Now we are ready to use the socket as we want, in our example we have a client socket which needs to be connected to a server. We begin a socket connection procedure which may or may not complete immediately. In case it completes immediately - we continue with our program logic as usual, but in case it can't complete immediately it just returns `EINPROGRESS` error code. If it does so, we set `write_handler` function pointer to the name of our function we want to be called when connection is established. And then we just return from our function, because there's nothing else for us to do - we must wait. At this point our application is free to do whatever it wants - process something else or just wait until some events are received from the kernel. Which is why we have a `worker()` function. It receives events from KQ and processes them one by one, calling the appropriate handler function. In our case, `connect_to_peer()` function will be called after the TCP socket connection is established (or failed). Now we're inside this function the second time and we now get the result of our previous connect request. It may be a failure, but I don't check it here for the simplicity of our example. In case the connection was successul, we continue by calling `write_data` function which sends an HTTP request to a server. Again, it may or may not complete immediately, so in case it returns with `EAGAIN` error, we set `write_handler` and return. As simple as that. After some time we are back inside our function again and we try to send the data once more. We may go back and forth with this logic until we have sent the complete data for our HTTP request. Once it's sent we start reading the HTTP response from server. We are inside the `read_data()` function which starts reading data from socket. It may or may not complete immediately. If it returns with `EAGAIN`, we set `read_handler` and return. Why do we use a different name for function pointer depending on whether it's READ or WRITE event? For our example it doesn't matter, but in real life when we use full-duplex sockets, *both* events may fire at once, therefore we must be prepared to handle both READ and WRITE events in parallel. Isn't it simple? The only thing we need inside our program logic is to check for return values and error codes and set handling function pointers, then after some time we're back **in the same function** to try once more **with the same code**. I love this approach - it makes everything seem very clear, even though we've just written the program logic that can easily handle thousands of connections in parallel. ### FreeBSD/macOS and kqueue Now I think we're ready for some real code with a real API. kqueue API is the one I like the most for some reason, so let's start with it. **I strongly advise you to read this section and try to completely understand it, even if you won't use FreeBSD in your work.** There's just one syscall `kevent()` which we use with several different flags to control its behaviour. #### Accepting socket connections with kqueue Let's see an easy example of a server which accepts a new connection by an event from kqueue. ``` /* Kernel Queue The Complete Guide: kqueue-accept.c: Accept socket connection Usage: $ ./kqueue-accept $ curl 127.0.0.1:64000/ */ #include #include #include #include #include #include #include #include int kq; // the structure associated with a socket descriptor struct context { int sk; void (\*rhandler)(struct context \*obj); }; void accept\_handler(struct context \*obj) { printf("Received socket READ event via kqueue\n"); int csock = accept(obj->sk, NULL, 0); assert(csock != -1); close(csock); } void main() { // create kqueue object kq = kqueue(); assert(kq != -1); struct context obj = {}; obj.rhandler = accept\_handler; // create and prepare a socket obj.sk = socket(AF\_INET, SOCK\_STREAM | SOCK\_NONBLOCK, 0); assert(obj.sk != -1); int val = 1; setsockopt(obj.sk, SOL\_SOCKET, SO\_REUSEADDR, &val, 4); struct sockaddr\_in addr = {}; addr.sin\_family = AF\_INET; addr.sin\_port = ntohs(64000); assert(0 == bind(obj.sk, (struct sockaddr\*)&addr, sizeof(addr))); assert(0 == listen(obj.sk, 0)); // attach socket to kqueue struct kevent events[2]; EV\_SET(&events[0], obj.sk, EVFILT\_READ, EV\_ADD | EV\_CLEAR, 0, 0, &obj); EV\_SET(&events[1], obj.sk, EVFILT\_WRITE, EV\_ADD | EV\_CLEAR, 0, 0, &obj); assert(0 == kevent(kq, events, 2, NULL, 0, NULL)); // wait for incoming events from kqueue struct timespec \*timeout = NULL; // wait indefinitely int n = kevent(kq, NULL, 0, events, 1, timeout); assert(n > 0); // process the received event struct context \*o = events[0].udata; if (events[0].filter == EVFILT\_READ) o->rhandler(o); // handle read event close(obj.sk); close(kq); } ``` This code creates a TCP socket, attaches it to the newly created KQ, and waits for incoming connections. After a client is connected, it prints a message to stdout and sends an HTTP response. Inline comments explain in short form what each block is for. Now we're going to describe all this in detail. #### Creating and closing kqueue object To create a new KQ object, we call `kqueue()` function which returns the descriptor or `-1` on error. KQ object is usually stored in the global context (in our case - it's just a global variable) because we need it all the time while our app is running. We close KQ object with `close()`. ``` kq = kqueue(); ... close(kq); ``` #### Attaching socket descriptor to kqueue So how do we attach a file descriptor to our kqueue object? First, we prepare an object where we define: * Which file descriptor we want to associate with KQ. This value can be a socket, UNIX signal, or an arbitrary user-defined ID, depending on the type of event we want to register. * Which event we are interested in. For I/O events this value must be either `EVFILT_READ` or `EVFILT_WRITE`. For UNIX signals it's `EVFILT_SIGNAL`, for timers it's `EVFILT_TIMER`, for user events it's `EVFILT_USER`, but they will be explained later in separate sections. * What we want `kevent()` to do: `EV_ADD` attaches descriptor to KQ. `EV_CLEAR` flag prevents the event from unnecessary signalling (it's explained later). * What object pointer we associate with our file descriptor. Normally, this object contains at least 2 fields: file descriptor itself and the function pointer which handles the event. To set the above parameters we use `EV_SET()` macro for convenience but you may also use the `struct kevent` fields directly. Then, we call `kevent()` function which processes all our events we supplied to it and returns `0` on success. ``` struct kevent events[2]; EV_SET(&events[0], sk, EVFILT_READ, EV_ADD | EV_CLEAR, 0, 0, obj); EV_SET(&events[1], sk, EVFILT_WRITE, EV_ADD | EV_CLEAR, 0, 0, obj); kevent(kq, events, 2, NULL, 0, NULL); ``` #### Receiving events from kqueue To receive events from KQ we must have a place to store them so the kernel can prepare the data for us - we need an array for signalled events, array of `struct kevent` objects. Note that it doesn't necessarily mean that events are stored in kernel memory in the same form - it's just what the kernel prepares for us. Normally, the events are stored in the chronological order, meaning that the event with index 0 has signalled before the event with a larger index, but this isn't important for us, because user software is prepared to handle the events in any order anyway. In our example we use an array for the maximum of 1 events. Only very busy software can benefit from using a large array here to minimize the number of context switching. We call `kevent()` function and pass the array to it along with a timeout value defining how long it can block in case there are no signalled events. The function returns the number of signalled events, or `0` if timeout value has passed before anything signalled, or `-1` on error. Normally, we call KQ waiting functions in a loop like so: ``` while (!quit) { struct timespec *timeout = NULL; // wait indefinitely struct kevent events[1]; int n = kevent(kq, NULL, 0, events, 1, &timeout); if (n < 0 && errno == EINTR) continue; // kevent() interrupts when UNIX signal is received } ``` As you can see we also check the return value for error `EINTR` which means that while `kevent()` was waiting for events a UNIX signal has been received and processed by a UNIX signal handling function. This behaviour allows us to easily handle some important global flags that signal handlers may set. For example we may handle `SIGINT` signal which is sent after the user presses `Ctrl+C` within the terminal window. Then `SIGINT` signal handling function may set some kind of `quit` flag to indicate we should exit our app. `kevent()` then returns with `EINTR`, and we check for `quit` value and exit the loop in this case. #### Processing received events from kqueue To process an event which we have received from KQ previously we have to know what to do with it. But all events look pretty much the same to us at this point. That's why we used an object pointer with `EV_SET()` to associate it with each event. Now we can simply call an event handling function. We get this pointer by accessing `struct kevent.udata` field. For full-duplex I/O we need either 2 different handling functions or a single handler which will check itself which filter has signalled. Since all KQ mechanisms have their different ways, I recommend you to go with 2-handlers approach and choose which handler to execute here, at the lowest level, to simplify the higher level code. ``` struct context *o = events[i].udata; if (events[i].filter == EVFILT_READ) o->rhandler(o); // handle read event else if (events[i].filter == EVFILT_WRITE) o->whandler(o); // handle write event ``` Do you remember the `EV_CLEAR` flag we supplied to KQ when we attached socket to it? Here's why we need to use it. For example, after KQ returns a READ event to us, it won't signal again until we drain all the data from this socket, i.e. until `recv()` returns with `EAGAIN` error. This mechanism prevents from signalling the same event over and over again each time we call KQ waiting function, thus improving overall performance. The software that can't deal with `EV_CLEAR` behaviour most probably has a design flaw. #### Establishing TCP connection with kqueue Now let's see how to correctly use `connect()` on a TCP socket with kqueue. What makes this use-case special is that there is no function that could return the result of previous `connect()` operation. Instead, we must use `struct kevent` to get the error code. Here's an example. ``` int r = connect(sk, ...); if (r == 0) { ... // connection completed successfully } else if (errno == EINPROGRESS) { // connection is in progress struct kevent events[1]; int n = kevent(kq, NULL, 0, events, 1, &timeout); if (events[0].filter == EVFILT_WRITE) { errno = 0; if (events[i].flags & EV_EOF) errno = events[0].fflags; ... // handle TCP connection result depending on `errno` value } } else { ... // fatal error } ``` Suppose that we created a non-blocking TCP socket, attached it to KQ, and now we begin the connection procedure. If it completes successfully right away, then we can read or write data to it immediately, and it isn't what we are talking about here. But if it returns `-1` with `EINPROGRESS` error, we should wait until OS notifies about with the result of the procedure. And here's the main thing: when `EVFILT_WRITE` event is received we test `struct kevent.flags` field for `EV_EOF` and if it's set, then it means that `connect()` has failed. In this case `struct kevent.fflags` field contains the error number - the same error that a blocking `connect()` call would set. > I have to say that I don't like this whole logic with getting an error code from `struct kevent` because it forces me to multiply branches in my code. Another reason behind that is because it's kqueue-specific stuff - for example on Linux we have to call `getsockopt(..., SOL_SOCKET, SO_ERROR, ...)` to get error code. But on the other hand, on FreeBSD we don't need to perform another syscall which probably outweighs both of my points above, so in the end I think it's alright. > > Let's see the complete example of a simple HTTP/1 client that connects, sends request and receives response - all via KQ. But of course you may notice that our code for handling WRITE event from KQ is useless here, because our request is very small and should always fit into the empty socket buffer, i.e. `send()` will always complete immediately. But I think it's OK for a sample program - the goal is to show you the general principle. ``` /* Kernel Queue The Complete Guide: kqueue-connect.c: HTTP/1 client Usage: $ nc -l 127.0.0.1 64000 $ ./kqueue-connect */ #include #include #include #include #include #include #include #include #include int kq; int quit; // the structure associated with a socket descriptor struct context { int sk; void (\*rhandler)(struct context \*obj); void (\*whandler)(struct context \*obj); int data\_offset; }; void obj\_write(struct context \*obj); void obj\_read(struct context \*obj); void obj\_prepare(struct context \*obj) { // create and prepare socket obj->sk = socket(AF\_INET, SOCK\_STREAM | SOCK\_NONBLOCK, 0); assert(obj->sk != -1); int val = 1; assert(0 == setsockopt(obj->sk, 0, TCP\_NODELAY, (char\*)&val, sizeof(int))); // attach socket to KQ struct kevent events[2]; EV\_SET(&events[0], obj->sk, EVFILT\_READ, EV\_ADD | EV\_CLEAR, 0, 0, obj); EV\_SET(&events[1], obj->sk, EVFILT\_WRITE, EV\_ADD | EV\_CLEAR, 0, 0, obj); assert(0 == kevent(kq, events, 2, NULL, 0, NULL)); } void obj\_connect(struct context \*obj) { if (obj->whandler == NULL) { // begin asynchronous connection struct sockaddr\_in addr = {}; addr.sin\_family = AF\_INET; addr.sin\_port = ntohs(64000); char ip4[] = {127,0,0,1}; \*(int\*)&addr.sin\_addr = \*(int\*)ip4; int r = connect(obj->sk, (struct sockaddr\*)&addr, sizeof(struct sockaddr\_in)); if (r == 0) { // connection completed successfully } else if (errno == EINPROGRESS) { // connection is in progress obj->whandler = obj\_connect; return; } else { assert(0); // fatal error } } else { assert(errno == 0); // connection is successful obj->whandler = NULL; // we don't want any more signals from KQ } printf("Connected\n"); obj\_write(obj); } void obj\_write(struct context \*obj) { const char data[] = "GET / HTTP/1.1\r\nHost: hostname\r\nConnection: close\r\n\r\n"; int r = send(obj->sk, data + obj->data\_offset, sizeof(data)-1 - obj->data\_offset, 0); if (r > 0) { // sent some data obj->data\_offset += r; if (obj->data\_offset != sizeof(data)-1) { // we need to send the complete request obj\_write(obj); return; } obj->whandler = NULL; } else if (r < 0 && errno == EAGAIN) { // the socket's write buffer is full obj->whandler = obj\_write; return; } else { assert(0); // fatal error } printf("Sent HTTP request. Receiving HTTP response...\n"); obj\_read(obj); } void obj\_read(struct context \*obj) { char data[64\*1024]; int r = recv(obj->sk, data, sizeof(data), 0); if (r > 0) { // received some data printf("%.\*s", r, data); obj\_read(obj); return; } else if (r == 0) { // server has finished sending data } else if (r < 0 && errno == EAGAIN) { // the socket's read buffer is empty obj->rhandler = obj\_read; return; } else { assert(0); // fatal error } quit = 1; } void main() { // create KQ object kq = kqueue(); assert(kq != -1); struct context obj = {}; obj\_prepare(&obj); obj\_connect(&obj); // wait for incoming events from KQ and process them while (!quit) { struct kevent events[1]; struct timespec \*timeout = NULL; // wait indefinitely int n = kevent(kq, NULL, 0, events, 1, timeout); if (n < 0 && errno == EINTR) continue; // kevent() interrupts when UNIX signal is received assert(n > 0); // now process each signalled event for (int i = 0; i != n; i++) { struct context \*o = events[i].udata; errno = 0; if (events[i].flags & EV\_EOF) errno = events[i].fflags; if (events[i].filter == EVFILT\_READ && o->rhandler != NULL) o->rhandler(o); // handle read event if (events[i].filter == EVFILT\_WRITE && o->whandler != NULL) o->whandler(o); // handle write event } } close(obj.sk); close(kq); } ``` *Note that macOS doesn't support* `SOCK_NONBLOCK` flag in `socket()` - you should set the socket as nonblocking manually. #### Processing stale cached events One of the most interesting aspects of programming with KQ is handling the events in which we in fact are not interested anymore. Here's what may happen when we use KQ *carelessly*: * We attach a socket to KQ for both READ and WRITE events. * We keep performing normal operations on a socket, reading and writing to it occasionally. * At some point both READ and WRITE events get signalled. * We use an array of events for KQ waiting function and it **returns 2 events to us for the same socket**. * We start handling the first event which happens to be a READ event. * We call READ event handling function, it processes this event and comes to a conclusion that the client object should be closed, because it has sent some invalid data. We close the socket and destroy the object. And everything seems to be correct, because after the socket is closed KQ won't signal us with it anymore. But remember that we have called a KQ waiting function some time ago and it has already returned 2 events to us. We've handled the first event just now, but the second event is still in our array of event objects and is yet to be processed in the next iteration of the loop. * We start handling the second event which is WRITE event in our case. We take our object data associated with the event and we try to call the handling function. BAM! We hit the memory region we have just destroyed while handling the READ event. This can happen at any time while our app is running and we don't know anything in advance - we need to correctly determine such cases and handle them as they occur. Note that this situation isn't just limited to full-duplex sockets, but to any KQ event in general. Suppose a timer signal has fired and we decided to close a client connection, but its socket has signalled already, and there's an associated event already in our cache - we just don't know it yet, because the timer signal has occurred just before it. So unless we always limit the number of received events from KQ to 1, we must always be ready to handle this situation - we can't prevent it from happening. And of course, there's the same problem on Linux with epoll, so it's not just kqueue-only stuff. So how are we going to solve this problem? Thankfully, it's already solved by Igor Sysoev (the great man who initially wrote nginx) long time ago. Here's the trick. ``` struct context { int sk; void (*handler)(struct context *obj); int flag; }; void handler_func(struct context *obj) { if (...) { goto finish; // an error occurred } ... finish: close(obj->sk); obj->flag = !obj->flag; // turn over the safety flag } void main() { ... struct context *obj = ...; obj->flag = 0; struct kevent events[2]; void *ptr = (void*)((size_t)obj | obj->flag); // pass additional flag along with the object pointer to KQ EV_SET(&events[0], obj->sk, EVFILT_READ, EV_ADD | EV_CLEAR, 0, 0, ptr); EV_SET(&events[1], obj->sk, EVFILT_WRITE, EV_ADD | EV_CLEAR, 0, 0, ptr); kevent(kq, events, 2, NULL, 0, NULL); ... int n = kevent(kq, NULL, 0, events, 8, &timeout); for (...) { void *ptr = events[i].udata; struct context *obj = (void*)((size_t)ptr & ~1); // clear the lowest bit int flag = (size_t)ptr & 1; // check the lowest bit if (flag != obj->flag) continue; // don't process this event obj->handler(obj); } } ``` Explanation: * When we attach a socket to KQ, we also associate our object pointer with it. But we can actually **store some more information** there - not just the pointer. In our example here, we set the value of `struct context.flag` field (which is `0` at first) as the lowest bit value along with our object pointer. It works because all structure objects that contain a pointer are aligned to at least 4 or 8 bytes by default. In other words, the lowest bit for any object pointer is always 0, and we can use it for our own purposes. * After we have received an event from KQ, we **clear the lowest bit** when converting the user data pointer to our object pointer. All event handlers are called as usual without any problem. ``` kevent(EV_ADD, 0x???????0) events[] = kevent() object = events[0].udata.bits[1..31] // object | events[0] // ---------+------------------- // {flag=0} | {udata=0x???????0} if 0 == 0 // TRUE object.handler() ``` * But if inside the event handling function we decided to close the socket, we **mark our object as unused** - in our case we set an internally stored safety flag to `1`. We don't free the memory associated with our object so that we can access this value later. ``` read_handler() { close(object.socket) object.flag = 1 } ``` * When we start the processing of the next (cached) event for the same socket, we **compare the lowest bit** from the associated data pointer with the flag stored within our object. In our case they don't match, which means that we don't want this event to be processed. Note that C doesn't allow logical bit operations on pointers, hence the somewhat ugly cast to integer type and back. ``` object = events[1].udata.bits[1..31] // object | events[1] // ---------+------------------- // {flag=1} | {udata=0x???????0} if 1 == 0 // FALSE ``` * After we have processed all cached events we may free the memory allocated for our objects marked as unused. Or we may decide not to free the memory for our objects at all - because the next iteration may need to create a new object and we would need to allocate memory again. Instead, we may **store all unused objects in a list** (or array) and free them only when our app is closing the whole KQ subsystem. * Next time we use the same object pointer (if we didn't free its memory), the flag is still set to `1` and so it is passed to KQ as the lowest bit of the user data pointer when we attach a new socket descriptor to KQ. ``` kevent(EV_ADD, 0x???????1) events[] = kevent() object = events[0].udata.bits[1..31] // object | events[0] // ---------+------------------- // {flag=1} | {udata=0x???????1} if 1 == 1 // TRUE object.handler() ``` * And again, when we have finished working with this object, we turn it over and set the flag to `0`. After that, the values from KQ (the old bit value `1`) and the flag value inside the object (now `0`) don't match, therefore the handling function won't be called which is exactly what we want. ``` read_handler() { close(object.socket) object.flag = 0 } object = events[1].udata.bits[1..31] // object | events[1] // ---------+------------------- // {flag=0} | {udata=0x???????1} if 0 == 1 // FALSE ``` Some people don't use the lowest bit approach to handle the problem with stale events. They just use a list where they put the unused objects until they can free them (after each iteration or by a timer signal). Imagine how this can slow down the processing when **every cached event starting at index 1 should be checked against some data in a container** - a search must be performed which wastes CPU cycles. I don't know what's the reasoning for doing so, but I really don't see how it's too hard to use the lowest bit trick and turn it over once in a while. So I advise using a list of unused objects only to save on countless memory allocations and deallocations and not for deciding whether an event is stale or not. #### User-triggered events with kqueue When we use an infinite timeout in KQ waiting function, it blocks forever until it can return an event. Similar to how it returns with `EINTR` after UNIX signal is processed, we can force it to return at any time by sending a user event to KQ. To do it we first register a `EVFILT_USER` event in KQ, then we can trigger this event via `NOTE_TRIGGER`. Here's an example. ``` /* Kernel Queue The Complete Guide: kqueue-user.c: User-triggered events */ #include #include #include #include #include int kq; struct context { void (\*handler)(struct context \*obj); }; struct context user\_event\_obj; void user\_event\_obj\_handler(struct context \*obj) { printf("Received user event via kqueue\n"); } // application calls this function whenever it wants to add a new event to KQ // which will execute user\_event\_obj\_handler() void trigger\_user\_event() { user\_event\_obj.handler = user\_event\_obj\_handler; struct kevent events[1]; EV\_SET(&events[0], 1234, EVFILT\_USER, 0, NOTE\_TRIGGER, 0, &user\_event\_obj); assert(0 == kevent(kq, events, 1, NULL, 0, NULL)); } void main() { // create kqueue object kq = kqueue(); assert(kq != -1); // register user event with any random ID // note that user data is NULL here struct kevent events[1]; EV\_SET(&events[0], 1234, EVFILT\_USER, EV\_ADD | EV\_ENABLE | EV\_CLEAR, 0, 0, NULL); assert(0 == kevent(kq, events, 1, NULL, 0, NULL)); trigger\_user\_event(); struct timespec \*timeout = NULL; // wait indefinitely int n = kevent(kq, NULL, 0, events, 1, timeout); assert(n > 0); struct context \*o = events[0].udata; if (events[0].filter == EVFILT\_USER) o->handler(o); // handle user event close(kq); } ``` To register a new user event in KQ we have to supply an arbitrary ID which we later will use to trigger it, I use `1234` just for example. Note also that contrary to when attaching socket descriptor, we don't set user data pointer at this point. ``` EV_SET(&events[0], 1234, EVFILT_USER, EV_ADD | EV_ENABLE | EV_CLEAR, 0, 0, NULL); ``` Then at some point we decide to trigger the event with `NOTE_TRIGGER`. And now we can pass an object pointer which the waiting function will return back to us after the event signals. ``` EV_SET(&events[0], 1234, EVFILT_USER, 0, NOTE_TRIGGER, 0, obj); ``` After this event is returned from KQ and gets processed, it won't signal again until we trigger it next time - that's because we set `EV_CLEAR` flag when registering the event. #### System timer events with kqueue Another facility that KQ offers us is system timers - we can order KQ to periodically send us a timer event. A timer is necessary when we want to close connections for the clients that are silent for too long, for example. In kqueue we register a timer with `EVFILT_TIMER` and process its events as usual. For example: ``` /* Kernel Queue The Complete Guide: kqueue-timer.c: System timer events */ #include #include #include #include #include int kq; struct context { void (\*handler)(struct context \*obj); }; void timer\_handler(struct context \*obj) { static int n; printf("Received timer event via kqueue: %d\n", n++); } void main() { kq = kqueue(); assert(kq != -1); struct context obj = {}; obj.handler = timer\_handler; // start system timer int period\_ms = 1000; struct kevent events[1]; EV\_SET(&events[0], 1234, EVFILT\_TIMER, EV\_ADD | EV\_ENABLE, 0, period\_ms, &obj); assert(0 == kevent(kq, events, 1, NULL, 0, NULL)); for (;;) { struct timespec \*timeout = NULL; // wait indefinitely int n = kevent(kq, NULL, 0, events, 1, timeout); assert(n > 0); struct context \*o = events[0].udata; if (events[0].filter == EVFILT\_TIMER) o->handler(o); // handle timer event } close(kq); } ``` Sometimes we don't need a periodic timer, but the timer which will signal us only once, i.e. a **one-shot timer**. It's simple with kqueue - we just use `EV_ONESHOT` flag: ``` EV_SET(&events[0], 1234, EVFILT_TIMER, EV_ADD | EV_ENABLE | EV_ONESHOT, 0, period_ms, obj); ``` Keep in mind that KQ timers are not designed so that you can use a million of them - you just need 1. Even if our software handles a million clients, we still need 1 system timer, because all we need is to just periodically wake up and process the oldest entries in our *timer queue* which we handle ourselves with our own code. Timer queue mechanism isn't a part of KQ, it isn't in scope of this article, but it's just a linked-list or rbtree container where the first item is the oldest. #### UNIX signals from kqueue Another convenient feature of KQ is handling UNIX signals. We register a UNIX signal handler with `EVFILT_SIGNAL` and pass the signal number we want to attach to. When processing an event, we get the signal number from `struct kevent.ident` field. Example: ``` /* Kernel Queue The Complete Guide: kqueue-signal.c: UNIX signal handler Usage: $ ./kqueue-signal $ killall -SIGUSR1 kqueue-signal */ #include #include #include #include #include #include int kq; struct context { void (\*handler)(int sig); }; void unix\_signal\_handler(int sig) { printf("Received UNIX signal via kqueue: %d\n", sig); } void main() { kq = kqueue(); assert(kq != -1); struct context obj = {}; obj.handler = unix\_signal\_handler; // block default signal handler int sig = SIGUSR1; sigset\_t mask; sigemptyset(&mask); sigaddset(&mask, sig); sigprocmask(SIG\_BLOCK, &mask, NULL); // register UNIX signal handler struct kevent events[1]; EV\_SET(&events[0], sig, EVFILT\_SIGNAL, EV\_ADD | EV\_ENABLE, 0, 0, &obj); assert(0 == kevent(kq, events, 1, NULL, 0, NULL)); struct timespec \*timeout = NULL; // wait indefinitely int n = kevent(kq, NULL, 0, events, 1, timeout); assert(n > 0); struct context \*o = events[0].udata; if (events[0].filter == EVFILT\_SIGNAL) { int sig = events[0].ident; obj.handler(sig); // handle UNIX signal } close(kq); } ``` Note that KQ will return the event only after the signal has been processed with its normal mechanism, i.e. the handlers registered with `sigaction()` - KQ can't completely replace this mechanism. But KQ makes it easier to handle signals such as `SIGCHLD`, when a child process signals its parent about its closure. #### Asynchronous file I/O with kqueue Trying to read or write data from/to files on disk is a little bit harder than performing I/O on sockets. One of the reasons behind this is because sockets don't have an offset to read at - we always read from one end, while with files we may issue several parallel operations at different offsets. And how can OS notify us about which particular operation has completed? That's why the kernel has to provide us with a new API for dealing with file AIO. And FreeBSD is the only OS that has a complete implementation of asynchronous file read/write operations. Sadly, it doesn't look anything like the rest of what we've talked about here so far. What we would have expected from kqueue is the mechanism which just signals us when some data is available to read or write from/to a file - exactly the same way we work with sockets. But no, what we have here instead is the mechanism of asynchronous file operations (only read/write operations are supported) which hold (or "lock") the user data buffer internally and don't signal at all unless the whole data chunk is transferred, depriving us from the flexibility we already got used to when working with sockets. *Now all this looks more like IOCP, which can't be a good sign.* But anyway, since I promised you to show everything I know about KQ, let's see how this mechanism works with files. * First, we enable the AIO subsystem by loading the appropriate kernel module: ``` % kldload aio ``` * The next step is to prepare an AIO object of type `struct aiocb` and call the appropriate function, that is `aio_read()` or `aio_write()`. * Then we immediately check for operation status with `aio_error()`, because it may have finished already before we even called KQ waiting function. * When we know that everything is fine and the operation is in progress, we wait for a signal from KQ as usual. * When we receive an event of type `EVFILT_AIO` from KQ we may read `struct kevent.ident` field to get `struct aiocb*` object pointer associated with the operation. This is how we can distinguish several parallel operations on the same file descriptor from each other. Here's the minimal example of how to read from a file asynchronously: ``` /* Kernel Queue The Complete Guide: kqueue-file.c: Asynchronous file reading Usage: $ echo 'Hello file AIO' >./kqueue-file.txt $ ./kqueue-file */ #include #include #include #include #include #include #include #include #include #include int kq; struct context { int fd; struct aiocb acb; int (\*handler)(struct context \*obj, struct aiocb \*acb); }; void file\_io\_result(const char \*via, int res) { printf("Read from file via %s: %d\n", via, res); } int file\_aio\_handler(struct context \*obj, struct aiocb \*acb) { int r = aio\_error(acb); if (r == EINPROGRESS) { return 0; // AIO in progress } else if (r == -1) { file\_io\_result("kqueue", -1); // AIO completed with error return -1; } r = aio\_return(acb); file\_io\_result("kqueue", r); // AIO completed successfully return 1; } void main() { // create KQ object kq = kqueue(); assert(kq != -1); // open file descriptor and prepare the associated object int fd = open("./kqueue-file.txt", O\_RDONLY, 0); assert(fd != -1); struct context obj = {}; obj.handler = file\_aio\_handler; // associate the AIO operation with KQ and user object pointer memset(&obj.acb, 0, sizeof(obj.acb)); obj.acb.aio\_sigevent.sigev\_notify\_kqueue = kq; obj.acb.aio\_sigevent.sigev\_notify = SIGEV\_KEVENT; obj.acb.aio\_sigevent.sigev\_notify\_kevent\_flags = EV\_CLEAR; obj.acb.aio\_sigevent.sigev\_value.sigval\_ptr = &obj void \*buf = malloc(4\*1024); // specify operation parameters obj.acb.aio\_fildes = fd; obj.acb.aio\_buf = buf; // destination buffer obj.acb.aio\_nbytes = 4\*1024; // max number of bytes to read obj.acb.aio\_offset = 0; // offset to begin reading at // begin file AIO operation obj.acb.aio\_lio\_opcode = LIO\_READ; if (0 != aio\_read(&obj.acb)) { if (errno == EAGAIN || errno == ENOSYS || errno == EOPNOTSUPP) { // no resources to complete this I/O operation // or AIO module isn't loaded // or the system can't perform AIO on this file } else { file\_io\_result("aio\_read", -1); return; // fatal error } // AIO doesn't work - perform synchronous reading at the specified offset int r = pread(fd, buf, obj.acb.aio\_nbytes, obj.acb.aio\_offset); file\_io\_result("pread", r); return; } // asynchronous file reading has started, but might be finished already if (0 != file\_aio\_handler(&obj, &obj.acb)) return; // asynchronous file reading is in progress, now wait for the signal from KQ struct kevent events[1]; struct timespec \*timeout = NULL; // wait indefinitely int n = kevent(kq, NULL, 0, events, 1, timeout); struct context \*o = events[0].udata; if (events[0].filter == EVFILT\_AIO) { struct aiocb \*acb = (void\*)events[0].ident; o->handler(o, acb); // handle file AIO event } free(buf); close(fd); close(kq); } ``` The main function here is `aio_read()`, which processes our request and starts the asynchronous operation. It returns `0` if the operation has started successfully. ``` struct aiocb acb = ...; // fill in `acb` object acb.aio_lio_opcode = LIO_READ; aio_read(&acb); // begin file AIO operation ``` However, if something is wrong, it returns with an error, and we must handle several cases here: ``` if (errno == EAGAIN || errno == ENOSYS || errno == EOPNOTSUPP) { // no resources to complete this I/O operation // or AIO module isn't loaded // or the system can't perform AIO on this file } else { // fatal error } ``` We can handle some types of errors by issuing a **synchronous file reading**: ``` // AIO doesn't work - perform synchronous reading at the specified offset int r = pread(fd, buf, size, off); ``` For **writing data to a file asynchronously** we use the same template, except the opcode and the function are different, while everything else is the same: ``` struct aiocb acb = ...; // fill in `acb` object acb.aio_lio_opcode = LIO_WRITE; aio_write(&acb); // begin file AIO operation ``` And of course we use a different function for the **synchronous file writing** in case file AIO doesn't work: ``` int r = pwrite(fd, buf, size, off); ``` > Though file AIO is good to have, it's still not enough for high-performance file servers, because such software needs not just file AIO in terms of reading/writing file data, but disk AIO in general. What for? In our example above we use asynchronous file reading only, but we know that the very first step in working with files in UNIX is opening a file descriptor. However, we just can't perform an asynchronous file open - it's not supported. And in the real life an `open()` syscall may take a whole second to complete on a busy machine - it may block our worker thread for a long time. In real life we also want to call `stat()` or `fstat()` on a file path or a file descriptor. And OS doesn't provide a way to call them asynchronously either, except calling them inside another thread. So even if file AIO can help sometimes, it's still somewhat lame and incomplete. And considering the fact that other OS don't have an appropriate file AIO implementation at all, it may be a better choice not to use any of those APIs at all. It may be better to use a thread pool with a file operations queue and dispatch operations to another thread. Inside a new thread the operations will be performed *synchronously*. And then it will signal the main thread when the operation is complete. > > ### Linux and epoll epoll API is very similar to kqueue for socket I/O notifications, though it's quite different for other purposes. Here we use `epoll_ctl()` to attach file descriptors to KQ and we use `epoll_wait()` to receive events from KQ. There are several more syscalls we're going to use for user events, timers and UNIX signals: `eventfd()`, `timerfd_create()`, `timerfd_settime()`, `signalfd()`. Overall, the functionality of `epoll` is the same as `kqueue` but sometimes with a slightly different approach. The key **differences of epoll and kqueue** are: * `kevent()` supports attaching many file descriptors in a single syscall, `epoll_ctl()` does not - we must call it once for each fd. `kevent()` even allows us to attach fd's AND wait for new events in a single syscall, `epoll_wait()` can't do that. * epoll may join 2 events (`EPOLLIN` and `EPOLLOUT`) into 1 event object in case both READ and WRITE events signal. This is contrary to kqueue which always returns 1 event object per 1 event (`EVFILT_READ` or `EVFILT_WRITE`). Be careful with epoll here, always check if it's alright to execute event handling functions, because otherwise you risk calling WRITE event handler after you have finalized the object in READ event handler. * epoll makes it somewhat harder to use additional KQ functionality such as UNIX signals, system timers or user events - see below. In kqueue, however, it looks all the same. What is different but also similar between epoll and kqueue: * We attach a socket to epoll using `EPOLLIN | EPOLLOUT` flags which is the same as registering 2 separate events `EVFILT_READ` and `EVFILT_WRITE` with kqueue. * `EPOLLET` flag in epoll is the same thing as `EV_CLEAR` flag in kqueue - it prevents epoll from signalling us about the same event more than once until we drain all data from the socket. And it's the same situation when writing to a streaming (e.g. TCP) socket - we must keep calling `write()` until it returns with `EAGAIN` error - only then we may expect epoll to signal us. #### Accepting socket connections with epoll Here's a minimal example for accepting a socket connection. ``` /* Kernel Queue The Complete Guide: epoll-accept.c: Accept socket connection Usage: $ ./epoll-accept $ curl 127.0.0.1:64000/ */ #include #include #include #include #include #include #include #include #include int kq; // the structure associated with a socket descriptor struct context { int sk; void (\*rhandler)(struct context \*object); }; void accept\_handler(struct context \*obj) { printf("Received socket READ event via epoll\n"); int csock = accept(obj->sk, NULL, 0); assert(csock != -1); close(csock); } void main() { // create KQ object kq = epoll\_create(1); assert(kq != -1); struct context obj = {}; obj.rhandler = accept\_handler; // create and prepare a socket obj.sk = socket(AF\_INET, SOCK\_STREAM | SOCK\_NONBLOCK, 0); assert(obj.sk != -1); int val = 1; setsockopt(obj.sk, SOL\_SOCKET, SO\_REUSEADDR, &val, 4); struct sockaddr\_in addr = {}; addr.sin\_family = AF\_INET; addr.sin\_port = ntohs(64000); assert(0 == bind(obj.sk, (struct sockaddr\*)&addr, sizeof(addr))); assert(0 == listen(obj.sk, 0)); // attach socket to KQ struct epoll\_event event; event.events = EPOLLIN | EPOLLOUT | EPOLLET; event.data.ptr = &obj assert(0 == epoll\_ctl(kq, EPOLL\_CTL\_ADD, obj.sk, &event)); // wait for incoming events from KQ struct epoll\_event events[1]; int timeout\_ms = -1; // wait indefinitely int n = epoll\_wait(kq, events, 1, timeout\_ms); assert(n > 0); // process the received event struct context \*o = events[0].data.ptr; if (events[0].events & (EPOLLIN | EPOLLERR)) o->rhandler(o); // handle read event close(obj.sk); close(kq); } ``` #### Creating and closing epoll object `epoll_create()` function returns new KQ object descriptor which we close as usual with `close()`. ``` kq = epoll_create(1); ... close(kq); ``` #### Attaching socket descriptor to epoll `EPOLLIN` flag means that we want the kernel to notify us when a READ event signals, and `EPOLLOUT` flag is the same for a WRITE event. `EPOLLET` prevents epoll from returning to us the same signal unnecessarily. We set our object pointer with `struct epoll_event.data.ptr` field. ``` struct epoll_event event; event.events = EPOLLIN | EPOLLOUT | EPOLLET; event.data.ptr = obj; epoll_ctl(kq, EPOLL_CTL_ADD, sk, &event); ``` #### Receiving events from epoll `epoll_wait()` function blocks until it has something to return to us, or until the timeout value expires. The function returns the number of signalled events which may be `0` only in case of timeout. It also returns with `EINTR` exactly like `kevent()` after a UNIX signal has been received, so we must always handle this case. ``` while (!quit) { struct epoll_event events[1]; int timeout_ms = -1; // wait indefinitely int n = epoll_wait(kq, events, 1, timeout_ms); if (n < 0 && errno == EINTR) continue; // epoll_wait() interrupts when UNIX signal is received } ``` #### Processing received events from epoll We get the events flags by reading `struct epoll_event.events` which we should always test for `EPOLLERR` too, because otherwise we can miss an event we're waiting for. To get the associated user data pointer, we read `struct epoll_event.data.ptr` value. I emphasize once again that you should be careful not to invalidate user object memory region inside READ event handler, or the program may crash inside the WRITE event handler which is executed next. To handle this situation you may just always set event handler function pointers to `NULL` when you don't expect them to signal. An alternative solution may be to clear `EPOLLOUT | EPOLLERR` flags from `struct epoll_event.events` field from inside READ event handler. ``` struct context *o = events[i].data.ptr; if ((events[i].events & (EPOLLIN | EPOLLERR)) && o->rhandler != NULL) o->rhandler(o); // handle read event if ((events[i].events & (EPOLLOUT | EPOLLERR)) && o->whandler != NULL) o->whandler(o); // handle write event ``` #### Establishing TCP connection with epoll As with kqueue, epoll also has a way to notify us about the status of TCP connection. But unlike kqueue which sets the error number for us inside `struct kevent` object, epoll doesn't do that (it can't do that). Instead, we get the error number associated with our socket via `getsockopt(..., SOL_SOCKET, SO_ERROR, ...)`. ``` int err; socklen_t len = 4; getsockopt(obj->sk, SOL_SOCKET, SO_ERROR, &err, &len); errno = err; ... // handle TCP connection result depending on `errno` value ``` #### User-triggered events with epoll There are slightly more things to do with epoll rather than with kqueue to handle user-triggered events: * First, we create a new file descriptor with `eventfd()` which we then attach to KQ. * We trigger a user event at any time by writing an 8 byte value to our eventfd descriptor. In our case this value is an object pointer. * After we receive an event from KQ, we read an 8 byte value from eventfd descriptor. We can convert this value to an object pointer. Remember that we need to keep reading data from eventfd descriptor until it returns with `EAGAIN` error, because we use `EPOLLET`. ``` /* Kernel Queue The Complete Guide: epoll-user.c: User-triggered events */ #include #include #include #include #include #include #include int kq; int efd; struct context { void (\*handler)(struct context \*obj); }; struct context eventfd\_obj; struct context user\_event\_obj; void user\_event\_obj\_handler(struct context \*obj) { printf("Received user event via epoll\n"); } // application calls this function whenever it wants to add a new event to KQ // which will execute user\_event\_obj\_handler() void trigger\_user\_event() { struct context \*obj = &user\_event\_obj; obj->handler = user\_event\_obj\_handler; unsigned long long val = (size\_t)obj; int r = write(efd, &val, 8); assert(r == 8); } // handle event from eventfd-descriptor void handle\_eventfd(struct context \*obj) { unsigned long long val; for (;;) { int r = read(efd, &val, 8); if (r < 0 && errno == EAGAIN) break; assert(r == 8); struct context \*o = (void\*)(size\_t)val; o->handler(o); } } void main() { // create kqueue object kq = epoll\_create(1); assert(kq != -1); struct context obj = {}; obj.handler = handle\_eventfd; // prepare eventfd-descriptor for user events efd = eventfd(0, EFD\_NONBLOCK); assert(efd != -1); // register eventfd in KQ struct epoll\_event event; event.events = EPOLLIN | EPOLLET; event.data.ptr = &obj assert(0 == epoll\_ctl(kq, EPOLL\_CTL\_ADD, efd, &event)); trigger\_user\_event(); struct epoll\_event events[1]; int timeout\_ms = -1; int n = epoll\_wait(kq, events, 1, timeout\_ms); assert(n > 0); struct context \*o = events[0].data.ptr; if (events[0].events & (EPOLLIN | EPOLLERR)) o->handler(o); // handle eventfd event close(efd); // close eventfd descriptor close(kq); } ``` #### System timer events with epoll To receive the notifications from system timer with epoll we must use a timerfd object - a special file descriptor we can attach to epoll. ``` /* Kernel Queue The Complete Guide: epoll-timer.c: System timer events */ #include #include #include #include #include #include int kq; int tfd; struct context { void (\*handler)(struct context \*obj); }; void timer\_handler(struct context \*obj) { static int n; printf("Received timerfd event via epoll: %d\n", n++); unsigned long long val; read(tfd, &val, 8); } void main() { // create kqueue object kq = epoll\_create(1); assert(kq != -1); struct context obj = {}; obj.handler = timer\_handler; // prepare timerfd-descriptor tfd = timerfd\_create(CLOCK\_MONOTONIC, 0); assert(tfd != -1); // register timerfd in KQ struct epoll\_event event; event.events = EPOLLIN | EPOLLET; event.data.ptr = &obj assert(0 == epoll\_ctl(kq, EPOLL\_CTL\_ADD, tfd, &event)); // start periodic timer struct itimerspec its; its.it\_value.tv\_sec = 1; its.it\_value.tv\_nsec = 0; its.it\_interval = its.it\_value; assert(0 == timerfd\_settime(tfd, 0, &its, NULL)); for (;;) { struct epoll\_event events[1]; int timeout\_ms = -1; int n = epoll\_wait(kq, events, 1, timeout\_ms); assert(n > 0); struct context \*o = events[0].data.ptr; if (events[0].events & (EPOLLIN | EPOLLERR)) o->handler(o); // handle timerfd event } close(tfd); // close timerfd descriptor close(kq); } ``` To create a timerfd object we call `timerfd_create()` with `CLOCK_MONOTONIC` parameter which means the timer isn't affected by system time/date changes. ``` tfd = timerfd_create(CLOCK_MONOTONIC, 0); ``` To start a periodic timer, we set `struct itimerspec.it_interval` field which defines the timer interval. ``` // start periodict timer struct itimerspec its; its.it_value.tv_sec = 1; its.it_value.tv_nsec = 0; its.it_interval = its.it_value; timerfd_settime(tfd, 0, &its, NULL); ``` After we have received the timer event we always need to read the data from timerfd descriptor, otherwise we won't get any more events from KQ because we use `EPOLLET` flag. ``` unsigned long long val; read(tfd, &val, 8); ``` To create a **one-shot timer**, we set `struct itimerspec.it_interval` fields to `0`: ``` // start one-shot timer struct itimerspec its; its.it_value.tv_sec = 1; its.it_value.tv_nsec = 0; its.it_interval.tv_sec = its.it_interval.tv_nsec = 0; timerfd_settime(tfd, 0, &its, NULL); ``` #### UNIX signals from epoll We can also receive UNIX signals with epoll. We must use a signalfd descriptor to be able to do that. To get the information about the UNIX signal we receive, we read some data from this signalfd object. ``` /* Kernel Queue The Complete Guide: epoll-signal.c: UNIX signal handler Usage: $ ./epoll-signal $ killall -SIGUSR1 epoll-signal */ #include #include #include #include #include #include int kq; int sfd; struct context { void (\*handler)(struct context \*obj); }; void unix\_signal\_handler(struct context \*obj) { struct signalfd\_siginfo si; int r = read(sfd, &si, sizeof(si)); assert(r == sizeof(si)); int sig = si.ssi\_signo; printf("Received UNIX signal via epoll: %d\n", sig); } void main() { // create kqueue object kq = epoll\_create(1); assert(kq != -1); struct context obj = {}; obj.handler = unix\_signal\_handler; // block default signal handler int sig = SIGUSR1; sigset\_t mask; sigemptyset(&mask); sigaddset(&mask, sig); sigprocmask(SIG\_BLOCK, &mask, NULL); // prepare signalfd-descriptor sfd = signalfd(-1, &mask, SFD\_NONBLOCK); assert(sfd != -1); // register signalfd in KQ struct epoll\_event event; event.events = EPOLLIN | EPOLLET; event.data.ptr = &obj assert(0 == epoll\_ctl(kq, EPOLL\_CTL\_ADD, sfd, &event)); struct epoll\_event events[1]; int timeout\_ms = -1; int n = epoll\_wait(kq, events, 1, timeout\_ms); assert(n > 0); struct context \*o = events[0].data.ptr; if (events[0].events & (EPOLLIN | EPOLLERR)) o->handler(o); // handle signalfd event close(sfd); // close signalfd descriptor close(kq); } ``` We create a signalfd object by calling `signalfd()`. ``` sfd = signalfd(-1, &mask, SFD_NONBLOCK); ``` As with timerfd object, we also need to read from signalfd descriptor otherwise we won't get more events from KQ. But another reason why we need this is we want to know which signal has fired. We do it by reading `struct signalfd_siginfo` data from signalfd object and then reading `struct signalfd_siginfo.ssi_signo` field that contains UNIX signal number. ``` struct signalfd_siginfo si; read(sfd, &si, sizeof(si)); int sig = si.ssi_signo; ``` #### Asynchronous file I/O with epoll It's even harder to work with files asynchronously when using epoll compared to the file AIO API we used earlier with kqueue. First of all, there's the requirement to use `O_DIRECT` flag when opening a file descriptor if we want it to support asynchronous operations. This flag alone creates 2 new restrictions for us: we must implement our own data caching mechanism and we must use buffers aligned to disk block size. We solve the first problem by not solving it - in our example we don't implement any data caching here. However, in the real life our performance may be very poor without it. Linux kernel has a very good disk data caching mechanism and it's a shame when we can't use it. In general, this means that there are not so many use-cases for using file AIO on Linux. The second restriction which is the requirement of using aligned buffers is just inconvenient, but at least we can handle it. We can't use a normal buffer pointer allocated by `malloc()` - we must use a pointer aligned to disk block size (in our example we use `posix_memalign()` function which returns an aligned pointer). Furthermore, we can't read or write an arbitrary amount of data, say, 1000 bytes, neither we can use an arbitrary file offset - we must also use an aligned number. Another inconvenient thing is that GLIBC still doesn't have the wrappers for the syscalls we need to use here. We solve this problem by writing our own wrappers. It isn't hard, but just inconvenient. *Does this mean that only some crazy people use this functionality on Linux?* The file AIO API on Linux sometimes looks similar to what we were using on FreeBSD (at least, submitting a new operation looks similar). However, the signal delivery mechanism is completely different. It uses eventfd descriptor we are already familiar with to notify us about that AIO subsystem has signalled. We then receive events from AIO and process the results of our operations. Though there's nothing here too hard to implement, the whole code just looks a little bit overcomplex and ugly. There are too many things we must control here, so the use of convenient wrappers is absolutely required in real life code. OK, let's see the example already, or else I won't stop complaining how bad all this is. ``` /* Kernel Queue The Complete Guide: epoll-file.c: Asynchronous file reading Usage: $ echo 'Hello file AIO' >./epoll-file.txt $ ./epoll-file */ #define _GNU_SOURCE #include #include #include #include #include #include #include #include #include #include #include int kq; int efd; aio\_context\_t aioctx; struct context { struct iocb acb; int (\*handler)(struct context \*obj); }; void file\_io\_result(const char \*via, int res) { printf("Read from file via %s: %d\n", via, res); } // GLIBC doesn't have wrappers for these syscalls, so we make our own wrappers static inline int io\_setup(unsigned nr\_events, aio\_context\_t \*ctx\_idp) { return syscall(SYS\_io\_setup, nr\_events, ctx\_idp); } static inline int io\_destroy(aio\_context\_t ctx\_id) { return syscall(SYS\_io\_destroy, ctx\_id); } static inline int io\_submit(aio\_context\_t ctx\_id, long nr, struct iocb \*\*iocbpp) { return syscall(SYS\_io\_submit, ctx\_id, nr, iocbpp); } static inline int io\_getevents(aio\_context\_t ctx\_id, long min\_nr, long nr, struct io\_event \*events, struct timespec \*timeout) { return syscall(SYS\_io\_getevents, ctx\_id, min\_nr, nr, events, timeout); } int file\_aio\_handler(struct context \*obj) { unsigned long long n; for (;;) { int r = read(efd, &n, 8); if (r < 0 && errno == EAGAIN) break; assert(r == 8); // we've got `n` unprocessed events from file AIO for (;;) { struct io\_event events[64]; struct timespec timeout = {}; r = io\_getevents(aioctx, 1, 64, events, &timeout); if (r < 0 && errno == EINTR) { continue; // interrupted due to UNIX signal } else if (r == 0) { break; // no more events } assert(r > 0); // process result value for each event for (int i = 0; i != r; i++) { struct context \*obj = (void\*)(size\_t)events[i].data; int result = events[i].res; if (result < 0) { errno = -result; result = -1; } file\_io\_result("epoll", result); } } } return 1; } void main() { // create KQ object kq = epoll\_create(1); assert(kq != -1); // prepare the associated object struct context obj = {}; obj.handler = file\_aio\_handler; // open file descriptor, O\_DIRECT is mandatory int fd = open("./epoll-file.txt", O\_DIRECT | O\_RDONLY, 0); assert(fd != -1); // initialize file AIO subsystem int aio\_workers = 64; assert(0 == io\_setup(aio\_workers, &aioctx)); // open eventfd descriptor which will pass signals from file AIO efd = eventfd(0, EFD\_NONBLOCK); assert(efd != -1); // attach eventfd to KQ struct epoll\_event event; event.events = EPOLLIN | EPOLLET; event.data.ptr = &obj assert(0 == epoll\_ctl(kq, EPOLL\_CTL\_ADD, efd, &event)); // associate the AIO operation with KQ and user object pointer memset(&obj.acb, 0, sizeof(obj.acb)); obj.acb.aio\_data = (size\_t)&obj obj.acb.aio\_flags = IOCB\_FLAG\_RESFD; obj.acb.aio\_resfd = efd; void \*buf; assert(0 == posix\_memalign(&buf, 512, 4\*1024)); // allocate 4k buffer aligned by 512 // specify operation parameters obj.acb.aio\_fildes = fd; obj.acb.aio\_buf = (size\_t)buf; // destination buffer obj.acb.aio\_nbytes = 4\*1024; // max number of bytes to read obj.acb.aio\_offset = 0; // offset to begin reading at // begin file AIO operation obj.acb.aio\_lio\_opcode = IOCB\_CMD\_PREAD; struct iocb \*cb = &obj.acb if (1 != io\_submit(aioctx, 1, &cb)) { if (errno == EAGAIN || errno == ENOSYS) { // no resources to complete this I/O operation // or the system can't perform AIO on this file } else { file\_io\_result("io\_submit", -1); return; // fatal error } // AIO doesn't work - perform synchronous reading at the specified offset int r = pread(fd, buf, obj.acb.aio\_nbytes, obj.acb.aio\_offset); file\_io\_result("pread", r); return; } // asynchronous file reading is in progress, now wait for the signal from KQ struct epoll\_event events[1]; int timeout\_ms = -1; // wait indefinitely int n = epoll\_wait(kq, events, 1, timeout\_ms); struct context \*o = events[0].data.ptr; if (events[0].events & (EPOLLIN | EPOLLERR)) { o->handler(o); // handle file AIO event via eventfd } free(buf); close(fd); io\_destroy(aioctx); close(kq); } ``` First, we initialize AIO subsystem by calling `io_setup()` which returns a pointer to AIO context. We specify how many I/O workers the system should allocate for us. I don't have any good advice for you on how many workers you should allocate - the official documentation is very short - so I just use `64` for this example. ``` aio_context_t aioctx; int aio_workers = 64; io_setup(aio_workers, &aioctx); ``` We need an object of type `struct iocb` which will define the operation we want to perform. We start filling it by specifiyng how it should signal us about its completion. Here we order it to notify us via eventfd descriptor. ``` struct iocb acb = {}; acb.aio_data = (size_t)obj; // user object pointer acb.aio_flags = IOCB_FLAG_RESFD; acb.aio_resfd = efd; // eventfd descriptor ``` Then we set the details on our operation: which file descriptor to use, where to put the data and so on. ``` acb.aio_fildes = fd; acb.aio_buf = (size_t)buf; // destination buffer acb.aio_nbytes = 4*1024; // max number of bytes to read acb.aio_offset = 0; // offset to begin reading at ``` Finally, we call the `io_submit()` function which will begin reading from a file and signal us via eventfd on completion. ``` acb.aio_lio_opcode = IOCB_CMD_PREAD; struct iocb *cb = &acb io_submit(aioctx, 1, &cb); ``` Just like on FreeBSD, we also must check for error codes here on Linux and be ready to perform our I/O operation synchronously if we need to. ``` if (1 != io_submit(aioctx, 1, &cb)) { if (errno == EAGAIN || errno == ENOSYS) { // no resources to complete this I/O operation // or the system can't perform AIO on this file } else { file_io_result(-1); return; // fatal error } // AIO doesn't work - perform synchronous reading at the specified offset int r = pread(fd, buf, size, offset); file_io_result(r); return; } ``` When we receive a signal from epoll for our eventfd we've associated the file AIO operation with, we ask AIO about which operations are complete using `io_getevents()` function. It returns the number of completed operations and fills our array of `struct io_event` from where we can determine the results of each operation. Timeout value defines how long the function can block, but we don't want it to block at all, obviously, so we use a zero timeout value. ``` struct io_event events[64]; struct timespec timeout = {}; n = io_getevents(aioctx, 1, 64, events, &timeout); ``` And lastly, we process each event, get the user object associated with it by reading `struct io_event.data` field and the result of operation from `struct io_event.res` field. The result is the number of bytes read or written, but in case an error has occurred, this value is negative and contains the error code. ``` struct context *obj = (void*)(size_t)events[i].data; int result = events[i].res; if (result < 0) { errno = -result; result = -1; } ``` > Once again I'm gonna say that this whole system has a poor design and it may be better to use a thread-pool mechanism which performs file operations synchronously. A good file AIO system must have more configuration options such as how many workers should be used for each physical disk. And it shouldn't have restrictions such as buffer alignment. And it shouldn't force the user to disable in-kernel caching for a file descriptor. And it should support more file functions including `open()` and `fstat()`. But I think the main point is that the code for using file AIO should look similar to what we have with KQ and network sockets. That is, we want an API which allows us to perform a simple operation such as reading a 64k byte chunk from a file, and *if it can't complete immediately*, it should just return with `EINPROGRESS`. This function should also start a new background operation internally which will read at least 1 block of data from our file (GLIBC could handle that). Then we should receive a signal from KQ which tells us that now we may try again. And again we call *the same code* but now it returns, say, 4k bytes to us - and even so it isn't 64k we asked for, it is still fine, because we can start processing this data immediately. This is a very straightforward approach that works very well with sockets (except the poorly designed `connect()+EINPROGRESS+getsockopt()` logic). I just wish the file functions could work this way too. But I guess that since it isn't still implemented, no one needs this functionality, that's all. > > ### Windows and I/O Completion Ports So are you ready for some more programming? I have to warn you that IOCP may be a little bit harder to use and understand. But even if you don't plan to use IOCP on Windows in the near future, I recommend you to at least walk through all these code samples just to learn and remember **how not to design a KQ API**. A bad example is still an example. I'm also very surprised to see that some developers even try to mimic the behaviour of IOCP in their own KQ/AIO libraries. They think that the API design of pending asynchronous operations that forces the user to have long living locked context data and buffer memory regions is better than the mechanism of simple and plain event signalling? Maybe for someone, but not for me. To prove my point, just see how the code for kqueue looks comparing to the same code for IOCP and judge for yourselves. But first, let's start with a minimal example which surprisingly looks quite clear, because we use pipes and not network sockets. #### Accepting connections to a named pipe with IOCP ``` /* Kernel Queue The Complete Guide: iocp-pipe.c: Accept connections to a named pipe */ #include #include #include HANDLE kq; struct context { HANDLE p; void (\*handler)(struct context \*obj); OVERLAPPED accept\_ctx; }; void pipe\_handler(struct context \*obj) { printf("Accepted pipe connection via IOCP\n"); } void main() { // create KQ object kq = CreateIoCompletionPort(INVALID\_HANDLE\_VALUE, NULL, 0, 0); assert(kq != NULL); struct context obj = {}; obj.handler = pipe\_handler; // create a named pipe obj.p = CreateNamedPipeW(L"\\\\.\\pipe\\iocp-pipe" , PIPE\_ACCESS\_DUPLEX | FILE\_FLAG\_FIRST\_PIPE\_INSTANCE | FILE\_FLAG\_OVERLAPPED , PIPE\_TYPE\_BYTE | PIPE\_READMODE\_BYTE | PIPE\_WAIT , PIPE\_UNLIMITED\_INSTANCES, 512, 512, 0, NULL); assert(obj.p != INVALID\_HANDLE\_VALUE); // attach pipe to KQ assert(NULL != CreateIoCompletionPort(obj.p, kq, (ULONG\_PTR)&obj, 0)); memset(&obj.accept\_ctx, 0, sizeof(obj.accept\_ctx)); BOOL ok = ConnectNamedPipe(obj.p, &obj.accept\_ctx); assert(ok || GetLastError() == ERROR\_IO\_PENDING); // wait for incoming events from KQ and process them for (;;) { OVERLAPPED\_ENTRY events[1]; ULONG n = 0; int timeout\_ms = -1; // wait indefinitely BOOL ok = GetQueuedCompletionStatusEx(kq, events, 1, &n, timeout\_ms, 0); assert(ok); // now process each signalled event for (int i = 0; i != (int)n; i++) { struct context \*o = (void\*)events[i].lpCompletionKey; o->handler(o); // handle event } } DisconnectNamedPipe(obj.p); // close accepted pipe CloseHandle(obj.p); // close listening pipe CloseHandle(kq); } ``` Note that some functions that return `HANDLE` type value on Windows return `NULL` on error while others return `INVALID_HANDLE_VALUE`. It's a typical design flaw from Microsoft. #### Creating and closing IOCP object To create a new KQ object we call `CreateIoCompletionPort()` function and we pass `INVALID_HANDLE_VALUE` as the first parameter and `NULL` as the second, which means that we want to create a new KQ object and not use the already existing object. Remember that it returns `NULL` on error and not `INVALID_HANDLE_VALUE`. We close this object with `CloseHandle()` as usual. ``` HANDLE kq = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0); ... CloseHandle(kq); ``` #### Attaching file descriptor to IOCP To attach a file or socket descriptor to KQ we call the same function `CreateIoCompletionPort()` and pass file descriptor, KQ object and a user object pointer. Remember that the function name is deceiving in this case: it doesn't create a new "completion port" but only registers the file descriptor with it. And we must not close the file descriptor it returns - we only check if it's `NULL`, which means error. When registering a socket descriptor rather than a file, an explicit cast to `HANDLE` is required, because `SOCKET != HANDLE`, even though they are essentially of the same pointer type and can be safely cast to `void*`. Also, a cast to `ULONG_PTR` is required when passing a user object pointer, because `ULONG_PTR != void*`. ``` CreateIoCompletionPort(fd, kq, (ULONG_PTR)obj, 0); // attach file to KQ CreateIoCompletionPort((HANDLE)sk, kq, (ULONG_PTR)obj, 0); // attach socket to KQ ``` #### Receiving events from IOCP The new function for waiting and receiving events from IOCP is `GetQueuedCompletionStatusEx()` which is available since Windows 7. Older Windows versions don't have this function, so we must use `GetQueuedCompletionStatus()` there. I don't think it will benefit this article to resurrect old Windows, so we don't talk about old functions here. Thankfully, `GetQueuedCompletionStatusEx()` works exactly the same as in kqueue or epoll - we pass KQ object, array of events and timeout value for how long the function may block. It returns 1 on success and sets the number of signalled events. ``` OVERLAPPED_ENTRY events[1]; ULONG n = 0; int timeout_ms = -1; // wait indefinitely BOOL ok = GetQueuedCompletionStatusEx(kq, events, 1, &n, timeout_ms, 0); ``` #### Processing received events from IOCP Now for each received event we read our object pointer from `OVERLAPPED_ENTRY.lpCompletionKey` field. Then we determine which event has signalled by reading `OVERLAPPED_ENTRY.lpOverlapped` field and comparing it with the appropriate `OVERLAPPED` object we use for our read and write operations. ``` struct context *o = events[i].lpCompletionKey; if (events[i].lpOverlapped == &o->read_context) // handle read event else if (events[i].lpOverlapped == &o->write_context) // handle write event ``` > I could never understand why the context objects for active I/O operations are called overlapped objects/events in Windows. And I still can't comprehend this idea - what overlaps with what here exactly? > > #### User-triggered events with IOCP Let's see how we can post a user event to KQ. ``` /* Kernel Queue The Complete Guide: iocp-user.c: User-triggered events */ #include #include #include HANDLE kq; struct context { void (\*handler)(struct context \*obj); }; void user\_event\_handler(struct context \*obj) { printf("Received user event via IOCP\n"); } void main() { // create KQ object kq = CreateIoCompletionPort(INVALID\_HANDLE\_VALUE, NULL, 0, 0); assert(kq != NULL); struct context obj = {}; obj.handler = user\_event\_handler; assert(0 != PostQueuedCompletionStatus(kq, 0, (ULONG\_PTR)&obj, NULL)); // wait for incoming events from KQ and process them OVERLAPPED\_ENTRY events[1]; ULONG n = 0; int timeout\_ms = -1; // wait indefinitely BOOL ok = GetQueuedCompletionStatusEx(kq, events, 1, &n, timeout\_ms, 0); assert(ok); assert(n == 1); struct context \*o = (void\*)events[0].lpCompletionKey; o->handler(o); // handle the event CloseHandle(kq); } ``` There's no need to register or prepare a user event as in kqueue or epoll. We just trigger the event at any time by calling `PostQueuedCompletionStatus()` and we pass any user object pointer to it. ``` PostQueuedCompletionStatus(kq, 0, (ULONG_PTR)obj, NULL); ``` #### Establishing TCP connection with IOCP Now that we start talking about sockets in Windows, you can finally see the whole picture of how difficult it is. There are many things that seem unnecessary and overcomplicated, and the code looks ugly and bloated. Here's the code for our HTTP/1 client. ``` /* Kernel Queue The Complete Guide: iocp-connect.c: HTTP/1 client Link with -lws2_32 */ #include #include #include #include #include HANDLE kq; int quit; LPFN\_CONNECTEX KQConnectEx; // the structure associated with a socket descriptor struct context { SOCKET sk; void (\*rhandler)(struct context \*obj); void (\*whandler)(struct context \*obj); OVERLAPPED read\_ctx; OVERLAPPED write\_ctx; char sendbuf[1]; int data\_offset; }; // some forward declarations void obj\_write(struct context \*obj); void obj\_read(struct context \*obj); void obj\_prepare(struct context \*obj) { // create and prepare socket obj->sk = socket(AF\_INET, SOCK\_STREAM, 0); assert(obj->sk != INVALID\_SOCKET); // make socket as non-blocking int nonblock = 1; ioctlsocket(obj->sk, FIONBIO, (unsigned long\*)&nonblock); int val = 1; assert(0 == setsockopt(obj->sk, 0, TCP\_NODELAY, (char\*)&val, sizeof(int))); // attach socket to KQ assert(NULL != CreateIoCompletionPort((HANDLE)obj->sk, kq, (ULONG\_PTR)obj, 0)); // get extended socket function pointers void \*func = NULL; DWORD res; GUID guid = WSAID\_CONNECTEX; WSAIoctl(obj->sk, SIO\_GET\_EXTENSION\_FUNCTION\_POINTER, (void\*)&guid, sizeof(GUID), &func, sizeof(void\*), &res, 0, 0); KQConnectEx = func; assert(KQConnectEx != NULL); } void obj\_connect(struct context \*obj) { if (obj->whandler == NULL) { struct sockaddr\_in baddr = {}; baddr.sin\_family = AF\_INET; char ip4[] = {127,0,0,1}; \*(int\*)&baddr.sin\_addr = \*(int\*)ip4; assert(0 == bind(obj->sk, (struct sockaddr\*)&baddr, sizeof(struct sockaddr\_in))); // begin asynchronous connection struct sockaddr\_in addr = {}; addr.sin\_family = AF\_INET; addr.sin\_port = ntohs(64000); \*(int\*)&addr.sin\_addr = \*(int\*)ip4; BOOL ok = KQConnectEx(obj->sk, (struct sockaddr\*)&addr, sizeof(struct sockaddr\_in), NULL, 0, NULL, &obj->write\_ctx); assert(ok || GetLastError() == ERROR\_IO\_PENDING); obj->whandler = obj\_connect; return; } else { DWORD res; BOOL ok = GetOverlappedResult(NULL, &obj->write\_ctx, &res, 0); assert(ok); } printf("Connected\n"); obj\_write(obj); } void obj\_write(struct context \*obj) { const char data[] = "GET / HTTP/1.1\r\nHost: hostname\r\nConnection: close\r\n\r\n"; int r; if (obj->whandler == NULL) { r = send(obj->sk, data + obj->data\_offset, sizeof(data)-1 - obj->data\_offset, 0); if (r > 0) { // sent some data } else if (r < 0 && GetLastError() == WSAEWOULDBLOCK) { // the socket's write buffer is full memset(&obj->write\_ctx, 0, sizeof(obj->write\_ctx)); obj->sendbuf[0] = data[obj->data\_offset]; DWORD wr; BOOL ok = WriteFile((HANDLE)obj->sk, obj->sendbuf, 1, ≀, &obj->write\_ctx); assert(ok || GetLastError() == ERROR\_IO\_PENDING); obj->whandler = obj\_write; return; } else { assert(0); // fatal error } } else { DWORD res; BOOL ok = GetOverlappedResult(NULL, &obj->write\_ctx, &res, 0); assert(ok); r = res; obj->whandler = NULL; } // sent some data obj->data\_offset += r; if (obj->data\_offset != sizeof(data)-1) { // we need to send the complete request obj\_write(obj); return; } printf("Sent HTTP request. Receiving HTTP response...\n"); obj\_read(obj); } void obj\_read(struct context \*obj) { char data[64\*1024]; if (obj->rhandler == NULL) { int r = recv(obj->sk, data, sizeof(data), 0); if (r > 0) { // received some data printf("%.\*s", r, data); obj\_read(obj); return; } else if (r == 0) { // server has finished sending data } else if (r < 0 && GetLastError() == WSAEWOULDBLOCK) { // the socket's read buffer is empty memset(&obj->read\_ctx, 0, sizeof(obj->read\_ctx)); DWORD rd; BOOL ok = ReadFile((HANDLE)obj->sk, NULL, 0, &rd, &obj->read\_ctx); assert(ok || GetLastError() == ERROR\_IO\_PENDING); obj->rhandler = obj\_read; return; } else { assert(0); // fatal error } } else { DWORD res; BOOL ok = GetOverlappedResult(NULL, &obj->read\_ctx, &res, 0); assert(ok); obj->rhandler = NULL; obj\_read(obj); return; } quit = 1; } void main() { // initialize sockets WSADATA wsa; WSAStartup(MAKEWORD(2, 2), &wsa); // create KQ object kq = CreateIoCompletionPort(INVALID\_HANDLE\_VALUE, NULL, 0, 0); assert(kq != NULL); struct context obj = {}; obj\_prepare(&obj); obj\_connect(&obj); // wait for incoming events from KQ and process them while (!quit) { OVERLAPPED\_ENTRY events[1]; ULONG n = 0; int timeout\_ms = -1; // wait indefinitely BOOL ok = GetQueuedCompletionStatusEx(kq, events, 1, &n, timeout\_ms, 0); assert(ok); assert(n == 1); // now process each signalled event for (int i = 0; i != n; i++) { struct context \*o = (void\*)events[i].lpCompletionKey; if (events[i].lpOverlapped == &o->read\_ctx) o->rhandler(o); // handle read event else if (events[i].lpOverlapped == &o->write\_ctx) o->whandler(o); // handle connect/write event } } closesocket(obj.sk); CloseHandle(kq); } ``` When we're dealing with sockets on Windows, the first thing we need to do is initialize socket subsystem. We do it by calling `WSAStartup()` function as following: ``` WSADATA wsa; WSAStartup(MAKEWORD(2, 2), &wsa); ``` There are several Windows-specific socket functions that can be used for KQ, but they are not exported by any `.dll` library, so we must get their pointers at runtime using this method: ``` void *func = NULL; DWORD b; GUID guid = WSAID_CONNECTEX; WSAIoctl(sk, SIO_GET_EXTENSION_FUNCTION_POINTER, (void*)&guid, sizeof(GUID), &func, sizeof(void*), &b, 0, 0); LPFN_CONNECTEX KQConnectEx = func; ``` Here, `WSAID_CONNECTEX` is a predefined GUID value (array of bytes, to be specific). We pass it to `WSAIoctl()` function along with the valid socket descriptor to get the real function pointer, in our case `ConnectEx()` - the function that asynchronously initiates a new TCP connection. In order for `ConnectEx()` to work, we must first bind our socket to a local address: ``` struct sockaddr_in addr = {}; addr.sin_family = AF_INET; char ip4[] = {127,0,0,1}; *(int*)&addr.sin_addr = *(int*)ip4; bind(obj->sk, (struct sockaddr*)&addr, sizeof(struct sockaddr_in)); ``` In this example we bind to 127.0.0.1 because we initiate connection to the loopback interface. And then we can call the function and pass to it remote address and the `OVERLAPPED` object which of course must stay valid until the operation completes. ``` addr = ...; KQConnectEx(sk, (struct sockaddr*)&addr, sizeof(struct sockaddr_in), NULL, 0, NULL, &obj->write_ctx); ``` When IOCP signals about the completion of operation, we get the result with `GetOverlappedResult()`. Normally it sets the number of transferred bytes upon return, but in our case the number will be 0. ``` DWORD res; BOOL ok = GetOverlappedResult(NULL, &obj->write_ctx, &res, 0); ``` #### Writing data to a TCP socket with IOCP After the connection is established, we send the request data to server. And this block of code looks worse than with kqueue or epoll where we just try to read or write some data and return when the functions can't fulfil our request. It's not that easy with IOCP, because here we must initiate an ongoing I/O operation to make IOCP signal us when the state of our socket changes. These are the steps of the write-data algorithm: 1. The first thing to do is to check whether we already have a result from the previously initiated WRITE operation - we do it simply by checking the WRITE event handling function `whandler`. 2. On the first entry the function pointer is unset, so we enter the first branch and try to send some data using common `send()` function. Unlike on UNIX it doesn't return with `EAGAIN` error code if it can't complete the request immediately, but on Windows it returns with `WSAEWOULDBLOCK`. 3. Here's where the things get more interesting. Now we need to emulate the algorithm we have on UNIX to make IOCP signal us when the kernel is ready to accept some more data from us for this socket, but we can't do it exactly the UNIX-way. The solution is that we start an asynchronous WRITE operation which will send just 1 byte for us. It also means that the next time we are back in our function, `send()` will be able to copy some more data from us. Why do we send just 1 byte via asynchronous operation and not the whole data we have for sending? Because the IOCP won't signal us at all until the whole data is sent. If the request is quite large, it's more likely that we'll hit our own timer signal which will kill the connection (we would think that it's stalled). That's why we send only 1 byte this way - it's much more flexible and it effectively emulates UNIX behaviour (which is canonical asynchronous I/O via KQ in my opinion). However, if you think you can benefit from sending larger chunk - go ahead and do it. Anyway, to send some data asynchronously we call `WriteFile()` and pass to it the data to send along with the `OVERLAPPED` object. Needless to say that the data buffer associated with the operation must stay valid until its completion. 4. Another interesting moment about asynchronous I/O with IOCP is that it seems like it always tries to deceive me. In our case, `WriteFile()` function may return `1` or it may return `0` with `ERROR_IO_PENDING` error, but in fact it's all the same to me. In the first case it says it has completed immediately, while in the second case it says it can't complete immediately. But in both cases IOCP will fire a signal anyway. I don't like the idea of increasing the complexity of my code while trying to support both cases correctly, therefore I just support 1 case - start an asynchronous operation then wait for its completion. Even if it's completed already - I still wait for the explicit signal. It's likely that you can adapt your own code to support both cases and save some context-switches and latency - I encourage you to try. 5. Now, the final step is handling the result from the previously initiated operation. We enter the `else` branch in this case and call `GetOverlappedResult()` with the same `OVERLAPPED` object. It returns the result of the operation and sets the number of bytes sent which is always 1 in our case. ``` if (obj->whandler == NULL) { r = send(obj->sk, data + obj->data_offset, sizeof(data)-1 - obj->data_offset, 0); if (r > 0) { // sent some data } else if (r < 0 && GetLastError() == WSAEWOULDBLOCK) { // the socket's write buffer is full memset(&obj->write_ctx, 0, sizeof(obj->write_ctx)); obj->sendbuf[0] = data[obj->data_offset]; DWORD wr; BOOL ok = WriteFile((HANDLE)obj->sk, obj->sendbuf, 1, ≀, &obj->write_ctx); assert(ok || GetLastError() == ERROR_IO_PENDING); obj->whandler = obj_write; return; } else { assert(0); // fatal error } } else { DWORD res; BOOL ok = GetOverlappedResult(NULL, &obj->write_ctx, &res, 0); assert(ok); r = res; obj->whandler = NULL; } ``` #### Reading data from a TCP socket with IOCP Reading data is very similar to writing the data - the process I described above. However, unlike what we did earlier with sending 1 byte of data to emulate UNIX behaviour, here we may achieve the exact UNIX behaviour by initiating an operation which reads 0 bytes. When we do so, IOCP will signal us at the moment the socket buffer becomes non-empty, and we can then read some data from it with `recv()`. I like this behaviour from IOCP very much - I wish everything in IOCP would work this way. ``` if (obj->rhandler == NULL) { int r = recv(obj->sk, data, sizeof(data), 0); if (r > 0) { // received some data printf("%.*s", r, data); obj_read(obj); return; } else if (r == 0) { // server has finished sending data } else if (r < 0 && GetLastError() == WSAEWOULDBLOCK) { // the socket's read buffer is empty memset(&obj->read_ctx, 0, sizeof(obj->read_ctx)); DWORD rd; BOOL ok = ReadFile((HANDLE)obj->sk, NULL, 0, &rd, &obj->read_ctx); assert(ok || GetLastError() == ERROR_IO_PENDING); obj->rhandler = obj_read; return; } else { assert(0); // fatal error } } else { DWORD res; BOOL ok = GetOverlappedResult(NULL, &obj->read_ctx, &res, 0); assert(ok); obj->rhandler = NULL; obj_read(obj); return; } ``` Note that I call our `obj_read()` function again after receiving some data or after processing the event - I just think it looks clearer this way than a loop, although I don't recommend doing so in real life code, because there's a small possibility to crash the app with stack memory overuse. #### Reading and writing data from/to a UDP socket with IOCP I have to explain the difference between reading data from a TCP and UDP sockets with IOCP. Although we used a beautiful way to get the signal from IOCP while using empty read buffer with `ReadFile()`, unfortunately it works only for TCP sockets. For UDP sockets we must provide the correct buffer with the maximum packet size, otherwise the message data will be cut (same as in UNIX, by the way). This buffer must stay valid until the operation completes. Then, after each asynchronous `ReadFile()` operation completes, I'm sure it's worth calling `recv()` in succession until it fails with `WSAEWOULDBLOCK`. ``` char buffer[64*1024]; ReadFile((HANDLE)udp_socket, buffer, sizeof(buffer), &rd, &obj->read_ctx); ``` It's slightly different situation with writing data to UDP sockets. We must provide the whole buffer with UDP message to `send()` and we never need to issue asynchronous operations with `WriteFile()`. ``` char data[] = ...; send(udp_socket, data, size, 0); ``` Someone once told me that he tried to force `WriteFile()` to return with `ERROR_IO_PENDING` with calling it relentlessly in a tight loop but he couldn't do it - it always succeeded. That's because sending data to a UDP socket just works this way - the kernel either sends the whole packet or the packet just gets dropped. After all, it's the user code that is responsible for UDP packet delivery - not the system. #### I/O Cancellation with IOCP Now let me explain why this approach of IOCP with its `ReadFile/WriteFile` for socket I/O is worse than the UNIX approach with `recv/send` and KQ events. On UNIX, when the kernel can't complete my I/O request immediately, the functions just return with `EAGAIN` error and do nothing else. And then I must wait for a signal from KQ which means that now the same functions will give me some result. During the time I wait for a signal all kinds of stuff is happening in parallel, such as timer events, user interaction, signals from other processes, hardware errors, input data corruptions - all this stuff can easily change the whole picture for my app. And I want my code to be flexible in order to easily adapt to any changes. The most basic example is the timer event. Imagine that while we're waiting for a specific socket event from KQ on UNIX, the timer has expired for this connection and I must now close the socket and destroy all data associated with this connection (i.e. destroy its context). It's very easy to do so with epoll or kqueue because I just go ahead and destroy everything immediately except the small portion which prevents from the stale cached events being handled by mistake. With IOCP, however, the `OVERLAPPED` object and the data associated with the ongoing asynchronous operation must both stay valid until I receive the notifications. And it's just very annoying because why would I want to receive unnecessary notifications from a thousand contexts when I have just initiated the closure of their associated sockets by myself? How does the notion of `receiving an event from a closed socket` sound in general? It sounds like nonsense to me. Maybe a schematic look can make my point clearer: ``` IOCP I/O Cancellation ==================== ReadFile(sk, rctx) WriteFile(sk, wctx) ... CloseHandle(sk) ... GetQueuedCompletionStatusEx() handle/skip wctx event ... GetQueuedCompletionStatusEx() handle/skip rctx event and destroy object data ``` while the same on UNIX is: ``` kqueue/epoll I/O Cancellation ============================= recv(sk) write(sk) ... close(sk) destroy object data and turn over the safety bit ``` In the end, IOCP's design is just different from that of kqueue and epoll. Maybe it's just me, but I have a feeling that there's not enough flexibility when I work with IOCP. It seems harder, it requires more code, more logical branches to support. But it is what it is. #### Accepting socket connections with IOCP Now let's see how we can use IOCP to accept incoming socket connections. ``` /* Kernel Queue The Complete Guide: iocp-accept.c: Accept socket connection Link with -lws2_32 */ #include #include #include #include #include HANDLE kq; LPFN\_ACCEPTEX KQAcceptEx; LPFN\_GETACCEPTEXSOCKADDRS KQGetAcceptExSockaddrs; struct context { void (\*handler)(struct context \*obj); OVERLAPPED accept\_ctx; unsigned char local\_peer\_addrs[(sizeof(struct sockaddr\_in6) + 16) \* 2]; SOCKET client\_sock; }; void accept\_handler(struct context \*obj) { DWORD res; BOOL ok = GetOverlappedResult(NULL, &obj->accept\_ctx, &res, 0); assert(ok); printf("Accepted socket connection via IOCP\n"); // get local and peer network address of the accepted socket int len\_local = 0, len\_peer = 0; struct sockaddr \*addr\_local, \*addr\_peer; KQGetAcceptExSockaddrs(obj->local\_peer\_addrs, 0, sizeof(struct sockaddr\_in6) + 16, sizeof(struct sockaddr\_in6) + 16, &addr\_local, &len\_local, &addr\_peer, &len\_peer); char buf[1000]; int r = recv(obj->client\_sock, buf, 1000, 0); assert(r >= 0); char data[] = "HTTP/1.1 200 OK\r\n\r\nHello"; assert(sizeof(data)-1 == send(obj->client\_sock, data, sizeof(data)-1, 0)); } void main() { // initialize sockets WSADATA wsa; WSAStartup(MAKEWORD(2, 2), &wsa); // create KQ object kq = CreateIoCompletionPort(INVALID\_HANDLE\_VALUE, NULL, 0, 0); assert(kq != NULL); struct context obj = {}; obj.handler = accept\_handler; // create the listening socket SOCKET lsock = socket(AF\_INET, SOCK\_STREAM, 0); assert(lsock != INVALID\_SOCKET); // make socket as non-blocking int nonblock = 1; ioctlsocket(lsock, FIONBIO, (unsigned long\*)&nonblock); struct sockaddr\_in addr = {}; addr.sin\_family = AF\_INET; addr.sin\_port = ntohs(64000); assert(0 == bind(lsock, (struct sockaddr\*)&addr, sizeof(struct sockaddr\_in))); assert(0 == listen(lsock, SOMAXCONN)); assert(NULL != CreateIoCompletionPort((HANDLE)lsock, kq, (ULONG\_PTR)&obj, 0)); // get extended socket function pointers void \*func = NULL; DWORD res; GUID guid = WSAID\_ACCEPTEX; WSAIoctl(lsock, SIO\_GET\_EXTENSION\_FUNCTION\_POINTER, (void\*)&guid, sizeof(GUID), &func, sizeof(void\*), &res, 0, 0); KQAcceptEx = func; func = NULL; GUID guid2 = WSAID\_GETACCEPTEXSOCKADDRS; WSAIoctl(lsock, SIO\_GET\_EXTENSION\_FUNCTION\_POINTER, (void\*)&guid2, sizeof(GUID), &func, sizeof(void\*), &res, 0, 0); KQGetAcceptExSockaddrs = func; assert(KQAcceptEx != NULL && KQGetAcceptExSockaddrs != NULL); // try to accept a connection synchronously obj.client\_sock = accept(lsock, NULL, 0); assert(obj.client\_sock == INVALID\_SOCKET && GetLastError() == WSAEWOULDBLOCK); // we require this for our example // begin asynchronous operation obj.client\_sock = socket(AF\_INET, SOCK\_STREAM, 0); assert(obj.client\_sock != INVALID\_SOCKET); memset(&obj.accept\_ctx, 0, sizeof(obj.accept\_ctx)); BOOL ok = KQAcceptEx(lsock, obj.client\_sock, obj.local\_peer\_addrs, 0, sizeof(struct sockaddr\_in6) + 16, sizeof(struct sockaddr\_in6) + 16, &res, &obj.accept\_ctx); assert(ok || GetLastError() == ERROR\_IO\_PENDING); // wait for incoming events from KQ OVERLAPPED\_ENTRY events[1]; ULONG n = 0; int timeout\_ms = -1; // wait indefinitely ok = GetQueuedCompletionStatusEx(kq, events, 1, &n, timeout\_ms, 0); assert(ok); assert(n == 1); struct context \*o = (void\*)events[0].lpCompletionKey; o->handler(o); // handle socket accept event closesocket(obj.client\_sock); closesocket(lsock); CloseHandle(kq); } ``` First, we call `accept()` as usual - we can always hope it will return immediately with a new client connetion and we won't need to go the long way with IOCP events. ``` csock = accept(lsock, NULL, 0); ``` But if it returns `INVALID_SOCKET` with `WSAEWOULDBLOCK`, it means that there are no clients at the moment and we must wait. Now we must use IOCP and a couple of new Windows-specific functions. `AcceptEx()` function begins an asynchronous operation which will signal us via IOCP when a new client connects to our listening socket. But since it's a real asynchronous operation and not just a signal like in kqueue or epoll, we must also provide it with a client socket descriptor created beforehand. Of course it must stay valid until the operation completes. Another inconvenient thing is that we need to also supply it with the buffer where local and peer address will be stored. For some reason we must make 16 bytes more room in our buffer for each address. Please don't mind me allocating the space for IPv6 while using an IPv4 socket. ``` csock = socket(AF_INET, SOCK_STREAM, 0); unsigned char local_peer_addrs[(sizeof(struct sockaddr_in6) + 16) * 2]; DWORD res; OVERLAPPED ctx = {}; KQAcceptEx(lsock, csock, local_peer_addrs, 0, sizeof(struct sockaddr_in6) + 16, sizeof(struct sockaddr_in6) + 16, &res, &ctx); ``` After we receive a signal from IOCP, our client socket descriptor is a valid connected socket which we would get by calling `accept()`. The only difference now is that we must get the local and peer address by calling a new special function `GetAcceptExSockaddrs()` which finally returns us `struct sockaddr*` pointers. ``` int len_local = 0, len_peer = 0; struct sockaddr *addr_local, *addr_peer; KQGetAcceptExSockaddrs(local_peer_addrs, 0, sizeof(struct sockaddr_in6) + 16, sizeof(struct sockaddr_in6) + 16, &addr_local, &len_local, &addr_peer, &len_peer); ``` Don't forget that after processing each `AcceptEx()` signal we must proceed by calling `accept()` again, and if it fails - begin a new operation with `AcceptEx()`. We need so much more stuff to handle here in IOCP rather than very simple behaviour of the asynchronous `accept()` we have with kqueue and epoll. But this is the reality. #### System timer events with IOCP Now let's see how we can work with timers and receive timer signals with IOCP. ``` /* Kernel Queue The Complete Guide: iocp-timer.c: System timer events */ #include #include #include HANDLE kq; HANDLE tmr; HANDLE evt; struct context { void (\*handler)(struct context \*obj); }; void timer\_handler(struct context \*obj) { static int n; printf("Received timer event via IOCP: %d\n", n++); } void \_\_stdcall timer\_func(void \*arg, DWORD dwTimerLowValue, DWORD dwTimerHighValue) { assert(0 != PostQueuedCompletionStatus(kq, 0, (ULONG\_PTR)arg, NULL)); } int \_\_stdcall timer\_thread(void \*param) { int period\_ms = 1000; long long due\_ns100 = (long long)period\_ms \* 1000 \* -10; assert(SetWaitableTimer(tmr, (LARGE\_INTEGER\*)&due\_ns100, period\_ms, timer\_func, param, 1)); for (;;) { int r = WaitForSingleObjectEx(evt, INFINITE, /\*alertable\*/ 1); if (r == WAIT\_IO\_COMPLETION) { } else if (r == WAIT\_OBJECT\_0) { } else { assert(0); break; } } return 0; } void main() { // create KQ object kq = CreateIoCompletionPort(INVALID\_HANDLE\_VALUE, NULL, 0, 0); assert(kq != NULL); struct context obj = {}; obj.handler = timer\_handler; // create timer object tmr = CreateWaitableTimer(NULL, 0, NULL); assert(tmr != NULL); // create event object to control the timer thread evt = CreateEvent(NULL, 0, 0, NULL); assert(evt != NULL); // start a new thread which will receive timer notifications HANDLE thd = CreateThread(NULL, 0, (PTHREAD\_START\_ROUTINE)timer\_thread, &obj, 0, NULL); assert(thd != NULL); // wait for incoming events from KQ and process them for (;;) { OVERLAPPED\_ENTRY events[1]; ULONG n = 0; int timeout\_ms = -1; // wait indefinitely BOOL ok = GetQueuedCompletionStatusEx(kq, events, 1, &n, timeout\_ms, 0); assert(ok); struct context \*o = (void\*)events[0].lpCompletionKey; o->handler(o); // handle event } CloseHandle(tmr); // Note that we should correctly exit the thread with WaitForSingleObject(), but it's OK for our example CloseHandle(thd); CloseHandle(evt); CloseHandle(kq); } ``` There are 3 things we need to do first - create timer object, create a thread that will process timer events and create an event object for controlling this timer thread. All 3 functions return `NULL` on error. ``` HANDLE tmr = CreateWaitableTimer(NULL, 0, NULL); HANDLE evt = CreateEvent(NULL, 0, 0, NULL); HANDLE thd = CreateThread(NULL, 0, (PTHREAD_START_ROUTINE)timer_thread, NULL, 0, NULL); ``` Inside the thread function we start the timer by calling `SetWaitableTimer()` and we pass to it the timer interval along with the timer function. ``` int period_ms = 1000; long long due_ns100 = (long long)period_ms * 1000 * -10; assert(SetWaitableTimer(htmr, (LARGE_INTEGER*)&due_ns100, period_ms, timer_func, param, 1)); ``` The timer function looks this way: ``` void __stdcall timer_func(void *arg, DWORD dwTimerLowValue, DWORD dwTimerHighValue) { } ``` The function is called each time the timer interval expires. But it won't be called unless we wait for incoming timer events. We can't do it via IOCP directly - we need to use another waiting function, for example `WaitForSingleObjectEx()` with *alertable state*. We also wait for events on our event descriptor we created earlier, but in this example I don't have a code which processes it. ``` for (;;) { WaitForSingleObjectEx(evt, INFINITE, /*alertable*/ 1); } ``` But the call to our timer function alone won't wake up our main thread, so we have to post a user event to it. And only then we have a working system timer via KQ. The signal delivery mechanism for a timer can be best explained by this diagram: ``` [Thread 2] [Thread 1] main() |- CreateThread(timer_thread) timer_thread() | |- SetWaitableTimer(timer_func) | |- WaitForSingleObjectEx() | |- timer_func() | |- PostQueuedCompletionStatus(obj) | with obj.handler=timer_handler | |- GetQueuedCompletionStatusEx() |- timer_handler() ``` But why do we need to post a user event into KQ while we can just process timer events in another thread? The reason for this is because in real world the timers are often used to close stalled connections. If we would try to do that directly from the timer thread, we will absolutely require a locking mechanism, because the KQ thread may operate with the same object at this time. So to simplify our code it's much better to do all the work from the same thread, thus eliminating the requirement to use per-object locks. The second reason for this is to emulate the behaviour of epoll and kqueue, thus making our code look similar everywhere. The third reason is just pure human logic which tells us that all we need is a single kernel queue mechanism for everything - we need a way to receive *any* event from the kernel and process it with the same code. We wouldn't need another thread for timer at all if Windows didn't force us. #### Asynchronous file I/O with IOCP File I/O with IOCP looks similar to file AIO API we used with kqueue. But file AIO on FreeBSD is still better than anything else because it supports unaligned and bufferred I/O, while file AIO on Linux and Windows require us to switch off kernel disk caching and require us using aligned buffers and offsets. It's interesting that due to the nature of IOCP the code doesn't look "off-topic" as with kqueue or epoll (there, file AIO tries to glue asynchronous operations with a pure event delivery mechanism). So in this situation I can't tell anything bad about IOCP because it delivers what it's designed for - asynchronous operations. Here's the code that reads from a file asynchronously. ``` /* Kernel Queue The Complete Guide: iocp-file.c: Asynchronous file reading Usage: echo Hello file AIO >iocp-file.txt iocp-file */ #include #include #include HANDLE kq; struct context { void (\*handler)(struct context \*obj); HANDLE fd; OVERLAPPED rctx; }; void file\_io\_result(struct context \*obj) { DWORD res; BOOL ok = GetOverlappedResult(NULL, &obj->rctx, &res, 0); if (ok) ; else if (GetLastError() == ERROR\_HANDLE\_EOF) res = 0; else assert(0); printf("Read from file with IOCP: %d\n", res); } void main() { // create KQ object kq = CreateIoCompletionPort(INVALID\_HANDLE\_VALUE, NULL, 0, 0); assert(kq != NULL); struct context obj = {}; obj.handler = file\_io\_result; // create a named pipe, FILE\_FLAG\_NO\_BUFFERING | FILE\_FLAG\_OVERLAPPED are mandatory obj.fd = CreateFileW(L"iocp-file.txt" , GENERIC\_READ, FILE\_SHARE\_READ | FILE\_SHARE\_WRITE | FILE\_SHARE\_DELETE, NULL, OPEN\_EXISTING , FILE\_ATTRIBUTE\_NORMAL | FILE\_FLAG\_NO\_BUFFERING | FILE\_FLAG\_OVERLAPPED, NULL); assert(obj.fd != INVALID\_HANDLE\_VALUE); // attach file to KQ assert(NULL != CreateIoCompletionPort(obj.fd, kq, (ULONG\_PTR)&obj, 0)); void \*buf = HeapAlloc(GetProcessHeap(), 0, 4\*1024); assert(buf != NULL); // begin asynchronous file read operation memset(&obj.rctx, 0, sizeof(obj.rctx)); unsigned int size = 4\*1024; unsigned long long off = 0; obj.rctx.Offset = (unsigned int)off; obj.rctx.OffsetHigh = (unsigned int)(off >> 32); BOOL ok = ReadFile(obj.fd, buf, size, NULL, &obj.rctx); assert(GetLastError() != ERROR\_HANDLE\_EOF); assert(ok || GetLastError() == ERROR\_IO\_PENDING); // asynchronous file reading is in progress, now wait for the signal from KQ OVERLAPPED\_ENTRY events[1]; ULONG n = 0; int timeout\_ms = -1; // wait indefinitely ok = GetQueuedCompletionStatusEx(kq, events, 1, &n, timeout\_ms, 0); assert(ok); struct context \*o = (void\*)events[0].lpCompletionKey; o->handler(o); // handle read event HeapFree(GetProcessHeap(), 0, buf); CloseHandle(obj.fd); CloseHandle(kq); } ``` File descriptor must be opened with `FILE_FLAG_NO_BUFFERING | FILE_FLAG_OVERLAPPED` flags, otherwise asynchronous operations won't work. To initiate an asynchronous file reading operation we call `ReadFile()` on a file descriptor and supply the parameters: aligned buffer pointer, aligned maximum number of bytes to read, aligned file offset. Remember that if the function fails immediately or asynchronously with `ERROR_HANDLE_EOF` error it simply means that we've reached file end. It's always interesting to see how Windows functions are designed: here we pass buffer and size as function parameters, but we pass file offset via `OVERLAPPED` object even though all 3 parameters are bound together for a single operation. ``` void *buf = ...; unsigned int size = ...; unsigned long long off = ...; OVERLAPPED ctx = {}; ctx.Offset = (unsigned int)off; ctx.OffsetHigh = (unsigned int)(off >> 32); ReadFile(fd, buf, size, NULL, &ctx); ``` Writing asynchronously to a file is the same as reading, except we would call `WriteFile()`. However, writing into a new file (into an unallocated disk space) on NTFS is **always blocking** and it isn't in fact asynchronous at all. So you should first allocate enough disk space before writing new data to a file using this method to achieve truely asynchronous behaviour. #### Conclusion So I've written here nearly everything that I know about kernel queues and I hope that this guide helped you at least with something. I've made a new repository on GitHub so that you can easily download all examples and so that we all can improve the code together: <https://github.com/stsaz/kernel-queue-the-complete-guide>. I understand that the low-level KQ APIs aren't very popular because the developers would rather use some library which handles all these complexities inside than waste their time trying to understand how it all works... But come on, since when did we start to ignore the true nature of the things? If you would sit down and write your own function wrappers for all KQs you will have a small library where you will understand every single line. You will have a complete experience which will absolutely help you with your future work. It will make you smarter, it will make you better. After all, isn't it what we are here in this world for? To make ourselves better with each passing day, to grow in confidence, to grow in experience, in knowledge?
https://habr.com/ru/post/600123/
null
null
18,743
52.49
Generate axis aligned BBox tree for raycasting and other Locator based searches. More... #include <vtkModifiedBSPTree.h> Generate axis aligned BBox tree for raycasting and other Locator based searches. vtkModifiedBSPTree creates an evenly balanced BSP tree using a top down implementation. Axis aligned split planes are found which evenly divide cells into two buckets. Generally a split plane will intersect some cells and these are usually stored in both child nodes of the current parent. (Or split into separate cells which we cannot consider in this case). Storing cells in multiple buckets creates problems associated with multiple tests against rays and increases the required storage as complex meshes will have many cells straddling a split plane (and further splits may cause multiple copies of these). During a discussion with Arno Formella in 1998 he suggested using a third child node to store objects which straddle split planes. I've not seen this published (Yes! - see below), but thought it worth trying. This implementation of the BSP tree creates a third child node for storing cells laying across split planes, the third cell may overlap the other two, but the two 'proper' nodes otherwise conform to usual BSP rules. The advantage of this implementation is cells only ever lie in one node and mailbox testing is avoided. All BBoxes are axis aligned and a ray cast uses an efficient search strategy based on near/far nodes and rejects all BBoxes using simple tests. For fast raytracing, 6 copies of cell lists are stored in each leaf node each list is in axis sorted order +/- x,y,z and cells are always tested in the direction of the ray dominant axis. Once an intersection is found any cell or BBox with a closest point further than the I-point can be instantly rejected and raytracing stops as soon as no nodes can be closer than the current best intersection point. The addition of the 'middle' node upsets the optimal balance of the tree, but is a minor overhead during the raytrace. Each child node is contracted such that it tightly fits all cells inside it, enabling further ray/box rejections. This class is intended for persons requiring many ray tests and is optimized for this purpose. As no cell ever lies in more than one leaf node, and parent nodes do not maintain cell lists, the memory overhead of the sorted cell lists is 6*num_cells*4 for 6 lists of ints, each num_cells in length. The memory requirement of the nodes themselves is usually of minor significance. Subdividision is controlled by MaxCellsPerNode - any node with more than this number will be subdivided providing a good split plane can be found and the max depth is not exceeded. The average cells per leaf will usually be around half the MaxCellsPerNode, though the middle node is usually sparsely populated and lowers the average slightly. The middle node will not be created when not needed. Subdividing down to very small cells per node is not generally suggested as then the 6 stored cell lists are effectively redundant. Values of MaxcellsPerNode of around 16->128 depending on dataset size will usually give good results. Cells are only sorted into 6 lists once - before tree creation, each node segments the lists and passes them down to the new child nodes whilst maintaining sorted order. This makes for an efficient subdivision strategy. NB. The following reference has been sent to me @Article{formella-1995-ray, author = "Arno Formella and Christian Gill", title = "{Ray Tracing: A Quantitative Analysis and a New Practical Algorithm}", journal = "{The Visual Computer}", year = "{1995}", month = dec, pages = "{465--476}", volume = "{11}", number = "{9}", publisher = "{Springer}", keywords = "{ray tracing, space subdivision, plane traversal, octree, clustering, benchmark scenes}", annote = "{We present a new method to accelerate the process of finding nearest ray–object intersections in ray tracing. The algorithm consumes an amount of memory more or less linear in the number of objects. The basic ideas can be characterized with a modified BSP–tree and plane traversal. Plane traversal is a fast linear time algorithm to find the closest intersection point in a list of bounding volumes hit by a ray. We use plane traversal at every node of the high outdegree BSP–tree. Our implementation is competitive to fast ray tracing programs. We present a benchmark suite which allows for an extensive comparison of ray tracing algorithms.}", } Implement intersection heap for testing rays against transparent objects This class is currently maintained by J. Biddiscombe who has specially requested that the code style not be modified to the kitware standard. Please respect the contribution of this class by keeping the style as close as possible to the author's original. Definition at line 156 of file vtkModifiedBSPTree.h. Standard Type-Macro. Definition at line 163 of file vtkModifiedBSPTree.h. Return 1 if this class is the same type of (or a subclass of) the named class. Returns 0 otherwise. This method works in combination with vtkTypeMacro found in vtkSetGet.h. Reimplemented from vtkAbstractCellLocator. Reimplemented from vtkAbstractCellLocator. Methods invoked by print to print information about the object including superclasses. Typically not called by the user (use Print() instead) but used in the hierarchical print process to combine the output of several classes. Reimplemented from vtkAbstractCellLocator. Construct with maximum 32 cells per node. (average 16->31) Free tree memory. Implements vtkLocator. Build Tree. Implements vtkLocator. Generate BBox representation of Nth level. Implements vtkLocator. Generate BBox representation of all leaf nodes. Return intersection point (if any) AND the cell which was intersected by the finite line. Uses fast tree-search BBox rejection tests. Reimplemented from vtkAbstractCellLocator. Return intersection point (if any) AND the cell which was intersected by the finite line. The cell is returned as a cell id and as a generic cell. Reimplemented from vtkAbstractCellLocator. Take the passed line segment and intersect it with the data set. The return value of the function is 0 if no intersections were found. For each intersection found, the vtkPoints and CellIds objects have the relevant information added in order of intersection increasing from ray start to end. If either vtkPoints or CellIds are nullptr pointers, then no information is generated for that list. Test a point to find if it is inside a cell. Returns the cellId if inside or -1 if not. Reimplemented from vtkAbstractCellLocator. Quickly test if a point is inside the bounds of a particular cell. Some locators cache cell bounds and this function can make use of fast access to the data. Reimplemented from vtkAbstractCellLocator. After subdivision has completed, one may wish to query the tree to find which cells are in which leaf nodes. This function returns a list which holds a cell Id list for each leaf node. Returns the Id of the cell containing the point, returns -1 if no cell found. This interface uses a tolerance of zero Find the cell containing a given point. returns -1 if no cell found the cell parameters are copied into the supplied variables, a cell must be provided to store the information. Return intersection point (if any) AND the cell which was intersected by the finite line. Return intersection point (if any) AND the cell which was intersected by the finite line. The cell is returned as a cell id and as a generic cell.. This method is currently only implemented in vtkOBBTree. Definition at line 241 of file vtkModifiedBSPTree.h. Definition at line 242 of file vtkModifiedBSPTree.h. Definition at line 243 of file vtkModifiedBSPTree.h. Definition at line 244 of file vtkModifiedBSPTree.h.
https://vtk.org/doc/nightly/html/classvtkModifiedBSPTree.html
CC-MAIN-2019-51
refinedweb
1,260
55.84
I want to change the save destination for each loop using Chromedriver. I'm studying web scraping. At the moment, I can access the page, save the file, and even change the save destination, but when I try to automatically change the save destination for each file using the loop part, a Google error "Failed-" I get a "download error". When I check the Google settings, it seems that the changes have been made, but for some reason the download does not work. Error that occursError that occurs from selenium import webdriver import glob import os import pprint import time def init_selenium (x): ### Set options for Chrome options = webdriver.ChromeOptions () options.add_experimental_option ('prefs', { 'download.default_directory': x, 'download.prompt_for_download': False, 'download.directory_upgrade': True, 'safebrowsing.enabled': True }) driver = webdriver.Chrome (chrome_options = options) return driver files = glob.glob ('C:/Users/koroz/Desktop/fits_make_text/*') filters = glob.glob ('C: /Users/koroz/Desktop/fits_make_text/{0}/*'.format(files[2][38:])) texts = glob.glob ('C: /Users/koroz/Desktop/fits_make_text/{0}/{1}/*'.format (files [2] [38:], filters [1] [76:])) for i in range (len (files)): for j in range (len (filters)): for k in range (texts): download_directory = r "C: /Users/koroz/Desktop/fits_files/{0}/{1}/{2}".format (files [i] [38:], filters [j] [76:], texts [ k] [116: -6]) driver = init_selenium (download_directory) driver.get ("URL") element = driver.find_element_by_name ("list") element.send_keys ('C: /Users/koroz/Desktop/fits_make_text/ {0}/{1}/{2} _ {3} _ {4} .txt'.format (files [i] [38:], filters [j] [76:], format (files [i] [38:]), texts [k] [116: -6], filters [j] [76:])) time.sleep (3) button = driver.find_element_by_id ("bulk-submit") button.click () time.sleep (10) driver.close (); There was no error in the execution environment The error on Google was displayed as "Failed-Download error" when downloading and could not be downloaded. - Answer # 1 Related articles - i want to change the youbube url to an embedded url using python replace - to get the same output without using python dict - - python - i am creating a breakout game i want to change the angle when the ball bounces off the paddle, but i can't also, the ba - python - i want to change the score of dict into grade - i don't understand the description when using lambda for the key of the sort method of python - image recognition using python beginner pyautogui is not possible - i want to store data using a for statement using a table in html in python, but it is not displayed well - [python] data preprocessing using pandas (deletion of multiple columns) - javascript - i want to change the process using check in jquery - python - when using pil, an error screen is displayed - [python3] i want to enter the contents (name) of the qr code using a barcode reader - python - probability prediction using multiple time series data - python 3x - replace does not change - i want to get a mac table using snmp in python Related questions - python - i made a code to search a website tag as a string, but can it be simplified? - python - whether scraping is possible - upgrade to windows 10 python no longer works - [python] i want to take a screenshot of the entire page with selenium (scrolling but the bottom of the page is cut off) - when i get information with python's telnetlib and write it to a file, extra line breaks are created - an init error that is not used in python and ldl appears - python - [selenium] i want to click the dropdown, but an error is returned - python - how to format (extract) only the json part of a character string that contains some json - python - #pipenv shell can't be done - python 390 does not install properly I made a mistake in writing the path. The local path should be'\' instead of'/'!
https://www.tutorialfor.com/questions-318048.htm
CC-MAIN-2020-50
refinedweb
620
59.53
richard -rw- weinberger <richard.weinberger@gmail.com> writes:> On Sun, Apr 8, 2012 at 7:10 AM, Eric W. Biederman <ebiederm@xmission.com> wrote:>> - Capabilities are localized to the current user namespace making>> it safe to give the initial user in a user namespace all capabilities.>>>> So, this makes LXC and friends ready for hostile environments?> IOW a root user (with all capabilities) sitting in his own namespace can no> longer ham the host?The user namespace now restricts the root user in a container to beingable to do no more harm than any other user can do. Additionally suidexecutables can no longer lead to having all power on the system. Whichmeans that the only privilege escalation attacks available from acontainer require kernel bugs.With my version of user namespaces you no longer have to worry about thecontainer root writing to files in /proc or /sys and changing thebehavior of the system. Nor do you have to worry about messages passedacross unix domain sockets to d-bus having a trusted uid and beingallowed to do something nasty.It allows for applications with no capabilities to use multipleuids and to implement privilege separation.I certainly see user namespaces like this as having the potentialto make linux systems more secure.You will have to make your own threat assessment to decide if that isenough of an improvement to start deploying containers in what youconsider hostile environments.For me the big potential I see is that it makes possible the creation ofa container without privilege (today the uid mapping setup stillrequires privilege), and it allows a lot of things that the existence ofsuid root executables has prevented us from making unprivileged before.After the core is settled we can start looking at patches to allowunprivileged creation of other namespaces. Unprivileged mounts.Unprivileged use of the networking stack. Bringing many of theimprovements that linux has seen over the years to unprivilegedusers.I also see great potential for April fools day jokes. You log in andtry to fix something and discover you are not the root you thought youwere. Does that count as a hostile environment?Eric--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
https://lkml.org/lkml/2012/4/8/100
CC-MAIN-2016-50
refinedweb
380
54.93
There - using TimerTask - using ScheduledExecutorService using simple thread This is very simple, which creates the simple thread puts it run in forever with use of while loop and makes use of sleep method to put the interval between running. This is simply fast and quick way to achieve it Following is code for this. public class Task1 { public static void main(String[] args) { // run in a second final long timeInterval = 1000; Runnable runnable = new Runnable() { public void run() { while (true) { // ------- code for task to run System.out.println("Hello !!"); // ------- ends here try { Thread.sleep(timeInterval); } catch (InterruptedException e) { e.printStackTrace(); } } } }; Thread thread = new Thread(runnable); thread.start(); } } using the Timer and TimerTask Previous method we saw was very quickest possible, but it lacks some functionality This has much more benefits than previous they are as follows - control over when start and cancel task - first execution can be delayed if wanted, provides useful In this we use, Timer class for scheduling purpose and TimerTask is used for enclosing task to be executed inside its run() method. Timer instance can be shared to schedule the multiple task and it is thread-safe. When Timer constructor is called , it creates one thread and this single thread is used any scheduling of task. For our purpose, we use Timer#scheduleAtFixedRate Following code shows the use of Timer and TimerTask import java.util.Timer; import java.util.TimerTask; public class Task2 { public static void main(String[] args) { TimerTask task = new TimerTask() { @Override public void run() { // task to run goes here System.out.println("Hello !!!"); } }; Timer timer = new Timer(); long delay = 0; long intevalPeriod = 1 * 1000; // schedules the task to be run in an interval timer.scheduleAtFixedRate(task, delay, intevalPeriod); } // end of main } These classes are classes existed from the JDK 1.3. using ScheduledExecutorService This is introduced in java.util.concurrent from Java SE 5 as Concurrency utilities. This is preferred way to achieve the goal. It provides following benefits as compared to previous solutions - pool of threads is used to execute as compared TImer`s single thread - Provides the flexibility for delaying first execution - Provides nice conventions for providing the time intervals Following code shows use of same, In this, we use ScheduledExecutorService#scheduleAtFixedRate as shown , it takes param as runnable which particular piece of code we want to run , initialdelay for first execution import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class Task3 { public static void main(String[] args) { Runnable runnable = new Runnable() { public void run() { // task to run goes here System.out.println("Hello !!"); } }; ScheduledExecutorService service = Executors .newSingleThreadScheduledExecutor(); service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS); } } Nice post but it would be more useful if you include the Quartz Api also. How to run the above code for only particular time period say 30 min. After that it should stop executing? Thank you for the great example snippets. I spent 2 hours trying to figure out why my TimerTasks were not cancelling and resetting. They do not seem as robust using ScheduledExecutorService!
https://www.javacodegeeks.com/2014/04/java-how-to-schedule-a-task-to-run-in-an-interval.html
CC-MAIN-2022-40
refinedweb
507
55.24
Compression Software Showing page 1 of 2. ShmenonPie's Stash of Stuff A database system, another, older database system, a compression library, something to do with menus and XML, and whatever I happen to be working on at the time Podi ZLib Data Compression Library ZLib 1.2.3 wrapper for Delphi language. It works on latest Delphi 2010 too.1 weekly downloads NetCompress Open MP accelerated implementation of distributed network storage system.0 weekly downloads epo "epo" is an advanced archiving system on Windows platforms. It tightly integrates into Explorer through its shell namespace extension and offers very easy-to-use archiving features.0 weekly downloads Catalog Now! Track all your files, locally, on CD-ROMs, and on removables.1 weekly downloads Compression with Huffman algorithm Logiciel codeur et décodeur de fichiers texte selon l'algortihme de Huffman.0 weekly downloads packmanpacker Windows 32 bit exe and dll packer2 weekly downloads hoz - Hacha Open Zource HOZ (Hacha Open Zource) is an Hacha clone written in pure C. It\'s smaller and faster than the original, and it\'s Open Source.0 weekly downloads Renpad Backup Renpad Backup is a small but powerful backup program. It has been designed with the end user in mind. Specifically targeting ease of use.1 weekly downloads Plug-in Setup Windows Setup tool specifically designed for installing PhotoShop compatible plug-ins. Will recognize all Windows PhotoShop plug-in compatible hosts and allow the user to pick which hosts the plug-in should be installed for.14 weekly downloads J7Z J7Z is an alternative 7-Zip GUI. It was designed by Xavion. 7-Zip is a high-compression file archiver. It was designed by Igor Pavlov.166 weekly downloads Fractal Image Archiver Fractal image archiver.0 weekly downloads AtomBackup This is a basic backup program that can be used to backup a system automatically very simply and eventually with many features.0 JAR Tool GUI A very simple GUI tool that can be used to unzip compressed files. It is a single file (a jar) that requires you have a Java runtime environment installed.0 weekly downloads QuickLZD QuickLZD is D programming language () bindings for QuickLZ ().0 weekly downloads Personal Zip Backup A simple utility to back-up and archive selected directories and files on your computer. Creates password enabled zip compression files for each configured archive and moves them to an archive path of your choice.0 weekly downloads
http://sourceforge.net/directory/security-utilities/storage/archiving/compression/os%3Amswin_xp/?sort=update
CC-MAIN-2014-42
refinedweb
405
58.38
If you visit Codeplex.com you can find a number of (in some cases) quite sophisticated implementations of indexing and search engines using Lucene.net. However, getting any one of them into a state of “usability” for your own “stuff” may be very difficult because they are complex. So while investigating Lucene.net for my own use as a potential alternative to say SQL Server FullText or perhaps DtSearch, I thought it would be a good idea to start instead from the ground – up, with just the basics. Lucene.net is a complete, single assembly solution to virtually any indexing and searching need. The compiled assembly is only 440Kb. Lucene.net is also pretty fast - you'll see a milliseconds elapsed time displayed in the demo. And there's nothing to stop you from kicking off multiple threads to do your indexing provided you have sufficient locking semantics around the Write method of the indexer. It is 100% managed code; there is no COM Interop and no dependency on a database. Lucene.Net is comprised of the following basic building blocks: Directory – a Lucene – specific index directory on disk ( There are other options such as in RAM). Analyzer – any of a number of different content analyzers. Here I use the StandardAnalyzer. IndexWriter – Does just what it says – writes index entries into the Directory IndexReader – Reads an index. Has many methods. Document – this is the basic structure that is used to design the fields in your index items IndexSearcher - Designed to implement searches on an index. QueryParser - Parses a specified query so that the Searcher can use it. Query - the object that represents the query item for the searcher to use. That's really all you need to know to understand Lucene.net. There is more, but by starting out with the basics, it becomes much easier to grasp it all. Indexing: Here is how we would create an index from within a web page: protected void btnIndex_Click(object sender, EventArgs e) { //Setup indexer Directory directory = FSDirectory.GetDirectory(Server.MapPath( "~/LuceneIndex")); Analyzer analyzer = new StandardAnalyzer(); //The third argument in the IndexWriter constructor is a boolean, which tells it to create the index if if doesn't already //exist (if true). IndexWriter writer = new IndexWriter(directory, analyzer, true); IndexReader red = IndexReader.Open(directory); int totDocs = red.MaxDoc(); red.Close(); //Add documents to the index string text = String.Empty; string txts = totDocs.ToString( ); int j = 0; WebClient wc = new WebClient(); string s = wc.DownloadString(""); MemoryStream ms = new MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(s)); XmlDocument doc = new XmlDocument(); doc.Load(ms); Stopwatch sw = new Stopwatch(); sw.Start(); XmlNodeList nodes = doc.DocumentElement.SelectNodes("//item"); for (int i = 0; i < nodes.Count; i++) { AddTextToIndex(i, nodes[i], writer); j++; } //Optimize our index writer.Optimize(); //Close everybody writer.Flush(); writer.Close(); directory.Close(); sw.Stop(); Label1.Text = j.ToString() + " entries added, " + txts + " documents total in " + sw.ElapsedMilliseconds.ToString() + "ms"; } First, we get our Directory. We create an Analyzer, an IndexWriter, and an IndexReader. Here, we're only using the IndexReader to get the total existing document count.. Normally, I would read the documents to be indexed out of a database. But to make the demo more portable, here I'm just getting one of our Eggheadcafe.com article feeds (the list of articles you see at the left on our home page) and I'll index that. My key method is the AddTextToIndex method: private void AddTextToIndex(int txts, XmlNode node, IndexWriter writer) { Document doc = new Document(); doc.Add(new Field("id", txts.ToString(), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc.Add(new Field("Description", (String)node.ChildNodes[3].InnerText , Field.Store.YES, Field.Index.TOKENIZED)); doc.Add(new Field("Link", (string)node.ChildNodes[2].InnerText , Field.Store.YES, Field.Index.UN_TOKENIZED)); doc.Add(new Field("Title", (string)node.ChildNodes[0].InnerText , Field.Store.YES, Field.Index.TOKENIZED)); writer.AddDocument(doc); } Your custom version of an AddTextToIndex method might have a DataRow parameter, for example, instead of an XmlNode. We create a new Document, and then we add fields. The "id" field is a must-have. Then I add Description, Link, and Title fields, just as you would find in an RSS Item node. The Field.Store.YES enum just says to store the field in the document object into the written index on disk, and the TOKENIZED enum means that I want Lucene.net to pull it apart and analyze it so it can be used in a query. UN_TOKENIZED (such as for Link) means I need it stored so it comes back in my results, but I'm not going to search on it. So essentially here I am indexing both the Description and the Title fields.You can get the documents to be indexed from anywhere you want - the file system, a Database, or here, some RSS feeds. Searches Searches are performed with the IndexSearcher and QueryParser objects: protected void btnSearch_Click(object sender, EventArgs e) { IndexSearcher searcher = new IndexSearcher(directory); QueryParser parser = new QueryParser("Description", analyzer); //Supply conditions Search(txtSearch.Text, searcher, parser); } private void Search(string text, IndexSearcher searcher, QueryParser parser) { if (text == null) text = ".NET"; //Supply conditions Query query = parser.Parse(text); //Do the search Hits hits = searcher.Search(query); int results = hits.Length(); Label1.Text ="Found " + results.ToString( ) +" results"; List<SearchResult> list = new List<SearchResult>(); SearchResult sr = null; for (int i = 0; i < results; i++) { sr = new SearchResult(); Document doc = hits.Doc(i); float score = hits.Score(i); sr.Id = int.Parse(doc.Get("id")); sr.Score = score; sr.Description = doc.Get("Description"); sr.Title = doc.Get("Title"); sr.Link = doc.Get("Link"); list.Add(sr); } //sort by score list = list.OrderByDescending(x => x.Score).ToList(); DataList1.DataSource = list; DataList1.DataBind(); } We get a query by having the parser parse the Search text. It's Search method returns the total hits. Here I am using a simple SearchResult class for databinding so I can assemble all the fields I want to display to the user: public class SearchResult { public float Score { get; set; } public int Id { get; set; } public string Link { get; set; } public string Description { get; set; } public string Title { get; set; } } That's all there is to it. Pretty simple, really. Of course there are a lot of other classes and extensions such as highlighters and document summary creators, etc. that you can build out your creations with For example, to generate highlighted hit text, you could do this, using the contrib Highlighter assembly: // in Search method: sr.Description = doc.Get("Description"); // replace the body text with a highlighted preview: string preview = GeneratePreviewText(query, sr.Description); sr.Description = preview; public string GeneratePreviewText(Query q, string text) { QueryScorer scorer = new QueryScorer(q); Lucene.Net.Highlight.Formatter formatter = new Lucene.Net.Highlight.SimpleHTMLFormatter("<span style='background:yellow;'>", "</span>"); Highlighter highlighter = new Highlighter(formatter, scorer); highlighter.SetTextFragmenter(new SimpleFragmenter(250)); TokenStream stream = new StandardAnalyzer().TokenStream("Description",new StringReader(text)); return highlighter.GetBestFragments(stream, text, 4, "<br/>"); } You can download the working Visual Studio 2010 Solution here. It includes a release build of the latest Lucene.Net assembly along with the Highliter assembly and the Highlight code shown above.
http://www.nullskull.com/a/1506/lucenenet-indexing-searching-entry-level-tutorial.aspx
CC-MAIN-2014-10
refinedweb
1,187
50.33
#include <nrt/Core/Design/BoundedSet.H> Thread-safe synchronized producer/consumer queue with element replacement policy. BoundedSet is designed for use in producer/consumer scenarios where multiple threads wish to push and pop data onto/from the set asynchronously. Threads that try to pop data when the set is empty will sleep until data is actually available, and threads that try to push data when the set is full will block until some space is available in the set. Threads that try to push an element that is already in the set will see that element pushed or not according to the insert policy. Definition at line 65 of file BoundedSet.H.
http://nrtkit.net/documentation/classnrt_1_1BoundedSet.html
CC-MAIN-2018-51
refinedweb
112
50.57
GTK# Platform Setup Xamarin.Forms now has preview support for GTK# apps. GTK# is a graphical user interface toolkit that links the GTK+ toolkit and a variety of GNOME libraries, allowing the development of fully native GNOME graphics apps using Mono and .NET. This article demonstrates how to add a GTK# project to a Xamarin.Forms solution. Before you start, create a new Xamarin.Forms solution, or use an existing Xamarin.Forms solution, for example, GameOfLife. Note While this article focuses on adding a GTK# app to a Xamarin.Forms solution in VS2017 and Visual Studio for Mac, it can also be performed in MonoDevelop for Linux. Adding a GTK# App GTK# for macOS and Linux is installed as part of Mono. GTK# for .NET can be installed on Windows with the GTK# Installer. Follow these instructions to add a GTK# app that will run on the Windows desktop: In Visual Studio 2017, right-click on the solution name in Solution Explorer and choose Add > New Project.... In the New Project window, at the left select Visual C# and Windows Classic Desktop. In the list of project types, choose Class Library (.NET Framework), and ensure that the Framework drop-down is set to a minimum of .NET Framework 4.7. Type a name for the project with a GTK extension, for example GameOfLife.GTK. Click the Browse button, select the folder containing the other platform projects, and press Select Folder. This will put the GTK project in the same directory as the other projects in the solution. Press the OK button to create the project. In the Solution Explorer, right click the new GTK project and select Manage NuGet Packages. Select the Browse tab, and search for Xamarin.Forms 3.0 or greater. Select the package and click the Install button. Now search for the Xamarin.Forms.Platform.GTK 3.0 package or greater. Select the package and click the Install button. In the Solution Explorer, right-click the solution name and select Manage NuGet Packages for Solution. Select the Update tab and the Xamarin.Forms package. Select all the projects and update them to the same Xamarin.Forms version as used by the GTK project. In the Solution Explorer, right-click on References in the GTK project. In the Reference Manager dialog, select Projects at the left, and check the checkbox adjacent to the .NET Standard or Shared project: In the Reference Manager dialog, press the Browse button and browse to the C:\Program Files (x86)\GtkSharp\2.12\lib folder and select the atk-sharp.dll, gdk-sharp.dll, glade-sharp.dll, glib-sharp.dll, gtk-dotnet.dll, gtk-sharp.dll files. Press the OK button to add the references. In the GTK project, rename Class1.cs to Program.cs. In the GTK project, edit the Program.cs file so that it resembles the following code: using System; using Xamarin.Forms; using Xamarin.Forms.Platform.GTK; namespace GameOfLife.GTK { class MainClass { [STAThread] public static void Main(string[] args) { Gtk.Application.Init(); Forms.Init(); var app = new App(); var window = new FormsWindow(); window.LoadApplication(app); window.SetApplicationTitle("Game of Life"); window.Show(); Gtk.Application.Run(); } } } This code initializes GTK# and Xamarin.Forms, creates an application window, and runs the app. In the Solution Explorer, right click the GTK project and select Properties. In the Properties window, select the Application tab and change the Output type drop-down to Windows Application. In the Solution Explorer, right-click the GTK project and select Set as Startup Project. Press F5 to run the program with the Visual Studio debugger on the Windows desktop: Next Steps Platform Specifics You can determine what platform your Xamarin.Forms application is running on from either XAML or code. This allows you to change program characteristics when it's running on GTK#. In code, compare the value of Device.RuntimePlatform with the Device.GTK constant (which equals the string "GTK"). If there's a match, the application is running on GTK#. In XAML, you can use the OnPlatform tag to select a property value specific to the platform: <Button.TextColor> <OnPlatform x: <On Platform="iOS" Value="White" /> <On Platform="macOS" Value="White" /> <On Platform="Android" Value="Black" /> <On Platform="GTK" Value="Blue" /> </OnPlatform> </Button.TextColor> Application Icon You can set the app icon at startup: window.SetApplicationIcon("icon.png"); Themes There are a wide variety of themes available for GTK#, and they can be used from a Xamarin.Forms app: GtkThemes.Init (); GtkThemes.LoadCustomTheme ("Themes/gtkrc"); Native Forms Native Forms allows Xamarin.Forms ContentPage-derived pages to be consumed by native projects, including GTK# projects. This can be accomplished by creating an instance of the ContentPage-derived page and converting it to the native GTK# type using the CreateContainer extension method: var settingsView = new SettingsView().CreateContainer(); vbox.PackEnd(settingsView, true, true, 0); For more information about Native Forms, see Native Forms. Issues This is a Preview, so you should expect that not everything is production ready. For the current implementation status, see Status, and for the current known issues, see Pending & Known Issues.
https://docs.microsoft.com/en-us/xamarin/xamarin-forms/platform/other/gtk
CC-MAIN-2019-04
refinedweb
846
60.11
The C library function char *strchr(const char *str, int c) searches for the first occurrence of the character c (an unsigned char) in the string pointed to by the argument str. Following is the declaration for strchr() function. char *strchr(const char *str, int c) str − This is the C string to be scanned. c − This is the character to be searched in str. This returns a pointer to the first occurrence of the character c in the string str, or NULL if the character is not found. The following example shows the usage of strchr() function. #include <stdio.h> #include <string.h> int main () { const char str[] = ""; const char ch = '.'; char *ret; ret = strchr(str, ch); printf("String after |%c| is - |%s|\n", ch, ret); return(0); } Let us compile and run the above program that will produce the following result − String after |.| is - |.tutorialspoint.com|
https://www.tutorialspoint.com/c_standard_library/c_function_strchr.htm
CC-MAIN-2021-25
refinedweb
148
72.76
This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project. On Tue, Mar 28, 2006 at 12:56:13AM +0200, Dieter Schuster wrote: > Hello, > > the version 0.8.0 of qemu in the Debian-pool will not compile on > PowerPC with GCC 3.4. The following patch will fix it: And suck performance wise with exploding code size. Without speaking of potential atomicity issues (although all architectures using the byte per byte generic code may hit the problem). > > --- cpu-all.h~ 2005-12-19 23:51:53.000000000 +0100 > +++ cpu-all.h 2006-03-27 22:47:54.291613000 +0200 > @@ -249,15 +249,11 @@ > > static inline void stl_le_p(void *ptr, int v) > { > -#ifdef __powerpc__ > - __asm__ __volatile__ ("stwbrx %1,0,%2" : "=m" (*(uint32_t *)ptr) : "r" (v), "r" (ptr)); > -#else > uint8_t *p = ptr; > p[0] = v; > p[1] = v >> 8; > p[2] = v >> 16; > p[3] = v >> 24; > -#endif > } > > static inline void stq_le_p(void *ptr, uint64_t v) > > > If I use GCC 3.3, then qemu compiles with the assembler instruction in > the patch above, but qemu does not work correctly (tested with Knoppix V5.0). Interesting, could it be an aliasing problem? Try to compile with -fno-strict-aliasing, although I doubt it will change anything. > > If I try to compile qemu with GCC 3.4 without the patch I get the following error: > > qemu-0.8.0/linux-user/elfload.c: In function `load_elf_binary': > qemu-0.8.0/cpu-all.h:253: error: inconsistent operand constraints in an `asm' > qemu-0.8.0/cpu-all.h:253: error: inconsistent operand constraints in an `asm' Weird. CC'ed to gcc list despite the fact that the 3.4 branch is definitely closed. I've not found anything remotely similar from bugzilla. > > But if I copy the function stl_le_p to a seperate file, the function > will compile with GCC 3.4. Which gcc-3.4 (gcc -v)? > > Is this a bug in qemu, or is it a bug in GCC 3.4? It looks like a compiler bug. But you should provide an environment independent test case, i.e., the preprocessed source. Please try also to provide a minimal failing test case (it may be hard given the symptoms). Regards, Gabriel
http://gcc.gnu.org/ml/gcc/2006-03/msg00778.html
CC-MAIN-2019-09
refinedweb
375
77.23
addrinfoex structure The addrinfoex structure is used by the GetAddrInfoEx function to hold host address information. Syntax - ai_flags Type: int Flags that indicate options used in the GetAddrInfoEx function. Supported values for the ai_flags member are defined in the Winsock2.h include file and can be a combination of the following options. - ai_family Type: int The address family. Possible values for the address family are defined in the Winsock2.h include table belowCTSTR The canonical name for the host. - ai_addr Type: struct sockaddr* A pointer to a sockaddr structure. The ai_addr member in each returned addrinfoex structure points to a filled-in socket address structure. The length, in bytes, of each returned addrinfoex structure is specified in the ai_addrlen member. - ai_blob Type: void* Type: size_t The length, in bytes, of the ai_blob member. - ai_provider Type: LPGUID A pointer to the GUID of a specific namespace provider. - ai_next Type: struct addrinfoex* A pointer to the next structure in a linked list. This parameter is set to NULL in the last addrinfoex structure of a linked list. Remarks The addrinfoex structure is used by the GetAddrInfoEx function to hold host address information. The addrinfoex structure is an enhanced version of the addrinfo and addrinfoW structures. The extra structure members are for blob data and the GUID for the namespace provider. The blob data is used to return additional provider-specific namespace information associated with a name. The format of data in the ai_blob member is specific to a particular namespace provider. Currently, blob data is used by the NS_EMAIL namespace provider to supply additional information. The addrinfoex structure is an enhanced version of the addrinfo and addrinfoW structure used with GetAddrInfoEx function.. When UNICODE or _UNICODE is defined, addrinfoex is defined to addrinfoexW, the Unicode version of this structure. The string parameters are defined to the PWSTR data type and the addrinfoexW structure is used. When UNICODE or _UNICODE is not defined, addrinfoex is defined to addrinfoexA, the ANSI version of this structure. The string parameters are of the PCSTR data type and the addrinfoexA structure is used. Upon a successful call to GetAddrInfoEx, a linked list of addrinfoex structures is returned in the ppResult parameter passed to the GetAddrInfoEx function. The list can be processed by following the pointer provided in the ai_next member of each returned addrinfoex structure until a NULL pointer is encountered. In each returned addrinfoex structure, the ai_family, ai_socktype, and ai_protocol members correspond to respective arguments in a socket or WSASocket function call. Also, the ai_addr member in each returned addrinfoex structure points to a filled-in socket address structure, the length of which is specified in its ai_addrlen member. Examples The following example demonstrates the use of the addrinfoexINFOEX *result = NULL; ADDRINFOEX *ptr = NULL; ADDRINFOEX hints; DWORD dwRetval = 0; int i = 1; DWORD dwNamespace = NS_DNS; LPGUID lpNspid = NULL;InfoEx with following parameters:\n"); wprintf(L"\tName = %ws\n", argv[1]); wprintf(L"\tServiceName (or port) = %ws\n\n", argv[2]); //-------------------------------- // Call GetAddrInfoEx(). If the call succeeds, // the aiList variable will hold a linked list // of ADDRINFOEX structures containing response // information about the host dwRetval = GetAddrInfoEx(argv[1], argv[2], dwNamespace, lpNspid, &hints, &result, NULL, NULL, NULL, NULL); if (dwRetval != 0) { wprintf(L"GetAddrInfoEx failed with error: %d\n", dwRetval); WSACleanup(); return 1; } wprintf(L"GetAddrInfoEx returned success\n"); // Retrieve each address and print out the hex bytes for (ptr = result; ptr != NULL; ptr = ptr->ai_next) { wprintf(L"GetAddrInfoExEx(result); WSACleanup(); return 0; } Requirements See also
https://msdn.microsoft.com/fr-fr/library/windows/desktop/ms737528(v=vs.85).aspx
CC-MAIN-2015-22
refinedweb
579
54.52
One critical note regarding Gems support in NetBeans is documented in the NetBeans Ruby Pack Wiki. According to the Wiki site, the Gems tool prevents you from being able to respond to prompts for those Ruby gems that require input during installation. JRuby Under the Covers It should be noted that what is really running under the covers of NetBeans Ruby Pack out-of-the-box is Java or more precisely JRuby. JRuby is a 100 percent Java-based Ruby interpreter. In other words, the Ruby language is interpreted and run on a JVM. In September 2006, Sun hired the two key developers behind JRuby: Thomas Enebo and Charles Nutter. According to several statements made by Sun representatives over the past year, Sun intends to make the Java Virtual Machine a suitable platform for other programming languages to compete with the likes of Microsoft's .NET. Running JRuby allows Ruby developers to tie into and use an extensive set of Java libraries and classes. NetBeans allows you to change the underlying engine. If you wish to run native Ruby (written in C) use the Tools—>Options dialog window to point to the native Ruby interpreter. In the Options window, click on the Miscellaneous category and locate the Ruby Installation option. Change the location of Ruby binary (see Figure 10) to point to your native Ruby installation. Of course, this requires that you have already downloaded and installed the native Ruby environment (available here). Better support for switching to/from JRuby/Native Ruby can be anticipated with future releases of NetBeans. The ToDo page on the NetBeans Ruby Pack Wiki suggests "Better support for switching Ruby platforms (JRuby, native Ruby) ala the Java Platform Manager" is at least on the drawing board. Be aware of a couple of issues/notes regarding use of native Ruby versus JRuby. If you want to use Gems with native Ruby, it must be installed with Ruby. The Ruby Gems window will then show you what Gems are installed with native Ruby and not NetBeans/JRuby. Also, when running under native Ruby, the IRB window still uses JRuby. Indeed, the native Ruby interpreter operates a bit faster and is a little less buggy because JRuby is still relatively new. However, using JRuby allows you to take advantage of Java code from Ruby. Today, using Java code classes/libraries in your Ruby code requires some effort in that NetBeans must be informed of where to locate and load your Java code before NetBeans is started. The Ruby Pack Wiki suggests that any Java classes or library .jar files that are to be used in the Ruby code must be made available by setting up a JRUBY_EXTRA_CLASSPATH environment variable. This did not work for me. The only way I was able to get my Ruby files to see and use Java classes through JRuby was to add the classes or .jar files directly to the JRuby library folder in NetBeans. Specifically, I had to make my com.intertech.shapes.Ellipse class shown in the Ruby example code below available through a JAR that was put into the NetBeans JRuby installation folder (\NetBeans 6.0 M9\ruby1\jruby-0.9.8\lib folder). package com.intertech.shapes; public class Ellipse { private int major_axis, minor_axis; public Ellipse(int major, int minor) { major_axis=major; minor_axis=minor; } public double area (){ return java.lang.Math.PI * (major_axis/2) * (minor_axis/2); } public String toString(){ return "This ellipse has a major axis of: " + major_axis + " and a minor axis of: " + minor_axis +"\n"; } } require "java" require "rectangle.rb" require "square.rb" require "circle.rb" MyEllipse=Java::com.intertech.shapes.Ellipse e = MyEllipse.new(3,4) print("The area of the ellipse is: " + e.area().to_s + "\n") print e.toString() r1 = Rectangle.new(3,4) print("Rectangle 1's area is: " + r1.area().to_s + "\n"); print("Rectangle 1's circumference is: " + r1.circumference().to_s + "\n\n"); r2 = Rectangle.new(5,7) print("Rectangle 2's area is: " + r2.area().to_s + "\n"); print("Rectangle 2's circumference is: " + r2.circumference().to_s + "\n\n"); Ecllipse Java class used by Ruby code. Please enable Javascript in your browser, before you post the comment! Now Javascript is disabled. Your name/nickname Your email WebSite Subject (Maximum characters: 1200). You have 1200 characters left.
http://www.devx.com/Java/Article/34747/0/page/3
CC-MAIN-2015-18
refinedweb
711
57.67
Hello all, I'm experiencing some quite annoying unresolved externals here. I have the following code: However, I get the following unresolved external error:However, I get the following unresolved external error:Code:// In Foo.h #ifndef _FOO_H_ #define _FOO_H_ template <typename T> class CFoo { private: T m_someT; public: void SetSomeT(T value); // Doesn't work! // Works, but not desirable. /*void SetSomeT(T value) { m_someT = value; }*/ }; #endif // In Foo.cpp #include "Foo.h" template <typename T> void CFoo<T>::SetSomeT(T value) { m_someT = value; } // In Main.cpp #include "Foo.h" int main() { CFoo<int> foo; foo.SetSomeT(2); return 0; } Template error LNK2019: unresolved external symbol "public: void __thiscall CFoo<int>::SetSomeT(int)" (?SetSomeT@?$CFoo@H@@QAEXH@Z) referenced in function _main I know one could "just" move the actual implementation of the template functions into the header (Foo.h) and everything would work out just fine, but WHY? I mean.. I like keeping my classes and its implementation separated (unless we're talking small accessor functions, etc.) Can anyone explain why this is messing up the linker? Oh, and while we're on it.. if I inline my functions in an ordinary class (in the .cpp, too) I get unresolved symbols until I move the actual implementation into the class definition itself. This really doesn't suit me well if I'm doing a .lib and I would like to hide the actual implementation from the user. Please, I hope you can enlighten me on my C++ path Thanks in advance!
https://cboard.cprogramming.com/cplusplus-programming/49829-template-class-unresolved-externals.html?s=8b541fc5fe61e40ed4890f485d820f99
CC-MAIN-2021-31
refinedweb
252
60.11
Modules Functions are great for organising your software into self-contained, reusable blocks of code. However, as it stands, you have to copy and paste your function into every script or program in which it is used. Modules (also called libraries) provide a way of packaging up a collection of functions into a single, reusable package. In python, creating a module is very easy. Indeed, you have already done it! The python scripts you have written are actually already python modules. You can import all of the functions defined in a script by using the import command. Ensure that you are in the same directory as your completed morse.py script and then start a new ipython session by typing; ipython Now, in ipython you can import all of the functions in your morse.py script by typing; import morse The import command has loaded the script, importing the functions and then running all of the code. This is why you can now see printed to the screen; Instruction (encode, decode, quit) :-> Type quit now to exit this prompt. Now in ipython, you have access to all of the functions and variables contained in morse.py. These functions are prefixed with the name morse., e.g. type; morse.[TAB] and you should see something similar to; morse.decodeFromMorse morse.letter_to_morse morse.morse_to_letter morse.sys morse.encodeToMorse morse.line morse.py morse.letter morse.morse morse.pyc You can now call the encode and decode functions interactively, e.g. try typing; print( morse.encodeToMorse("Hello World") ) and you should see printed; '.... . .-.. .-.. --- / .-- --- .-. .-.. -..' You can check that this is correct by decoding the above message. Type; print( morse.decodeFromMorse(".... . .-.. .-.. --- / .-- --- .-. .-.. -..") ) This should print the string hello world. While this is great, it was quite annoying that the actual code in morse.py was run when we imported the function (i.e. that we have to type quit to exit the while loop). We can stop this from happening by using a python hidden variable. Hidden variables begin with one or two underscores, and we can list them all using ipython TAB. Type underscore followed by hitting the TAB key, e.g. _[TAB] You should see something like; _ __IPYTHON__ __doc__ _i _ih _2 __IPYTHON__active __import__ _i1 _ii _3 ___ __name__ _i2 _iii _4 __builtin__ __package__ _i3 _oh __ __debug__ _dh _i4 _sh The hidden variable that we are interested in is called __name__. Type; print( __name__ ) You should see the word __main__ printed to the screen. The value of __name__ is the name of the current function or module. The top level module is called __main__. To stop code in our morse.py script from running, we just need to make sure that it is only run if the value of __name__ is __main__. For example, the below script does exactly that; def addArrays(x, y): z = [] for x_, y_ in zip(x, y): z.append(x_ + y_) return z if __name__ == "__main__": # Don't run this code if this script is being # imported as a module a = [ 1, 2, 3, 4 ] b = [ 5, 6, 7, 8 ] c = addArrays(a, b) print(c) Exit ipython and copy and paste the above script into a file called checkmain.py. If you run the script from the command line, e.g. by typing; python checkmain.py then the whole script is executed, and you will see the array [6, 8, 10, 12] printed to the screen. However, if you import the script, then __name__ will not be equal to __main__, and so the code inside the if statement will not be executed. Try this by starting a new ipython session and typing; import checkmain Now you should see that nothing is printed. You can now use the addArrays function in checkmain.py by typing; c = checkmain.addArrays( [1, 2, 3], [4, 5, 6] ) print( c ) which should print the array [5, 7, 9]. As you can see, it is very easy to turn your Python script into a reusable module. You just need to add if __name__ == "__main__": around the code that should only be run when you use the script from the command line. This will allow you to import the script when you want to re-use the functions that you have defined within the script. It is extremely good programming practice to write all of your scripts as if they were modules (and indeed to write all of your code as if they were part of a reusable library). This makes it really easy for you to pick up and reuse all of your code, preventing you from having to continually rewrite the same functionality over and over again. Exercise Edit your morse.py script so that it can be re-used as a module. Do this by adding in an if __name__ == "__main__": check. If you are really stuck, here is an example answer. Make sure you test your script by using import to import it into a new ipython session, and try encoding and decoding the same strings, e.g. try typing; import morse message = "sos we have hit an iceberg" code = morse.encode(message) decode = morse.decode(code) print( message == decode ) This should print True if the decoded form of the encoded message equals the original message (which you would hope it would!).
https://chryswoods.com/intermediate_python/modules.html
CC-MAIN-2018-17
refinedweb
884
72.87
#include <Regexp.h>void setup (){ Serial.begin (115200); Serial.println (); // what we are searching (the target) char newsString [100] = "The quick & fox jumps over & lazy wolf"; // match state object MatchState ms (newsString); ms.GlobalReplace ("&", "'"); // show results Serial.print ("Converted string: "); Serial.println (newsString);} // end of setup void loop () {} char newsString[85]; // make sure this is large enough for the largest string it must hold And yes, the "&" should properly be "&#39;" if (client.connected()) { strcpy_P(buffer, (char*)pgm_read_word(&(string_table[14]))); // "title data=" finder.find(buffer); for (int i = 0; i < randomInt; i++) { if (finder.getString(buffer,"\"", newsString, 84)) { } }++; }} Can I see the whole thing please? Mine works, yours doesn't. But the news item is not clean text. It occasionally has "smart quotes" in it. These appear in the feed as "&amp;#39;" in the displayed feed. I want to replace the ugliness with a simple quote, '.So, after searching high and low for a reliable replace function, I stumbled on the one right under my nose: String.replace.However, the feed is dumped into char newsString[]. Sorry to be thick about it, but it's not clear to me what you need. You're asking me for how newsString is defined, but I've posted that twice, which makes me think I'm not interpreting your questions correctly. MatchState ms (newsString); ms.Target (newsString); Back to the start. It has been my experience that the material downloaded from the net has far too many characters to be saved in total to a string on an arduino. Have you been able to capture all that is downloaded into a single string? Please enter a valid email to subscribe We need to confirm your email address. To complete the subscription, please click the link in the Thank you for subscribing! Arduino via Egeo 16 Torino, 10131 Italy
http://forum.arduino.cc/index.php?topic=62260.0;prev_next=prev
CC-MAIN-2015-22
refinedweb
306
77.03
Once you've decided on names, creating the child domains is easy. But first, you've got to or not to delegate it. It doesn't make sense to delegate a subdomain to an entity that doesn't manage its own hosts or networks. For example, in a large corporation, the personnel department probably doesn't run its own computers: IT (Information Technology) department manages them. So while you may want to create a subdomain for personnel, delegating management for that subdomain to them is probably wasted effort. You can create a subdomain without delegating it, however. How? By creating resource records that refer to the subdomain within the parent's zone. Say one day a group of students approaches us, asking for a DNS entry for a web server for student home pages. The name they'd like is. You might think that we'd need to create a new zone, students.movie.edu, and delegate to it from the movie.edu zone. Well, that's one way to do it, but it's easier to create an A record for in the movie.edu zone. We find that few people realize this is perfectly legal. You don't need a new zone for each new level in the namespace. A new zone would make sense if the students were going to run students.movie.edu by themselves and wanted to administer their own name servers. But they just want one A record, so creating a whole new zone is more work than necessary. It's easy to add this record with the DNS console. First create a students.movie.edu subdomain in the movie.edu zone, then add the A record. To create the subdomain, right-click on the zone in the left pane and select New Domain. You'll see a window like the one shown in Figure 10-1. Enter the name of the new subdomain. You don't need to append movie.edu?the DNS console knows what you mean. You'll then see a folder icon for the new domain in the DNS console, as shown in Figure 10-2. To enter the A record, just select the students folder and follow the procedures described previously to add a new host. In fact, you can even skip the Add Domain step and use the Add Host (A) function to add the host's address record and implicitly create the students.movie.edu subdomain (if it hasn't already been created). Just specify in the Name field and voila! You've created an address for. Now users can access to get to the students' home pages. We could make this setup especially convenient for students by adding students.movie.edu to their PCs' or workstations' search lists; they'd need to type only www as the URL to get to the right host. Did you notice there's no SOA record for students.movie.edu? There's no need for one since the movie.edu SOA record indicates the start of authority for the entire movie.edu zone. Since there's no delegation to students.movie.edu, it's part of the movie.edu zone. If you decide to delegate your subdomains?to send your children out into the world, as it were?you'll need to do things a little differently. We're in the process of doing it now, so you can follow along with us. We need to create a new subdomain of movie.edu for our special-effects lab. We've chosen the name fx.movie.edu?short, recognizable, unambiguous. Because we're delegating fx.movie.edu to administrators in the lab, it'll be a separate zone. The hosts bladerunner and outland, both within the special-effects lab, will serve as the zone's name servers (bladerunner will serve as the primary master). We've chosen to run two name servers for the zone for redundancy?a single fx.movie.edu name server would be a single point of failure that could effectively isolate the entire special-effects lab. Since there aren't many hosts in the lab, though, two name servers should be enough. The special-effects lab is on movie.edu's new 192.253.254/24 network. Here are the partial contents of First, we make sure the Microsoft DNS Server is installed on the new server, bladerunner. Then we create the new zone fx.movie.edu on bladerunner using the process described in the section "Creating a New Zone" in Chapter 4. We also create the corresponding in-addr.arpa zone, 254.253.192.in-addr.arpa. Next, we populate the zone with all the hosts from our snippet of HOSTS, making sure the DNS console automatically adds the PTR records that correspond to our A records. We then add MX records for all of our hosts, pointing to starwars.fx.movie.edu and wormhole.movie.edu, at preferences 10 and 100, respectively. The zone datafile we end up with, called fx.movie.edu.dns, looks like this: ; ; Database file fx.movie.edu.dns for fx.movie.edu zone. ; Zone version: 22 ; @ IN SOA bladerunner.fx.movie.edu. administrator.fx.movie.edu. ( 22 ; serial number 900 ; refresh 600 ; retry 86400 ; expire 3600 ) ; default TTL ; ; Zone NS records ; @ NS bladerunner.fx.movie.edu. @ NS outland.fx.movie.edu. ; ; Zone records ; @ MX 100 wormhole.movie.edu. @ MX 10 starwars.fx.movie.edu. bladerunner A 192.253.254.2 MX 100 wormhole.movie.edu. MX 10 starwars.fx.movie.edu. empire A 192.253.254.5 MX 100 wormhole.movie.edu. MX 10 starwars.fx.movie.edu. jedi A 192.253.254.6 MX 10 starwars.fx.movie.edu. MX 100 wormhole.movie.edu. outland A 192.253.254.3 MX 100 starwars.fx.movie.edu. MX 10 starwars.fx.movie.edu. starwars A 192.253.254.4 MX 100 wormhole.movie.edu. MX 10 starwars.fx.movie.edu. Note that we added an NS record for outland.fx.movie.edu even though we didn't strictly need to: the DNS console would have added it for us when we added outland as a secondary. But adding the NS record lets us restrict zone transfers to name servers listed in NS records and still set up the secondary on outland. We'll do this for the reverse-mapping zone, too. The 254.253.192.in-addr.arpa.dns file ends up looking like this: ; ; Database file 254.253.192.in-addr.arpa.dns for 254.253.192.in-addr.arpa zone. ; Zone version: 14 ; @ IN SOA bladerunner.fx.movie.edu. administrator.fx.movie.edu. ( 14 ; serial number 900 ; refresh 600 ; retry 86400 ; expire 3600 ) ; default TTL ; ; Zone NS records ; @ NS bladerunner.fx.movie.edu. bladerunner.fx.movie.edu. A 192.253.254.2 @ NS outland.fx.movie.edu. outland.fx.movie.edu. A 192.253.254.3 ; ; Zone records ; 1 PTR movie-gw.movie.edu. 2 PTR bladerunner.fx.movie.edu. 3 PTR outland.fx.movie.edu. 4 PTR starwars.fx.movie.edu. 5 PTR empire.fx.movie.edu. 6 PTR jedi.fx.movie.edu. Notice that the PTR record for 1.254.253.192.in-addr.arpa points to movie-gw.movie.edu. That's intentional. The router connects to the other movie.edu networks, so it really doesn't belong in fx.movie.edu. There's no requirement that all the PTR records in 254.253.192.in-addr.arpa map into a single zone, although they should correspond to the canonical names for those hosts. Now we need to configure bladerunner's resolver. Following the directions in Chapter 6, we configure bladerunner to send queries to its own IP address. Then we set bladerunner's domain to fx.movie.edu. Now we'll use nslookup to look up a few hosts in fx.movie.edu and in 254.253.192.in-addr.arpa: C:\> nslookup Default Server: bladerunner.fx.movie.edu Address: 192.253.254.2 > jedi Server: bladerunner.fx.movie.edu Address: 192.253.254.2 Name: jedi.fx.movie.edu Address: 192.253.254.6 > set type=mx > empire Server: bladerunner.fx.movie.edu Address: 192.253.254.2 empire.fx.movie.edu MX preference = 10, mail exchanger = starwars.fx.movie.edu empire.fx.movie.edu MX preference = 100, mail exchanger = wormhole.movie.edu starwars.fx.movie.edu internet address = 192.253.254.4 > ls fx.movie.edu [bladerunner.fx.movie.edu] fx.movie.edu. NS server = bladerunner.fx.movie.edu fx.movie.edu. NS server = outland.fx.movie.edu bladerunner A 192.253.254.2 empire A 192.253.254.5 jedi A 192.253.254.6 outland A 192.253.254.3 starwars A 192.253.254.4 > set type=ptr > 192.253.254.3 Server: bladerunner.fx.movie.edu Address: 192.253.254.2 3.254.253.192.in-addr.arpa name = outland.fx.movie.edu > ls 254.253.192.in-addr.arpa [bladerunner.fx.movie.edu] 254.253.192.in-addr.arpa. NS server = bladerunner.fx.movie.edu 254.253.192.in-addr.arpa. NS server = outland.fx.movie.edu 1 PTR host = movie-gw.movie.edu 2 PTR host = bladerunner.fx.movie.edu 3 PTR host = outland.fx.movie.edu 4 PTR host = starwars.fx.movie.edu 5 PTR host = empire.fx.movie.edu 6 PTR host = jedi.fx.movie.edu > exit The output looks reasonable, so it's safe to set up a secondary name server for fx.movie.edu and then delegate fx.movie.edu from movie.edu. Setting up the secondary name server for fx.movie.edu is simple: use the DNS console to add outland as a new server, then add two secondary zones, according to the instructions in Chapter 4. Like bladerunner, outland's resolver will point to the local name server, and we'll configure the local domain to be fx.movie.edu. All that's left now is to delegate the fx.movie.edu subdomain to the new fx.movie.edu name servers on bladerunner and outland. Right-click on the parent domain, movie.edu, in the left pane and choose New Delegation, which starts the New Delegation Wizard. Click Next in the welcome screen to display a screen like the one shown in Figure 10-3. The first step is entering the name of the delegated subdomain, which we've done. Click Next and you'll be presented with a window to choose the name servers to host (i.e., be authoritative for) the delegated zone. Our two servers are bladerunner.fx.movie.edu and outland.fx.movie.edu, so we enter the appropriate information by clicking Add (we have to run through the add process twice, once for each name server), resulting in a window like Figure 10-4. The final window of the wizard is just for confirmation, so we won't bother to show it. Click Finish and you've delegated a zone. The DNS console adds a special gray icon for delegated zones; if you select this icon, you'll see the NS records added by the wizard. These records perform the actual delegation. A sample DNS console view showing the fx.movie.edu delegation appears in Figure 10-5. According to RFC 1034, the domain names in the resource record-specific portion (the "right side") of the bladerunner.fx.movie.edu and outland.fx.movie.edu NS records must be the canonical domain names for the name servers. A remote name server following delegation expects to find one or more address records attached to that domain name, not an alias (CNAME) record. Actually, the RFC extends this restriction to any type of resource record that includes a domain name as its value?all must specify the canonical domain name. These two records alone aren't enough, though. Do you see the problem? How can a name server outside of fx.movie.edu look up information within fx.movie.edu? Well, a movie.edu name server would refer it to the name servers authoritative for fx.movie.edu, right? That's true, but the NS records in movie.edu give only the names of the fx.movie.edu name servers. The foreign name server needs the IP addresses of the fx.movie.edu name servers in order to send queries to them. Who can give it those addresses? Only the fx.movie.edu name servers. A real chicken-and-egg problem! The solution is to include the addresses of the fx.movie.edu name servers in movie.edu. Although these aren't strictly part of the movie.edu zone, delegation to fx.movie.edu won't work without them. Of course, if the name servers for fx.movie.edu weren't within fx.movie.edu, these addresses?called glue records?wouldn't be necessary. A foreign name server would be able to find the address it needed by querying other name servers. We don't have to worry about adding these records, though?the New Delegation Wizard takes care of it for us. Also, remember to keep the glue up-to-date. If bladerunner gets a new network interface, and hence another IP address, you'll need to update the glue data. The DNS console doesn't let you edit the glue records directly, though. You have use the name server modification window. With the DNS console showing a view like Figure 10-5, double-click on an NS record in the right pane to produce a window like the one shown in Figure 10-6. If fx.movie.edu's delegation changes?i.e., a name server gets added or deleted or a name server's IP address changes?use the Add, Edit, or Remove buttons to make the appropriate changes. We might also want to include aliases for any hosts moving into fx.movie.edu from movie.edu. For example, if we move plan9.movie.edu, a server with an important library of public-domain special-effects algorithms, into fx.movie.edu, we should create an alias under movie.edu pointing the old domain name to the new one. In the zone datafile, the record would look like this: plan9 IN CNAME plan9.fx.movie.edu. This will allow people outside of movie.edu to reach plan9 even though they're using its old domain name, plan9.movie.edu. Don't get confused about the zone in which this alias belongs. The plan9 alias record is actually in the movie.edu zone, so it belongs in the file movie.edu.dns. An alias pointing p9.fx.movie.edu to plan9.fx.movie.edu, on the other hand, is in the fx.movie.edu zone and belongs in fx.movie.edu.dns. We almost forgot to delegate the 254.253.192.in-addr.arpa zone! This is a little trickier than delegating fx.movie.edu because we don't manage the parent zone. First, we need to figure out what 254.253.192.in-addr.arpa's parent zone is and who runs it. Figuring this out may take some sleuthing; we covered how to do this in Chapter 3. As it turns out, the 192.in-addr.arpa zone is 254.253.192.in-addr.arpa's parent. And, if you think about it, that makes sense. There's no reason for the administrators of 192.in-addr.arpa to delegate 253.192.in-addr.arpa to a separate authority because, unless 192.253/16 is all one big CIDR block, networks like 192.253.253/24 and 192.253.254/24 don't have anything in common with each other. They may be managed by totally unrelated organizations. To find out who runs 192.in-addr.arpa, we can use nslookup or whois, as we demonstrated in Chapter 3. Here's how we'd use nslookup to find the administrator: C:\> nslookup Default Server: bladerunner.fx.movie.edu Address: 192.253.254.2 > set type=soa > set norecurse > 253.192.in-addr.arpa. Server: bladerunner.fx.movie.edu Address: 192.253.254.2 192.in-addr.arpa primary name server = arrowroot.arin.net responsible mail addr = bind.arin.net serial = 2003070219 refresh = 1800 (30 mins) retry = 900 (15 mins) expire = 691200 (8 days) default TTL = 10800 (3 hours) > So ARIN is responsible for 192.in-addr.arpa. (Remember them from Chapter 3?) All that's left is for us to submit the form at to request registration of our reverse-mapping zone. If the special-effects lab gets big enough, it may make sense to put a movie.edu secondary somewhere on the 192.253.254/24 network. That way, a larger proportion of DNS queries from fx.movie.edu hosts can be answered locally. It seems logical to make one of the existing fx.movie.edu name servers into a movie.edu secondary, too?that way, we can make better use of an existing name server instead of setting up a brand-new name server. We've decided to make bladerunner a secondary for movie.edu. This won't interfere with bladerunner's primary mission as the primary master name server for fx.movie.edu. A single name server, given enough memory, can be authoritative for literally thousands of zones. One name server can load some zones as a primary master and others as a secondary.[1] [1] Clearly, though, a name server can't be both the primary master and a secondary for a single zone. The name server gets the data for a given zone either from a local zone datafile (and is a primary master for the zone) or from another name server (and is a secondary for the zone). The configuration change is simple: we use the DNS console to add a secondary zone to bladerunner and tell bladerunner to get the movie.edu zone data from terminator's IP address, per the instructions in Chapter 4.
http://etutorials.org/Server+Administration/dns+windows+server/Chapter+10.+Parenting/10.4+How+to+Become+a+Parent+Creating+Subdomains/
CC-MAIN-2018-30
refinedweb
2,988
71
Important: Please read the Qt Code of Conduct - std::reduce not known with C++17 enabled - Asperamanca last edited by I have a large project in Creator, configured to use Qt 5.15.1 with MinGW 8.1.0 64bit. The project files has CONFIG += c++17 However, Creator shows a semantic issue no member named 'reduce' in namespace 'std' Any ideas what I could try? - Christian Ehrlicher Lifetime Qt Champion last edited by @Asperamanca said in std::reduce not known with C++17 enabled: However, Creator shows a semantic issue QtCreator or the compiler? - Asperamanca last edited by @Christian-Ehrlicher QtCreator. Probably from the clang backend However, the selected kit is relevant, because switching to MSVC-based toolchain makes the semantic issue disappear. I have wondered whether a) Enabling c++17 for MinGW isn't that straightforward (been there in the past, but can't remember the details) b) The MinGW shipped with Qt 5.15.1 isn't fully c++17 compliant (I'd love to check the MinGW docs, but they are a right mess - there's nothing like an easy-to-find release notes list for version)
https://forum.qt.io/topic/119335/std-reduce-not-known-with-c-17-enabled
CC-MAIN-2022-05
refinedweb
191
58.52
reactotron ReactotronReactotron Control, monitor, and instrument your React DOM and React Native apps. From the comfort of your TTY. Platforms SupportedPlatforms Supported - React Native 0.23+ - React DOM 15+ - React Native Web 0.0.15+ Great ForGreat For - sending logging commands as text or objects - relaying all redbox errors and yellowbox warnings - watching the flow of actions as they get dispatched - tracking performance of each action watching for hotspots - querying your global state like a database - subscribing to values in your state and be notified when they change - dispatching your custom actions - watching your HTTP calls to servers and track timing RequirementsRequirements - Node 4.x+ - Abnormal love for all things console InstallingInstalling npm install reactotron --save-dev Running The ServerRunning The Server node_modules/.bin/reactotron Might be worth creating an alias or adding it to your script section of your package.json. How To UseHow To Use To use this, you need to add a few lines of code to your app. Depending on how much support you'd like, there's a few different places you'll want to hook in. Entry Point (required)Entry Point (required) ProvidesProvides - sending logging commands as text or objects - relaying all redbox errors and yellowbox warnings How To HookHow To Hook If you have index.ios.js or index.android.js, you can place this code somewhere near the top: // connect with defaultsReactotron// Connect with optionsconst options =name: 'React Web' // Display name of the clientserver: 'localhost' // IP of the server to connect toport: 3334 // Port of the server to connect to (default: 3334)enabled: true // Whether or not Reactotron should be enabled.secure: false // Are you piggybacking on HTTP or HTTPS (default: false)Reactotron I'd recommend using the following for connect in React Native so that release builds will disable reactotron. Reactotron Ensure connect() Happens First It is important that your Reactotron.connect() happens before your redux store gets created. Especially if you're using the {enabled: false} option. To make this happen, you can create a ReactotronConfig.js file and import that as your first import in the entry point of your application. Check out the 3 projects under examples to see that in action. Redux Middleware (optional)Redux Middleware (optional) ProvidesProvides - watching the flow of actions as they get dispatched - tracking performance of each action watching for hotspots Hook To HookHook To Hook // wherever you create your Redux store, add the Reactotron middleware:const store =// Or you can use the Reactotron storeEnhancer!const enhancer =const store = Redux Store (optional)Redux Store (optional) ProvidesProvides - querying your global state like a database - subscribing to values in your state and be notified when they change - dispatching your custom actions How To HookHow To Hook // wherever you create your Redux storeconst store = // however you create your storeReactotron // <--- here i am!// If you're using the Reactotron.storeEnhance(), it's already// setup for you! API Tracking (optional)API Tracking (optional) ProvidesProvides How To HookHow To Hook // wherever you create your API// with your existing api object, add a monitorapi Other FeaturesOther Features LogLog Call Reactotron.log() and pass a string or object to have it log. Emojis are supported. BenchBench You can use Reactotron for unscientific benchmarks. const bench = Reactotronbench You can also register steps if you're timing a sequence. const bench = Reactotronbenchbenchbench TipsTips Using On A DeviceUsing On A Device When you initialize the reactotron you can tell it the server location when you connect: Reactotron.connect({server: '10.0.1.109'}) Useful shortcutsUseful shortcuts You can clear your reactotron by hitting backspace/delete OR you can insert a separator by pressing the "-" key. For some commands, like dispatching an action, you can repeat previous by pressing the "." key. Getting InvolvedGetting Involved PRs and bug reports are welcome! You want to start extending this? Run the console programRun the console program cd src npm install npm start Pick an example app and run itPick an example app and run it cd examples/ReactNativeExample npm install cp ../../src/client/client.js . react-native run-ios Then hack around. Hack around. Hack up hack up and hack down. Be sure to read the silly examples/README.md file for more details. WishlistWishlist - Get the vocab right (current everything is a "command") - Refactor clients to organize commands - Allow commands to be extended on client & server - Allow a .reactotron sub-folder for project-specific things - Does router need to exist anymore? - Api size metrics - Pages for logging - Show what the profile shows - Track saga effect chains - Provide a way to drive the navigator - Allow simple scripts to be written that send commands - Strategy for dealing with multiple apps connecting Random PicsRandom Pics Special ThanksSpecial Thanks A shout out to my teammates at Infinite Red who encourage this type of open-source hacking & sharing. Also, to Kevin VanGelder, who spawned the idea for this library by saying, "Hey, you know what would be cool? A REPL. We should do that." Change LogChange Log See the full CHANGES.md file.
https://www.npmjs.com/package/reactotron
CC-MAIN-2018-34
refinedweb
831
53.51
Introduction: Twitter and the Arduino Yún After spending almost $100 on an Arduino Yún to see what the fuss was about, it seemed like a good idea to find and demonstrate some uses for it. So in this article we’ll examine how your Yún can send a tweet using some simple example sketches – and the first of several Arduino Yún-specific tutorials., if you don’t have a twitter account – go get one. Step 1: Sending a Tweet From Your Yún Sending a tweet from your Yún Thanks to Arduino and Temboo, 99% of the work is already done for you. To send a tweet requires the Arduino sketch, a header file with your Temboo account details, and also the need to register an application in the twitter development console. Don’t panic, just follow the “Get Set Up” instructions from the following page. When you do – make sure you’re logged into the Temboo website, as it will then populate the header file with your Temboo details for you. During the twitter application stage, don’t forget to save your OAuth settings which will appear in the “OAuth Tool” tab in the twitter developer page, for example in the image above. These settings are then copied into every sketch starting from the line: constStringTWITTER_ACCESS_TOKEN= When you save the sketch, make sure you place the header file with the name TembooAccount.h in the same folder as your sketch. You know this has been successful when opening the sketch, as you will see the header file in a second tab, for example in the second image in this step. Finally, if you’re sharing code with others, remove your OAuth and TembooAccount.h details otherwise they can send tweets on your behalf. Step 2: Did It Work? OK – enough warnings. If you’ve successfully created your Temboo account, got your twitter OAuth details, fed them all into the sketch and header file, then saved (!) and uploaded your sketch to the Arduino Yún - a short tweet will appear on your timeline, for example in the first image above. If nothing appears on your twitter feed, open the serial monitor in the IDE and see what messages appear. It will feed back to you the error message from twitter, which generally indicates the problem. Step 3: Sending Your Own Data As a Tweet Moving on, let’s examine how to send tweets with your own information. In the following example sketch we send the value resulting from analogRead(0) and text combined together in one line. Don’t forget twitter messages (tweets) have a maximum length of 140 characters. We’ve moved all the tweet-sending into one function tweet(), which you can then call from your sketch when required – upon an event and so on. The text and data to send is combined into a String in line 26. ------------------------------------------------------------------------------------------------------------------------------------------------- #include <Bridge.h> #include <Temboo.h> #include "TembooAccount.h" // contains Temboo account information // as described in the footer comment below const String TWITTER_ACCESS_TOKEN = "aaaa"; const String TWITTER_ACCESS_TOKEN_SECRET = "bbbb"; const String TWITTER_CONSUMER_KEY = "ccccc"; const String TWITTER_CONSUMER_SECRET = "dddd"; int analogZero; void setup() { Serial.begin(9600); delay(4000); while(!Serial); Bridge.begin(); } void tweet() { Serial.println("Running tweet() function"); // define the text of the tweet we want to send String tweetText("The value of A0 is " + String(analogZero) + ". Hooray for twitter"); TembooChoreo StatusesUpdateChoreo; // invoke the Temboo client // NOTE that the client must be reinvoked, and repopulated with // appropriate arguments, each time its run() method is called. StatusesUpdateChoreo.begin(); // set Temboo account credentials StatusesUpdateChoreo.setAccountName(TEMBOO_ACCOUNT); StatusesUpdateChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME); StatusesUpdateChoreo.setAppKey(TEMBOO_APP_KEY); // identify the Temboo Library choreo to run (Twitter > Tweets > StatusesUpdate) StatusesUpdateChoreo.setChoreo("/Library/Twitter/Tweets/StatusesUpdate"); // add the Twitter account information StatusesUpdateChoreo.addInput("AccessToken", TWITTER_ACCESS_TOKEN); StatusesUpdateChoreo.addInput("AccessTokenSecret", TWITTER_ACCESS_TOKEN_SECRET); StatusesUpdateChoreo.addInput("ConsumerKey", TWITTER_CONSUMER_KEY); StatusesUpdateChoreo.addInput("ConsumerSecret", TWITTER_CONSUMER_SECRET); // and the tweet we want to send StatusesUpdateChoreo.addInput("StatusUpdate", tweetText); // tell the Process to run and wait for the results. The // return code (returnCode) will tell us whether the Temboo client // was able to send our request to the Temboo servers unsigned int returnCode = StatusesUpdateChoreo.run(); // a return code of zero (0) means everything worked if (returnCode == 0) { Serial.println("Success! Tweet sent!"); } else { // a non-zero return code means there was an error // read and print the error message while (StatusesUpdateChoreo.available()) { char c = StatusesUpdateChoreo.read(); Serial.print(c); } } StatusesUpdateChoreo.close(); // do nothing for the next 90 seconds Serial.println("Waiting..."); delay(90000); } void loop() { // get some data from A0. analogZero=analogRead(0); tweet(); do {} while (1); // do nothing } --------------------------------------------------------------------------------------------------------------------------------------- Which results with the following example tweet shown in the image above. With the previous example sketch you can build your own functionality around the tweet() function to send data when required. Recall that the data to send as a tweet is combined into a String at line 26. Please note that you can’t blast out tweets like a machine, for two reasons – one, twitter doesn’t like rapid automated tweeting – and two, you only get 1000 free calls on your Temboo account per month. If you need more, the account needs to be upgraded at a cost. Conclusion Well the Yún gives us another way to send data out via twitter. It wasn’t the cheapest way of doing so, however it was quite simple. And thus the trade-off with the Arduino platform – simplicity vs. price. Stay tuned for more tutorials. And if you’re interested in learning more about Arduino, or want to introduce someone else to the interesting world of Arduino – check out my book (now in a third printing!) “Arduino Workshop” from No Starch Press. Recommendations We have a be nice policy. Please be positive and constructive. should I get a yun?
http://www.instructables.com/id/twitter-and-the-Arduino-Y%C3%BAn/
CC-MAIN-2018-26
refinedweb
953
56.25
The Wikipedians Who Make it Happen 236 Phoe6 writes "Many of us might have wondered who these crazy people are, spending lot of time at wikipedia and presenting us with such an invaluable information. Wired has decided to give some credits to the most active wikipedians, in their article titled Wiki becomes a way of life" Quality! (Score:5, Insightful) Good to see that a few of these people are getting the recognition that they deserve! Re:Quality! (Score:5, Funny) but then (Score:3, Interesting) Instead we are seen as this kind of human wave that takes down websites. Maybe it's more eligatarian this way. because we don't (Score:5, Insightful) Good for them (Score:4, Interesting) Re:Good for them (Score:3, Funny) Re:Good for them (Score:2) Yikes. (Score:5, Funny) "...It's a good thing I don't have friends - then I wouldn't be able to do this!" Re:Yikes. (Score:3, Insightful) You read a text book from the index end first! perhaps he should have said... (Score:5, Funny) Re:perhaps he should have said... (Score:3, Insightful) I have one thing to say... (Score:5, Funny) Wouldnt it be ironic, if the OCD wiki, was edited, relentlessly? Re:I have one thing to say... (Score:5, Funny) Re:I have one thing to say... (Score:2) These are good values to have. The comma separated values, i mean. Re:I have one thing to say... (Score:3, Funny) He's here! (Score:2) TwistedSquare is William F'n Shatner! Re:I have one thing to say... (Score:2) Wikipedia has flaws, but its a truly worthwhile proyect. Re:I have one thing to say... (Score:2) No. Irony [wiktionary.org] would be if it was never edited. Stephen Re:I have one thing to say... (Score:2) Apparently he had OCD. It's all just one big fraud (Score:5, Funny) Link to the first page... (Score:5, Informative) The link in the post goes to page two for me WTF? Why would you /. Wikipedia? (Score:3, Interesting) Don't worry, Slashdotting is insignificant... (Score:5, Insightful) Now, how many places can honestly say that a Slashdotting is insignificant (ducking from CmdrTaco)?:-) Well, we do get spikes, they just don't hurt (Score:5, Informative) On the Slashdot/RSS thing, RSS is getting quite a reputaton for really unpleasant surge loads. Something we're factoring in to anything we doing relation to RSS, designing for caching. Not really a surprise if Slashdot has had to do some tweaking. We were suffering a bit today from the combination of Slashdot, Wired News (Wikipedia Becomes a Way of Life [wired.com]) and Spiegel Online with an overloaded image server. Image server was bouncing around 100% utilization, kept some pages in the queue too long and that hurt overall apache capacity. We've seen far worse and we're getting rid of that bottleneck. As a temporary measure we've asked people to remove some pretty but not content images from a few places. Won't last long, though. On the fund-raising side, the drive ended early after exceeding its $75,000 target. It's currently at around $95,000 probably with some data still to arrive, close to reaching $100,000, my initial thought of a target. Really good news for those of us doing the capacity and reliability work but it'll take a few months for it to be visible. Thanks to everyone here who helped! Anyone who wants to spend a bit of money on another useful project might consider sending a bit to Freenode.net [freenode.net], the IRC host. Among other things they host our channels, including our offsite 24/7 IRC NOC and a superb MySQL channel, regularly inhabited by MySQL employees. Providing good service to lots of other open source projects. Re:WTF? Why would you /. Wikipedia? (Score:4, Informative) maybe it has happened in the past but wikipedia hardly notices its a noticeable but small blip in the squids traffic to the squids and pretty much nothing at all beyond that there are two types of slashdotting: 1: bandwidth slashdotting: wikipedia has a gigabit link that is not exactly heavilly utilised so this just isn't going to happen. 2: server load slashdotting: (that is where a badly designed dynamic site can't keep up) squid pretty much takes care of making sure this doesn't happen (/.ers are very much a flash crowd they come they mostly view the same pages and then they go again if your site does seperate dynamic rendering for every pageview with no caching you are in trouble) the main reason the wikipedia has had problems (power currupts power failure currupts absoloutely) and more recently some problems related to the software keeping transactions open too long whilst purging the squids and to a lesser extent hardware shortages. HOWEVER bandwidth and I love the wikipedia, (Score:5, Interesting) And before you flame on, I DID send a donation. Re:I love the wikipedia, (Score:5, Informative) Bandwidth isn't the problem (or the cost, really), but the servers. We spend $4k-ish a month on bandwidth (off the top of my head; ICBW), but we spent about $65k in just the last 6 months on servers (see the server list [wikimedia.org]). BTW, we prefer that people just call it "Wikipedia", without a definite article. Re:I love the wikipedia, (Score:2) Re:I love the wikipedia, (Score:2) Some interview! -- Wired needs to be a wiki (Score:2, Informative) Hey wired, good job on your homework! Contribute. But don't be an obsessive fixer (Score:5, Insightful) Be there. Contribute. But learn to read what others have to say. Let wikis evolve the way they are supposed to be. It's a website. Re:Contribute. But don't be an obsessive fixer (Score:2) Kudos (Score:5, Funny) I give up. (Score:2, Insightful) Still wondering who these crazy people are (Score:5, Insightful) Not meaning to be critical, but the article cited does not explain who these crazy people are. I don't exactly know whom the article is targeting at an audience, in fact. It publish a list of usernames with the number of submissions, along with brief snippets about two specific users. I was hoping to learn more about the actual type of person who is contributing, demographically. I realize this would have taken a lot of work and might even be impossible, but would have made a hell of a lot better article. :-) Easy for me to say, from the comfort of my office. Re:Still wondering who these crazy people are (Score:2, Informative) Re:Still wondering who these crazy people are (Score:3, Informative) who is these are (Score:4, Funny) Heck. Where's the [edit] link to correct the typo? Can't wait for the wiki version of Hmm. /. wiki Er Slashdot Conspiracy (Score:5, Funny) Talking about the beginning of Wikipedia, I realized that this was posted on slashdot. Not long ago, I discovered that a moderator on slashdot was named Samzenpus, who is the second cousin twice removed of Snagglepus [slashdot.org] Well Snagglepus is famous for saying "Heavens to Mergatroid [freeserve.co.uk] Mergatroid was the sister of a guy in a band called Newcleus [discogs.com] The guy just happens to say [weddingvendors.com], and I quote: this song came out in the early eighties - a Paradox (how could a wiki exist in the eighties before wikis existed?). Cosmos, nucleus, wikis, it all makes sense now. Slashdot may look like an innocent little blog which slashdots servers from time to time, but they are in actuality trying to slashdot the universe Google (Score:2, Redundant) One thing though, it get's damn slow sometimes. Wikipedia should either hook up with google on some webserving or Google should grab a nightly dump and set up pedia.google.com Ignore the idiotic slashdot articles about google trying to take things over and lock things up. Wikipedia is licensed to prevent that, but also to allow sharing, and I'm keeping my fingers crossed they take google up on their hosting offer sooner rather then later Re:Google (Score:2) Wikipedia Link (Score:3, Funny) wikipedia skeptic (Score:4, Insightful) People should use caution when trusting info from there due to the fact that anyone can slip a bit of misinformation in there without anyone noticing for months or years. Re:wikipedia skeptic (Score:3, Insightful) Re:wikipedia skeptic (Score:2, Insightful) Re:wikipedia skeptic (Score:2) Re:wikipedia skeptic (Score:2) Not that I can claim to speak for wikipedians, but I imagine it's the same as most open-source projects: we need participants, not mere users. If you're looking for a product, any number of companies will sell you a fine product. If you want to be part of something, jump on board. That's the wiki way, the open source way. Re:wikipedia skeptic (Score:2) But frankly, I'd be sad to see the well-meaning efforts of so many people spent on a social experiment, because there is a lot of great stuff on Wikipedia; it's just that when you have Re:wikipedia skeptic (Score:2) Although 99.5% of the information is accurate. Researchers need to go beyond wikipedia articles to better ascertain the validity of its information. It's a good starting point. There is information in wikipedia that would be difficult to obtain without access to a good research library or personal access to an expert, however. It contains a lot of information that could not be found anywhere in a typical public library. Re:wikipedia skeptic (Score:2, Insightful) Re:wikipedia skeptic (Score:4, Insightful) Re:wikipedia skeptic (Score:2) Re:wikipedia skeptic (Score:2) Re:wikipedia skeptic (Score:3, Interesting) I just recently discovered Wikipedia and think it is great! The way I found it was through Trillian [ceruleanstudios.com]. When I am in chat Trillian highlights words that have Wikipedia articles. Once I found it I immediately looked up my favorite subject, beer [realbeer.com]! Like you I found many mistakes. Of course I never completely believe anything I read even from so called experts. I still think it is a great site and project. As far as a teacher letting students use it as a Re:wikipedia skeptic (Score:2) And did you bother to fix any of those errors? Knowledge is democratized? (Score:4, Insightful) So...if Wikipedia had been around way back when... the "world-is-flat" crowd would have edited out the silly "world-is-round" guy, right? This is what keeps me from giving Wikipedia much credibility. I know all publications are in danger of being biased by the writer. However, I can decide to place my trust on that one writer or entity. With Wikipedia, there's no way to know past agendas or the like. Re:Knowledge is democratized? (Score:2) controvercial topics might be dangerous, most articles are trustworthy. That said, you should never use Wikipedia as your sole source for anything that really matters, but for satisfying idle curiosity, Wikipedia is fine. Re:Knowledge is democratized? (Score:3, Interesting) No. The idea that the flat earth theory was ever widely accepted by is a myth. Auguste Compte and others laid the ground work for the "theory" in the 1800s with anti-religious sentiments that overstated the whole idea of "war" between science and religion. The idea that Colombus was opposed by a vast Flat Earth opposition was invented by Washington Irving in his book on Re:Knowledge is democratized? (Score:2) Re:Knowledge is democratized? (Score:2) I was looking for a table of AWG to diameter, which it has. It was the first paragraph that rubbed me the wrong way: Maybe AWG is also used for body piercing sizes (which are wires), but the second sentenc Re:Knowledge is democratized? (Score:3, Interesting) It was the first paragraph that rubbed me the wrong way: ... So, click on the 'Edit' button which was just a few inches away from the text. Insert a phrase that makes the statement more neutral, without removing details others have added. Re:Knowledge is democratized? (Score:2) The opportunity to flame without risk, is all. You hit "[edit]". and you're exposing your work and knowledge to the judgment of others. It's so much safer to just camp and snipe. There are a lot of folks who think wiki is just one huge bedroom, and they're all eunuchs commenting on the participants' lack of sexual skill and style. C'mon, folks, you think you know so much more than us? Prove it; put your brains where Re:Knowledge is democratized? (Score:2) Actually, I did just that. But that misses the OP's point -- the credibility is only as good as the writer, and anyone can be a writer. Wikipedia's own disclaimer sums it up very, very well. Many people will argue things as true, even if it's just their opinion or something they heard. That's why we have and need research and peer review. I think Wikipedia is a great idea, but it is not without problems. Re:Knowledge is democratized? (Score:2, Insightful) I don't see how this is different that a traditional encylopedia. With Wikipedia you can look at the history and see the debate. With a traditional one, you put full trust in an editor. Re:Knowledge is democratized? (Score:2) Both are expressed, Netonian is further listed as the historical view. So all the old people who grew up before Einstein was proven right haven't broken that one at least. Wikipedia doesn't seem concerned by becoming cumbersome if it can express 2 valid and posible viewpoints. Re:Knowledge is democratized? (Score:4, Insightful) No. The Wikipedia article would've said roughly "Many people, including X, Y, Z and believe the Earth is flat, but others (such as A, B, C) believe the Earth is round. Here are the arguments for and against each position." That's the meaning of Wikipedia's NPOV policy. Only if no one believed in a round Earth at all would the viewpoint not be mentioned. Re:Knowledge is democratized? (Score:3, Insightful) If a controversy pops up, usually in the form of edit wars, there are a few mechanisms for calming the issue. Edits toward a NPOV perspective are attempted, temporary suspension of edits to allow interested parties to calm, and a locked edit by some Re:Knowledge is democratized? (Score:2) You probably associate "democracy" with "liberal democracy" and thats the most common definition, but not the only one. Of course, democracy is literally rule by the people. In this instance, you're giving power to the readers of a text to also be the editors in the same way that democracy allows citizens to also participate in the political process. [Slightly OT] On the word "wiki" (Score:2) A moped, in the Indian context, is a 2-wheeled motorized vehicle, usually with a 50cc engine, with a top speed of perhaps 50kmph, and with a mileage that would put any hybrid vehicle to shame (over 100km per litre). It also has a strange design. It looks like a motor Kudos to Citizen Knowledge Patrol (Score:4, Insightful) The first edition of Encyclopedia Britannica came out in 1768; Wikipedia first appeared in 2001; in terms of readership, we know who is kicking whose butt. Updating Articles Feels Good! (Score:5, Insightful) So I added to it what I could... and you know what? It felt GOOD! I hadn't really done anything worthwhile that week, and I felt that I made a great contribution to society! So don't knock it til you try it. There's a great sense of accomplishment in giving knowledge to other people, even if it's something as trivial as finding the best burgers in town. And now I see that someone took away my link to the best burgers in town. I'll fix that. Re:Updating Articles Feels Good! (Score:2) Columbus, OH [wikipedia.org] Columbus [wikitravel.org] I'll have to figure out how to combine that into one. Columbus, OH is better, but the good stuff I added (like where to eat and drink) is in the Columbus one. Re:Updating Articles Feels Good! (Score:2) I think the most important Wikipedians.. (Score:5, Insightful) To be honest though, it really shakes my confidence in Wikipedia articles, I mean how much is actually missed by the policemen? You've got multiple vandalisms from a few well known addresses, it's not a rare problem. A user doing one or two vandalisms in a bunch of legitimate edits is going to, on the whole, escape censure. I really only trust articles which have been locked from editing as they have been validated repeatedly and are immune to the random vandalism that a little looked at page must inevitably gain. Vandalism (Score:4, Insightful) > by the policemen? It's a fact that the quality of Wikipedia will always be uneven -- but so is the quality of our general knowledge: we know some topics in far greater detail than others. This is due to the vagarities of human interest: some topics attract more people & resources than others. This same principle applies to fighting vandalism on Wikipedia. Articles that are importnat will be more closely watched for vandalism than those that are not. For example, if you wanted to write some nonsense about an imaginary or little-known village in Africa or South America, chances are that should it escape notice in the first day or two, this nonsense may persist for months or years. But then, if no one knows about this -- or cares -- what damage does it do? This issue reminds me of the alleged practice of encyclopedia companies long ago, who would create articles about fictional cities or towns in order to catch illegal copying: if no one consults these articles, does it truly harm anyone? Geoff Pffft (Score:2) Discussing Wikinews stories (Score:4, Interesting) I posted a Wikinews story yesterday entitled "CIA Sending Suspects Overseas For 'Rendition' [theworldforum.org]", which received almost 2000 hits due to being displayed on the front page of Google News for most of the day. This helps give Wikinews more readership, since they are not listed in Google News. Sadly, however, it does not result in increased discussion, since most people visiting from Google News are not people interested in posting comments. rambot! (Score:3, Interesting) I must say I appreciate the Jack Kerouac reference in my hometown's article [wikipedia.org], though. Re:rambot! (Score:2) Also, (and I talked with him about this when I met him in person) it's going to be interesting to see what happens in 2010 when the next census data comes out. Why I don't like Wikipedia (Score:3, Insightful) While this is based on my experience with some edits and corrections that I did as an anonymous user, it was disheartening enough that I decided to stop wasting my time on it. I discovered a number of factually incorrect statements on a technical article. I corrected those and wrote the corrections in clear and concise language. For each correction, I provided a solid reference, less than 10 minutes after my extensive corrections had been saved, they had been reverted back to their original state. I figure that if people want to live in ignorance, why waste my time stopping them? Yet there are two things that bother me about Wikipedia: 1) A well-funded "think-tank" could hire a hundred people and have them work on wikipedia for one or two years. Their concerted effort would be enough to distort much of the already contributed materials and they could work in tandem under a veil of anonymity that would allow them to support each other in a way that democracy would appear to be at work. 2) If you read Kuhn, you'll realize that scientific breakthroughs, what he termed "scientific revolutions" often happen by breaking with the established dogma/doctrine/explanandum of the era. Wikipedia's focus on consensus-building and catering to lower-common denominator is bound to favor the common wisdom. 3) Ultimately, real researchers are paid good money for a reason. Getting published in the peer-reviewed journals in any discipline is not easy and ultimately it ensures a certain level of quality control, one which no doubt often brings other problems in its wake such as the fact that many journals also are run by a clique of insiders with an agenda, but even these biases are usually known and accounted for in academic circles. 4) Wikipedia is a fun and would succeed if it would just sell itself as a fun interesting social project. It can even be resourceful at times. Authorative or trustworthy, it is not. Re:Wiki (Score:5, Informative) Re:Wiki (Score:2, Interesting) I am suprised that these entries aren't changing on a minute by minute basis. Everyone wants to write history from their viewpoint." yep. [wikipedia.org] Re:Wiki (Score:2) Nothing? Nothing? Nothing? How about the hundreds of other people watching the article? Ever wonder why the history of some articles say "revert...revert...revert..."? It is a large number of people keeping idiots from vandalizing articles. As for your comment that the everyone wants to write history from their viewpoint, it is t Re:Wiki (Score:2) Re:but.. (Score:4, Insightful) Wikipedia is GFDL. No one can close it. Re:but.. (Score:2, Informative) It's released under the GPL, so anyone caan bring back the free content for free. Re:but.. (Score:3, Informative) Anyone have a torrent of these? Re:but.. (Score:5, Insightful) If any company tried to take control like that, someone else could just fork the content and offer it for free again. Re:but.. (Score:2) Re:Wikipedia is too biased to be useful (Score:3, Informative) [wikipedia.org] Also, there is no "they". Re:Wikipedia is too biased to be useful (Score:5, Informative) Re:Wikipedia is too biased to be useful (Score:2) Re:Wikipedia is too biased to be useful (Score:2, Insightful) I see your point. But that would still be much harder and would take you *much* more time to have such an information added to a regular, old-school-paper-version encyclopedia, you know. No entries on Wikipedia can truly be trusted. Er... that sounds slightly exaggerated, right? Re:Wikipedia is too biased to be useful (Score:2, Informative) It looks like the article [wikipedia.org] was edited by a pesistant vandal, (Sistertina), from a brief look at the edit history [wikipedia.org]. These edits were also reverted (restored to the original version), fairly quickly, as they removed everyone from the list. If there are other edits removing Charles Manson, that don't seem to be by the same person, please post links to the edit history. If not, this looks to be more a case of one isolated idiot, rather than sytematic bias. In any case, Charles Manson is on the list now. I a Re:Wikipedia is too biased to be useful (Score:2, Insightful) / [rotten.com] There is huge outcry whenever anyone tries to make an article "kid-safe", and for good reason. But no, don't trust Wikipedia alone -- same as you don't trust *any other single source* without double-checking. I find it to be less bias Re:The truth (Score:2) Re:I'd be happy if.... (Score:3, Informative) So, about equal to many history and politics textbooks. Wikipedia is a useful first source of information. Research for any project should include a wide variety and decent number of sources. Published encyclopedias are often riddled with errors and out-of-date information. Re:Women (Score:2) Re:Wikipedia should evolve to a Linux like model (Score:2) Re:All Male? (Score:3, Informative) Angela: No. 31. in the main namespace; No. 10. in all namespaces. Morwen: No. 18. in the main namespace; No. 25. in all namespaces. Jengod: No. 21. in the main namespace; No. 27 in all namespaces Dysprosia: No. 24 in the main namespace; No. 32.
https://slashdot.org/story/05/03/08/1419245/the-wikipedians-who-make-it-happen?sdsrc=nextbtmprev
CC-MAIN-2018-05
refinedweb
4,078
64.41
769Views4Replies read and right a text file through batch in python Answered Ok so I have a - batch file named run.choice.bat - text file named choice.txt - text file named python.txt - and a python file named choice.py The batch file contains this code: @echo off set /p c=<"choice.txt" echo %c% choice /c:%c% echo %errorlevel% echo %errorlevel% > python.txt pause The python file contains this code: def choice(keys="yn"): """Choice.com""" import os import time o = open("choice.txt", "wb") o.write(keys); time.sleep(1) os.system("run.choice.bat") i = open("python.txt", "r+") errorlevel=int(i.read(2)) return errorlevel choice(raw_input("choice(")) my problem is that the batch file wont read choice.txt while running in python, on its own it runs fine. can somebody help me fix it? From the Python docs on write: "file.write(str) -- Write a string to the file. There is no return value. Due to buffering, the string may not actually show up in the file until the flush() or close() method is called." Select as Best AnswerUndo Best Answer . Just a guess, but the Python interpreter probably changes the working directory so the the BAT file can't find the data file. Try specifying the complete path to the data file inside the BAT file. Eg, set /p c=<"c:\mydata\choice.txt" Select as Best AnswerUndo Best Answer Thank you for the quick reply. It didn't work got any other Ideas? Select as Best AnswerUndo Best Answer . No. :( Select as Best AnswerUndo Best Answer
http://www.instructables.com/topics/read-and-right-a-text-file-through-batch-in-python/
CC-MAIN-2018-17
refinedweb
263
79.67
First time here? Check out the FAQ! Platform Details: Ubuntu 14.04 LTS Linux Kernel 4.4.0-112-generic ROS Version: Indigo ROS Package: camera_aravis from here - camera_aravis Aravis LIbrary - aravis-0.4.1 from here - . I have also tried version 0.5.11 with same results. aravis-0.4.1 Cameras used (Same behavior with all cameras and all are GigE cameras): Each camera is tested separately and is powered through PoE (Power over Ethernet) and the Ethernet packet size has been set to 9000 MTU. Command to run after compiling the package: rosrun camera_aravis camera_node rosrun camera_aravis camera_node The node then detects the camera and can print the device ID and also can access Vendor name and other camera specific parameters with Aravis API's. However, the call to arv_camera_new() in src/camera_nodelet.cpp returns NULL or doesn't return at all (hangs). arv_camera_new() After trying different debugging methods, I narrowed down the issue to Nodelet manager in src/camera_node.cpp. In the modified camera_node.cpp below, the arv_camera_new() function can detect the camera and return a camera object. #include <ros/ros.h> #include <nodelet/loader.h> #include <camera_aravis/camera_nodelet.h> int main(int argc, char** argv) { ros::init(argc, argv, "camera_node"); //nodelet::Loader manager(true); //nodelet::M_string remappings; //nodelet::V_string my_argv; arv_update_device_list(); printf("Devices: %d\n", arv_get_n_devices()); ArvCamera *pCamera = arv_camera_new(NULL); if(pCamera){ printf("Device Opened: %s\n",arv_camera_get_vendor_name(pCamera)); } else{ printf("Device couldn't be opened\n"); } //manager.load(ros::this_node::getName(), "camera_aravis/CameraNodelet", remappings, my_argv); ros::spin(); } As you can see, I have commented out the Nodelet Manager and directly calling the Aravis APIs to access the camera. I also wrote a separate non-ROS C++ program to use Aravis API's and can access the camera without any issues. Further more, the test scripts provided within aravis library (Ex: tools/arvcameratest.c) work fine and can connect and stream data from the cameras. So, the symptoms can be bolied down to arv_camera_new() and arv_open_device() (may be other similar APIs which I haven't tested) can find the camera directly in the node, but not when called within the nodelet. Another thing to note is that, other API's such as arv_get_n_devices(), arv_get_device_id() work fine in both node and nodelet. arv_open_device() arv_get_n_devices() arv_get_device_id() I have reproduced the issue with two machines with same platform and software versions mentioned above. Note that the code is directly taken from the camera_aravis github repo mentioned above and modifications are only done to camera_node.cpp as shown above while debugging. What might be going wrong? Anyone experienced similar issues with this package? Any help in debugging would be greatly appreciated. EDIT: After digging deeper into Aravis library(0.4.1) and glib (v2.0), I found out that the function g_regex_split behaves differently for a node and nodelet implementation. Below is the function call to g_regex_split in arvgvdevice.c g_regex_split arvgvdevice.c tokens = g_regex_split (arv_gv_device_get_url_regex (), filename, 0); For the filename string - local:GV-527xFA-C_1_3_120.zip;70000000;3fd0, the tokens after ... (more) local:GV-527xFA-C_1_3_120.zip;70000000;3fd0 tokens YUV422 Rectification messes up the colors Hi, I have an image topic camera/image_color which has images streaming with So, did you have a workaround for this issue in Ubuntu 14.04? What was your solution? Do you know why the "regex_split.c" test script was created in your package repo? Did you face a similar issue? Thanks. Even with the updated camera_aravis pkg, the issues exists since the problem is with glib as I have mentioned in arv_camera_new() doesn't open the camera when called within a nodelet Platform Details: Ubuntu 14.04 LTS Linux Kernel 4 @Link, please check the edit to the question details. Actually that folder is empty. Nothing related to aravis is in /usr Got this : /usr/local/share/doc/aravis I first tested with 0.5.11 and it didn't work. So, I switched to 0.4 and I have been using that now for most of my debug Thanks for the response. Yes, as mentioned in the question, the sample programs provided in the aravis library work fine I have reached out to the fork author. Waiting for their response. I have the same issue right now. Did this ever get resolved? Hello, I want to get the distance of an object from the depth sensor(Primesense). I am able to subscribe to all the topics. I am not sure which one to use for my purpose. I tried using "/camera/depth_registered/image_rect_raw" topic. I have the following information from the topic: Image Height: 480 Image Width: 640 Encoding: 16UC1 Is Big Endian ?: 0 Step: 1280 The data looks like this: 2 86 2 85 2 85 2 85 2 84 2 84 2 83 2 82 2 82 2 82 2 82 2 82 2 82 2 82 2 82 2 81 2 81 2 81 2 81 2 80 2 80 2 78 2 77 2 75 2 75 2 63 2 63 2 62 2 61 2 60 2 59 2 59 2 58 2 58 2 57 2 57 2 57 2 57 2 56 2 57 2 56 2 57 2 58 2 58 2 58 2 58 .............. But I don't know what these array of bytes indicate. It would be very helpful if someone can teach me How to get the distance from this data? Thanks in advance. @Sai, Thank you very much. It was such a simple thing. Hi, I have a C file(cluster.c) and a header file(cluster.h) which are not a part of any ROS package. I want to call functions in that C file from my already existing ROS package's source file(detect.cpp). Note that "cluster.c" is just a collection of some C functions without a main(). So, it can't be compiled separately. I thought of creating a library out of "cluster.c" and "cluster.h" and link that library to my ROS package? How do I do this? What changes should I make to my existing package's CMakeLists.txt and package.xml? This may be a silly and repeated question as I found similar questions being answered. As I am very new to ROS I couldn't understand much from those answers. If someone could explain me in simple terms, it would be great. Thanks, Raj How to find the library which is holding this symbol? Sorry, I am totally new to ROS. I want to model the noise in kinect's grayscale or RGB images. If anyone has done that before, please share any documentation. I got a couple of papers where noise modelling was done for depth measured by kinect but couldn't find anything for grayscale or RGB images. Even). sudo apt-get update sudo apt-get dist-upgrade? It worked. It was taking lot of time to process and my PC didn't respond for some time. So, I thought it was hung. Anyways, I was able to calibrate the camera. Thank you very much. Thanks joanpau. I ran the calibration for "camera/rgb/camera_info". But, when I hit the calibrate button, the display window hangs and the respective terminal also hangs and calibration will not end. Any idea why this happens?
https://answers.ros.org/users/8061/keerthi-raj/?sort=recent
CC-MAIN-2019-51
refinedweb
1,216
67.96
Hi, I've been trying to learn what pointers are and how they function, and I now finally understand most of it. However, I don't understand the assignment of strings to a char *, and what the values they have mean. I wrote a small program to learn: #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int a = 60; int * p; p = &a; printf("Value (with asterisk): %d\n", *p); printf("Location (without asterisk): %d\n\n", (int) p); char a1 = 'c'; char * p1 = &a1; printf("Value (with asterisk): %c\n", *p1); printf("Location (without asterisk): %d\n\n", (int) p1); char * p2 = "Some string"; printf("Unknown (with asterisk): %d\n", *p2); printf("Location (with ampersand): %d\n", (int) &p2); printf("Value (without asterisk): %s\n\n", p2); int * p3 = "47352"; printf("Unknown (with asterisk): %d\n", *p3); printf("Location (with ampersand): %d\n", (int) &p3); printf("Unknown (without asterisk): %d\n", (int) p3); return 0; } I've marked the values I don't understand as 'Unknown'. It seems as if a char * that has a string assigned to it, is sort of the same as a regular type (like int), because it it's value is p2 and it's location &p2. But I don't understand how. I also tryed the same trick with a int *, but the results are not the same (the 'without asterisk' is not the correct value of 47352) I've googled many tutorials, but none can explain how this really works! If someone could send me a tutorial that does, it would really help me out :) ~G PS: The output on my computer: Value (with asterisk): 60 Location (without asterisk): 2293572 Value (with asterisk): c Location (without asterisk): 2293571 Unknown (with asterisk): 83 Location (with ampersand): 2293564 Value (without asterisk): Some string Unknown (with asterisk): 892548916 Location (with ampersand): 2293560 Unknown (without asterisk): 4210883
https://www.daniweb.com/programming/software-development/threads/413432/pointer-arithmetic-problem
CC-MAIN-2015-48
refinedweb
314
51.52
Sorry for the very silly question. I am a self-study beginner in python and I am having issues with using a function and calling it. I am coming from a MATLAB background so i was trying to do something similar. Tools used: Python 2 in a Linux environment As a test, I created a function that i called prthis (for "print this") within a file called also prthis.py. This function just takes a number as an input, and then outputs two numbers, respectively the same one and its square. I defined it like this: #---------------------------------------- # content of the file prthis.py #---------------------------------------- def prthis(x): y=x*x nb=x return (y, nb) #------------------------------------------ >>> import prthis >>> g,t = prthis(7) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'module' object is not callable you are importing a module, not the function. If you want to import just the function you could do this: from prthis import prthis g,t = prthis(7) but if you import the full module you have to call the function as well: import prthis g,t = prthis.prthis(7)
https://codedump.io/share/G0v8l9jZM8Rm/1/a-first-use-of-python-function
CC-MAIN-2016-50
refinedweb
186
75.03
AltSoftSerial is particularly useful when simultaneous data flows are needed. More details below. AltSoftSerial is capable of running up to 31250 baud on 16 MHz AVR, or up to 400000 baud on Teensy 3.2 at 96 MHz. Slower baud rates are recommended when other code may delay AltSoftSerial's interrupt response. Yet another alternate software serial exists for only Arduino Uno, using timer2 and pins 3 and 4. It appears to only work with the ATMEGA328 chip on Uno. Create the AltSoftSerial object. Only one AltSoftSerial can be used, with the fixed pin assignments shown above. Initialize the port to communicate at a specific baud rate. Print a number or text. This works the same as Serial.print(). Returns the number of bytes received, which can be read. Reads the next byte from the port. If nothing has been received, -1 is returned. #include <AltSoftSerial.h> AltSoftSerial altSerial; void setup() { Serial.begin(9600); Serial.println("AltSoftSerial Test Begin"); altSerial.begin(9600); altSerial.println("Hello World"); } void loop() { char c; if (Serial.available()) { c = Serial.read(); altSerial.print(c); } if (altSerial.available()) { c = altSerial.read(); Serial.print(c); } } However, some libraries may disable interrupts for longer than 1 bit time. If they do, AltSoftSerial will not work properly. If you discover erroneous results from AltSoftSerial, please try testing without other libraries. Some boards, like Teensy, Teensy++ and Arduino Mega, have more than 1 timer which is suitable for AltSoftSerial. You can configure which timer AltSoftSerial uses by editing "config/known_boards.h" within the library. This may allow AltSoftSerial to be used together with other libraries which require the timer which AltSoftSerial uses by default. Without other libraries, on Teensy or Arduino (with the issue 776 fix), interrupt latency is about 3 to 4 µs. 115200 baud is possible. However, the maximum baud rate is often not the most important question. Each library imposes interrupt latency on other libraries. AltSoftSerial causes approximately 2-3 µs latency. SoftwareSerial causes 10 bit times of latency for other libraries. Running at 57600 baud, that's 174 µs! This latency is the primary difference between AltSoftSerial and SoftwareSerial. To see this in action, you can try the example that comes with SoftwareSerial in Arduino 1.0. If. AltSoftSerial can handle this test easily, since it does not lock out interrupts for long times. Because SoftwareSerial creates 10 bit times of latency for other libraries, it should be used for a device needing high baud rate. SoftwareSerial should NOT be used at slow baud rates, because it will interfere with the other ports. SoftwareSerial can not simultaenously transmit and receive, so it should be used with a device that never sends in both directions at once. HardwareSerial can tolerate up to 20 bit times latency for receive, or 10 bit times for non-stop transmit. To maintain full transmit speed, HardwareSerial's baud rate should be no greater than SoftwareSerial's. If continuous transmit is not needed, HardwareSerial can use a baud rate almost twice as fast as SoftwareSerial and still reliably receive. But more than twice SoftwareSerial's baud will not be able to receive reliably. AltSoftSerial can tolerate almost 1 bit time latency, so its baud rate must be at least 10 times less than the baud rate used for SoftwareSerial. If the baud rates are chosen wisely, all 3 can work together reliably! Please report any bugs or submit pull requests via GitHub!
https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html
CC-MAIN-2016-44
refinedweb
570
51.55
Solution for Programmming Exercise 4.6 This page contains a sample solution to one of the exercises from Introduction to Programming Using Java. Exercise 4.6: For this exercise, you will write another program based on the non-standard Mosaic class that was presented in Section 4.6. While the program does not do anything particularly interesting, it's interesting as a programming problem. The program will do the same thing as the following applet: The program will show rectangle.) The animation loops through the same sequence of steps over and over. In each. When the rectangle gets to the outer edge of the applet, the loop ends. The animation then starts again at the beginning of the loop. You might want to make a subroutine that does one loop through all the steps of the.) According to the exercise, the first task is to write a subroutine that draws a rectangle in a Mosaic window. The name and seven parameters of the subroutine are specified. So the first line of the subroutine definition will look like this: static void rectangle(int left, int top, int height, int width, int r, int g, int b) { The subroutine has to draw the four lines that make up the outline of the rectangle. Each square that lies along one of these lines will have its color set by a call to Mosaic.setColor(row,col,r,g,b). We just have to make sure that row and col take on all the correct values that are needed to hit all the necessary squares. For the topmost line of the rectangle, for example, row is given by the value of the parameter, top. And, as the exercise explains, the value of col varies from left to left+width-1. So the topmost line of the rectangle can be drawn with the for loop: for ( col = left; col <= left+width-1; col++ ) Mosaic.setColor(top,col,r,g,b); The bottommost row can be drawn by a similar for loop, except that the value of row along the bottommost row is top+height-1, as noted in the exercise. We can combine the two for loops to draw the top and bottom lines at the same time: for ( col = left; col <= left+width-1; col++ ) { Mosaic.setColor(top,col,r,g,b); // A square on the top line. Mosaic.setColor(top+height-1,col,r,g,b); // A square on the bottom line. } Drawing the leftmost and rightmost lines of the rectangle is similar. The row number along these lines varies from top to top+height-1. The column number of the leftmost line is given by left, and the column number of the rightmost line is left+width-1. So, these two lines can be drawn with the for loop: for ( row = top; row <= top+height-1; row++ ) { Mosaic.setColor(row,left,r,g,b); // A square on the left line. Mosaic.setColor(row,left+width-1,r,g,b); // A square on the right line. } When I wrote my program, I used the test "row < top+height" in the first for loop in place of "row <= top+height-1", and similarly for the second loop. The meaning is the same, and the form that I used would probably be preferred by most Java and C++ programmers. Putting this all together gives the rectangle subroutine:() We still have the problem of designing the complete program. The main() routine plays the same animation over and over as long as the window is still open. A pseudocode algorithm for this is given by Open a mosaic window while the window remains open: Delay for 1000 milliseconds Play once through the animation I will write a subroutine named strobe that plays the animation once. Using this subroutine, the body of the main() routine becomes Mosaic.open(41,41,5,5); while ( Mosaic.isOpen() ) { Mosaic.delay(1000); strobe(); } The final stage in the design is to write the strobe() routine. The outline of an algorithm is already given in the exercise. It can be written more formally as Initialize variables top,left,size,brightness for the first step Repeat until the rectangle is as big as the whole window: Draw the rectangle in gray Delay 200 milliseconds Draw the rectangle in black Update the variables for the next step The window has 41 columns and 41 rows of squares. We want the rectangle to start at the middle of the window. That will be in row 20 and column 20, so we can initialize top and left to 20. The rectangle starts off as small as possible, that is with size equal to 1. The value of size is used as both the width and the height of the rectangle. The brightness is initialized to 50. The value of brightness is used for each of the color components, r, g, and b. So, the rectangle can be drawn in gray with the subroutine call statement: rectangle(top,left,size,size,brightness,brightness,brightness); To draw the rectangle in black, just substitute 0 for brightness in this statement. To go from one step in the animation to the next, brightness increases by 10. The topmost line of the rectangle moves up one row. This means that the value of top decreases by 1. Similarly, the value of left decreases by 1. The rectangle grows by one row on each side, so its size increases by 2. There are several ways to check whether the animation should continue. We could check whether its size is <= 41. Or whether left is >= 0. Or whether top is >= 0. Alternatively, we could notice that there are 21 steps in the animation, and we could just use a for loop to count from 1 to 21. Picking one of these methods more or less at random, the algorithm for the strobe() becomes left = 20 top = 20 size = 1 brightness = 50 while left is >= 0: draw the rectangle with specified brightness delay 200 milliseconds draw the rectangle in black left -= 1 top -= 1 size += 2 brightness += 10 This translates easily into Java code. One more note: In my implementation of the subroutine, I changed the condition in the loop to "while (left >= 0 && Mosaic.isOpen())", since there is no reason to continue with the animation if the user has closed the window. However, the program will work without this extra test. It just might take an extra second or so for the program to end after the user closes the window. /** * This program shows an animation in which a small square grows from the * center of the window until it fills the whole square. Then, after a short * delay, the process repeats. As the square grows, its brightness also * increases. The animation continues until the user closes the window. * This program depends on the non-standard classes Mosaic and MosaicCanvas. */ public class MosaicStrobe { /** * Opens a mosaic window then play the "stobe" animation over and over * as long as the window is still open. */ public static void main(String[] args) { Mosaic.open(41,41,5,5); while ( Mosaic.isOpen() ) { Mosaic.delay(1000); strobe(); } } // end main() /** * Draw the animation, showing a square that starts at the center of the * mosaic and grows to fill the whole window. The square gets brighter * as it grows. Note that the animation ends immediately if the user * closes the window. */ static void strobe() { int rectSize; // The number of rows (and columns) in the square. int left; // The leftmost column in the square. int top; // The topmost row in the square. int brightness; // The brightness of the square, which increases from // 50 to a maximum of 250 as the square grows. This // quantity is used for all three color components, // giving a gray color that brightens to white. left = 20; // Start at the center of the 41-by-41 mosaic. top = 20; rectSize = 1; brightness = 50; while (left >= 0 && Mosaic.isOpen()) { // Draw the square in gray, pause so the user can see it, then // redraw the same rectangle in black, effectively erasing the // gray square. rectangle(top,left,rectSize,rectSize,brightness,brightness,brightness); Mosaic.delay(200); rectangle(top,left,rectSize,rectSize,0,0,0); // Now, adjust the parameters to get ready to draw the next square left--; top--; rectSize += 2; brightness += 10; } } // end strobe() /** * Draws the outline of a rectangle in the mosaic window by setting the color * of each little square on that rectangle. (Only the outline of the rectangle * is drawn; it is not filled in.) * @param top gives the starting row, at the top edge of the rectangle * @param left gives the starting column, at the left edge of the rectangle * @param height gives the number of rows in the rectangle * @param width gives the number of columns in the rectangle * @param red the red component of the color, in the range 0 to 255 * @param green the green component of the color * @param blue the blue component of the color */() } // end class MosaicStrobe
http://www-h.eng.cam.ac.uk/help/importedHTML/languages/java/javanotes5.0.2/c4/ex6-ans.html
CC-MAIN-2017-51
refinedweb
1,496
71.04
@c -*-texinfo-*- @c This is part of the GNU Emacs Lisp Reference Manual. @c Copyright (C) 1990, 1991, 1992, 1993, 1995, 1998, 1999, 2001, 2002, @c 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc. @c See the file elisp.texi for copying conditions. @setfilename ../info/tips @node Tips, GNU Emacs Internals, GPL, Top @appendix Tips and Conventions @cindex tips for writing Lisp @cindex standards of coding style @cindex coding standards @kbd{M-x checkdoc RET} when visiting a Lisp file. It cannot check all of the conventions, and not all the warnings it gives necessarily correspond to problems, but it is worth examining them all. @menu *. @end menu @node Coding Conventions @section Emacs Lisp Coding Conventions @cindex coding conventions in Emacs Lisp Here are conventions that you should follow when writing Emacs Lisp code intended for widespread use: @itemize @bullet @item Simply loading the package should not change Emacs's editing behavior. Include a command or commands to enable and disable the feature, or to invoke it. This convention is mandatory for any file that includes custom definitions. If fixing such a file to follow this convention requires an incompatible change, go ahead and make the incompatible change; don't postpone it. @item Since all global variables share the same name space, and all functions share another name space, you should choose a short word to distinguish your program from other Lisp programs@footnote{The benefits of a Common Lisp-style package system are considered not to outweigh the costs.}. Then take care to begin the names of all global variables, constants, and functions in your program with the chosen prefix. This helps avoid name conflicts. Occasionally, for a command name intended for users to use, it is more convenient if some words come before the package's name prefix. And constructs that define functions, variables, etc., work better if they start with @samp{defun} or @samp{defvar}, so put the name prefix later on in the name. This recommendation applies even to names for traditional Lisp primitives that are not primitives in Emacs Lisp---such as @code{copy-list}. Believe it or not, there is more than one plausible way to define @code{copy-list}. Play it safe; append your name prefix to produce a name like @code{foo-copy-list} or @code{mylib-copy-list} instead. If you write a function that you think ought to be added to Emacs under a certain name, such as @code{twiddle-files}, don't call it by that name in your program. Call it @code{mylib-twiddle-files} in your program, and send mail to @samp{bug-gnu-emacs@@gnu.org} suggesting we add it to Emacs. If and when we do, we can change the name easily enough. If one prefix is insufficient, your package can use two or three alternative common prefixes, so long as they make sense. Separate the prefix from the rest of the symbol name with a hyphen, @samp{-}. This will be consistent with Emacs itself and with most Emacs Lisp programs. @item Put a call to @code{provide} at the end of each separate Lisp file. @item If a file requires certain other Lisp programs to be loaded beforehand, then the comments at the beginning of the file should say so. Also, use @code{require} to make sure they are loaded. @item If one file @var{foo} uses a macro defined in another file @var{bar}, @var{foo} should contain this expression before the first use of the macro: @example (eval-when-compile (require '@var{bar})) @end example @noindent (And the library @var{bar} should contain @code{(provide '@var{bar})}, to make the @code{require} work.) This will cause @var{bar} to be loaded when you byte-compile @var{foo}. Otherwise, you risk compiling @var{foo} without the necessary macro loaded, and that would produce compiled code that won't work right. @xref{Compiling Macros}. Using @code{eval-when-compile} avoids loading @var{bar} when the compiled version of @var{foo} is @emph{used}. @item Please don't require the @code{cl} package of Common Lisp extensions at run time. Use of this package is optional, and it is not part of the standard Emacs namespace. If your package loads @code{cl} at run time, that could cause name clashes for users who don't use that package. However, there is no problem with using the @code{cl} package at compile time, with @code{(eval-when-compile (require 'cl))}. That's sufficient for using the macros in the @code{cl} package, because the compiler expands them before generating the byte-code. @item When defining a major mode, please follow the major mode conventions. @xref{Major Mode Conventions}. @item When defining a minor mode, please follow the minor mode conventions. @xref{Minor Mode Conventions}. @item If the purpose of a function is to tell you whether a certain condition is true or false, give the function a name that ends in @samp{p}. If the name is one word, add just @samp{p}; if the name is multiple words, add @samp{-p}. Examples are @code{framep} and @code{frame-live-p}. @item If a user option variable records a true-or-false condition, give it a name that ends in @samp{-flag}. @item If the purpose of a variable is to store a single function, give it a name that ends in @samp{-function}. If the purpose of a variable is to store a list of functions (i.e., the variable is a hook), please follow the naming conventions for hooks. @xref{Hooks}. @item @cindex unloading packages, preparing for If loading the file adds functions to hooks, define a function @code{@var{feature}-unload-hook}, where @var{feature} is the name of the feature the package provides, and make it undo any such changes. Using @code{unload-feature} to unload the file will run this function. @xref{Unloading}. @item It is a bad idea to define aliases for the Emacs primitives. Normally you should use the standard names instead. The case where an alias may be useful is where it facilitates backwards compatibility or portability. @item. @example (defalias 'gnus-point-at-bol (if (fboundp 'point-at-bol) 'point-at-bol 'line-beginning-position)) @end example @item Redefining (or advising) an Emacs primitive is a bad idea. It may do the right thing for a particular program, but there is no telling what other programs might break as a result. In any case, it is a problem for debugging, because the.. @item If a file does replace any of the functions or library programs of standard Emacs, prominent comments at the beginning of the file should say which functions are replaced, and how the behavior of the replacements differs from that of the originals. @item Constructs that define a function or variable should be macros, not functions, and their names should start with @samp{def}. @item A macro that defines a function or variable should have a name that starts with @samp{define-}. The macro should receive the name to be defined as the first argument. That will help various tools find the definition automatically. Avoid constructing the names in the macro itself, since that would confuse these tools. @item Please keep the names of your Emacs Lisp source files to 13 characters or less. This way, if the files are compiled, the compiled files' names will be 14 characters or less, which is short enough to fit on all kinds of Unix systems. @item In some other systems there is a convention of choosing variable names that begin and end with @samp{*}. We don't use that convention in Emacs Lisp, so please don't use it in your programs. (Emacs uses such names only for special-purpose buffers.) The users will find Emacs more coherent if all libraries use the same conventions. @item If your program contains non-ASCII characters in string or character constants, you should make sure Emacs always decodes these characters the same way, regardless of the user's settings. There are two ways to do that: @itemize - @item Use coding system @code{emacs-mule}, and specify that for @code{coding} in the @samp{-*-} line or the local variables list. @example ;; XXX.el -*- coding: emacs-mule; -*- @end example @item Use one of the coding systems based on ISO 2022 (such as iso-8859-@var{n} and iso-2022-7bit), and specify it with @samp{!} at the end for @code{coding}. (The @samp{!} turns off any possible character translation.) @example ;; XXX.el -*- coding: iso-latin-2!; -*- @end example @end itemize @item Indent each function with @kbd{C-M-q} (@code{indent-sexp}) using the default indentation parameters. @item Don't make a habit of putting close-parentheses on lines by themselves; Lisp programmers find this disconcerting. Once in a while, when there is a sequence of many consecutive close-parentheses, it may make sense to split the sequence in one or two significant places. @item Please put a copyright notice and copying permission notice on the file if you distribute copies. Use a notice like this one: @smallexample ;; Copyright (C) @var{year} @var If you have signed papers to assign the copyright to the Foundation, then use @samp{Free Software Foundation, Inc.} as @var{name}. Otherwise, use your name. See also @xref{Library Headers}. @end itemize @node Key Binding Conventions @section Key Binding Conventions @cindex key binding, conventions for @itemize @bullet @item @cindex mouse-2 @cindex references, following Special major modes used for read-only text should usually redefine @kbd{mouse-2} and @key{RET} to trace some sort of reference in the text. Modes such as Dired, Info, Compilation, and Occur redefine it in this way. In addition, they should mark the text as a kind of ``link'' so that @kbd{mouse-1} will follow it also. @xref{Links and Mouse-1}. @item @cindex reserved keys @cindex keys, reserved Please do not define @kbd{C-c @var{letter}} as a key in Lisp programs. Sequences consisting of @kbd{C-c} and a letter (either upper or lower case) are reserved for users; they are the @strong{only} sequences reserved for users, so do not block them. Changing all the Emacs major modes to respect this convention was a lot of work; abandoning this convention would make that work go to waste, and inconvenience users. Please comply with it. @item Function keys @key{F5} through @key{F9} without modifier keys are also reserved for users to define. @item Applications should not bind mouse events based on button 1 with the shift key held down. These events include @kbd{S-mouse-1}, @kbd{M-S-mouse-1}, @kbd{C-S-mouse-1}, and so on. They are reserved for users. @item Sequences consisting of @kbd{C-c} followed by a control character or a digit are reserved for major modes. @item Sequences consisting of @kbd{C-c} followed by @kbd{@{}, @kbd{@}}, @kbd{<}, @kbd{>}, @kbd{:} or @kbd{;} are also reserved for major modes. @item Sequences consisting of @kbd{C-c} followed by any other punctuation character are allocated for minor modes. Using them in a major mode is not absolutely prohibited, but if you do that, the major mode binding may be shadowed from time to time by minor modes. @item Do not bind @kbd{C-h} following any prefix character (including @kbd{C-c}). If you don't bind @kbd{C-h}, it is automatically available as a help character for listing the subcommands of the prefix character. @item Do not bind a key sequence ending in @key{ESC} except following another @key{ESC}. (That is, it is OK to bind a sequence ending in @kbd{@key{ESC} @key{ESC}}.) The reason for this rule is that a non-prefix binding for @key{ESC} in any context prevents recognition of escape sequences as function keys in that context. @item Anything which acts like a temporary mode or state which the user can enter and leave should define @kbd{@key{ESC} @key{ESC}} or @kbd{@key{ESC} @key{ESC} @key{ESC}} as a way to escape. For a state which accepts ordinary Emacs commands, or more generally any kind of state in which @key{ESC} followed by a function key or arrow key is potentially meaningful, then you must not define @kbd{@key{ESC} @key{ESC}}, since that would preclude recognizing an escape sequence after @key{ESC}. In these states, you should define @kbd{@key{ESC} @key{ESC} @key{ESC}} as the way to escape. Otherwise, define @kbd{@key{ESC} @key{ESC}} instead. @end itemize @node Programming Tips @section Emacs Programming Tips @cindex programming conventions Following these conventions will make your program fit better into Emacs when it runs. @itemize @bullet @item Don't use @code{next-line} or @code{previous-line} in programs; nearly always, @code{forward-line} is more convenient as well as more predictable and robust. @xref{Text Lines}. @item Don't call functions that set the mark, unless setting the mark is one of the intended features of your program. The mark is a user-level feature, so it is incorrect to change the mark except to supply a value for the user's benefit. @xref{The Mark}. In particular, don't use any of these functions: @itemize @bullet @item @code{beginning-of-buffer}, @code{end-of-buffer} @item @code{replace-string}, @code{replace-regexp} @item @code{insert-file}, @code{insert-buffer} @end itemize If you just want to move point, or replace a certain string, or insert a file or buffer's contents, without any of the other features intended for interactive users, you can replace these functions with one or two lines of simple Lisp code. @item Use lists rather than vectors, except when there is a particular reason to use a vector. Lisp has more facilities for manipulating lists than for vectors, and working with lists is usually more convenient. Vectors are advantageous for tables that are substantial in size and are accessed in random order (not searched front to back), provided there is no need to insert or delete elements (only lists allow that). @item The recommended way to show a message in the echo area is with the @code{message} function, not @code{princ}. @xref{The Echo Area}. @item When you encounter an error condition, call the function @code{error} (or @code{signal}). The function @code{error} does not return. @xref{Signaling Errors}. Do not use @code{message}, @code{throw}, @code{sleep-for}, or @code{beep} to report errors. @item An error message should start with a capital letter but should not end with a period. @item A question asked in the minibuffer with @code{y-or-n-p} or @code{yes-or-no-p} should start with a capital letter and end with @samp{? }. @item When you mention a default value in a minibuffer prompt, put it and the word @samp{default} inside parentheses. It should look like this: @example Enter the answer (default 42): @end example @item In @code{interactive}, if you use a Lisp expression to produce a list of arguments, don't try to provide the ``correct'' default values for region or position arguments. Instead, provide @code{nil} for those arguments if they were not specified, and have the function body compute the default value when the argument is @code{nil}. For instance, write this: @example (defun foo (pos) (interactive (list (if @var{specified} @var{specified-pos}))) (unless pos (setq pos @var{default-pos})) ...) @end example @noindent rather than this: @example (defun foo (pos) (interactive (list (if @var{specified} @var{specified-pos} @var{default-pos}))) ...) @end example @noindent This is so that repetition of the command will recompute these defaults based on the current circumstances. You do not need to take such precautions when you use interactive specs @samp{d}, @samp{m} and @samp{r}, because they make special arrangements to recompute the argument values on repetition of the command. @item Many commands that take a long time to execute display a message that says something like @samp{Operating...} when they start, and change it to @samp{Operating...done} when they finish. Please keep the style of these messages uniform: @emph{no} space around the ellipsis, and @emph{no} period after @samp{done}. @item Try to avoid using recursive edits. Instead, do what the Rmail @kbd{e} command does: use a new local keymap that contains one command defined to switch back to the old local keymap. Or do what the @code{edit-options} command does: switch to another buffer and let the user switch back at will. @xref{Recursive Editing}. @end itemize @node Compilation Tips @section Tips for Making Compiled Code Fast @cindex execution speed @cindex speedups Here are ways of improving the execution speed of byte-compiled Lisp programs. @itemize @bullet @item @cindex profiling @cindex timing programs @cindex @file{elp.el} Profile your program with the @file{elp} library. See the file @file{elp.el} for instructions. @item @cindex @file{benchmark.el} @cindex benchmarking Check the speed of individual Emacs Lisp forms using the @file{benchmark} library. See the functions @code{benchmark-run} and @code{benchmark-run-compiled} in @file{benchmark.el}. @item Use iteration rather than recursion whenever possible. Function calls are slow in Emacs Lisp even when a compiled function is calling another compiled function. @item Using the primitive list-searching functions @code{memq}, @code{member}, @code{assq}, or @code{assoc} is even faster than explicit iteration. It can be worth rearranging a data structure so that one of these primitive search functions can be used. @item Certain built-in functions are handled specially in byte-compiled code, avoiding the need for an ordinary function call. It is a good idea to use these functions rather than alternatives. To see whether a function is handled specially by the compiler, examine its @code{byte-compile} property. If the property is non-@code{nil}, then the function is handled specially. For example, the following input will show you that @code{aref} is compiled specially (@pxref{Array Functions}): @example @group (get 'aref 'byte-compile) @result{} byte-compile-two-args @end group @end example @item. @xref{Inline Functions}. @end itemize @node Warning Tips @section Tips for Avoiding Compiler Warnings @cindex byte compiler warnings, how to avoid @itemize @bullet @item Try to avoid compiler warnings about undefined free variables, by adding dummy @code{defvar} definitions for these variables, like this: @example (defvar foo) @end example Such a definition has no effect except to tell the compiler not to warn about uses of the variable @code{foo} in this file. @item If you use many functions and variables from a certain file, you can add a @code{require} for that package to avoid compilation warnings for them. For instance, @example (eval-when-compile (require 'foo)) @end example @item If you bind a variable in one function, and use it or set it in another function, the compiler warns about the latter function unless the variable has a definition. But adding a definition would be unclean if the variable has a short name, since Lisp packages should not define short variable names. The right thing to do is to rename this variable to start with the name prefix used for the other functions and variables in your package. @item The last resort for avoiding a warning, when you want to do something that usually is a mistake but it's not a mistake in this one case, is to put a call to @code{with-no-warnings} around it. @end itemize @node Documentation Tips @section Tips for Documentation Strings @cindex documentation strings, conventions and tips @findex checkdoc-minor-mode Here are some tips and conventions for the writing of documentation strings. You can check many of these conventions by running the command @kbd{M-x checkdoc-minor-mode}. @itemize @bullet @item Every command, function, or variable intended for users to know about should have a documentation string. @item An internal variable or subroutine of a Lisp program might as well have a documentation string. In earlier Emacs versions, you could save space by using a comment instead of a documentation string, but that is no longer the case---documentation strings now take up very little space in a running Emacs. @item @code{apropos}. You can fill the text if that looks good. However, rather than blindly filling the entire documentation string, you can often make it much more readable by choosing certain line breaks with care. Use blank lines between topics if the documentation string is long. @item The first line of the documentation string should consist of one or two complete sentences that stand on their own as a summary. @kbd{M-x apropos} displays just the first line, and if that line's contents don't stand on their own, the result looks bad. In particular, start the first line with a capital letter and end with a period.. @item When the user tries to use a disabled command, Emacs displays just the first paragraph of its documentation string---everything through the first blank line. If you wish, you can choose which information to include before the first blank line so as to make this display useful. @item The first line should mention all the important arguments of the function, and should mention them in the order that they are written in a function call. If the function has many arguments, then it is not feasible to mention them all in the first line; in that case, the first line should mention the first few arguments, including the most important arguments. @item When a function's documentation string mentions the value of an argument of the function, use the argument name in capital letters as if it were a name for that value. Thus, the documentation string of the function @code{eval} refers to its second argument as @samp{FORM}, because the actual argument name is @code{form}: @example Evaluate FORM and return its value. @end example Also write metasyntactic variables in capital letters, such as when you show the decomposition of a list or vector into subunits, some of which may vary. @samp{KEY} and @samp{VALUE} in the following example illustrate this practice: @example The argument TABLE should be an alist whose elements have the form (KEY . VALUE). Here, KEY is ... @end example @item Never change the case of a Lisp symbol when you mention it in a doc string. If the symbol's name is @code{foo}, write ``foo,'' not ``Foo'' (which is a different symbol). This might appear to contradict the policy of writing function argument values, but there is no real contradiction; the argument @emph{value} is not the same thing as the @emph{symbol} which the function uses to hold the value. If this puts a lower-case letter at the beginning of a sentence and that annoys you, rewrite the sentence so that the symbol is not at the start of it. @item Do not start or end a documentation string with whitespace. @item @strong! @anchor{Docstring hyperlinks} @item @iftex When a documentation string refers to a Lisp symbol, write it as it would be printed (which usually means in lower case), with single-quotes around it. For example: @samp{`lambda'}. There are two exceptions: write @code{t} and @code{nil} without single-quotes. @end iftex @ifnottex When a documentation string refers to a Lisp symbol, write it as it would be printed (which usually means in lower case), with single-quotes around it. For example: @samp{lambda}. There are two exceptions: write t and nil without single-quotes. (In this manual, we use a different convention, with single-quotes for all symbols.) @end ifnottex @cindex hyperlinks in documentation strings @samp{variable}, @samp{option}, @samp{function}, or @samp{command}, immediately before the symbol name. (Case makes no difference in recognizing these indicator words.) For example, if you write @example This function sets the variable `buffer-file-name'. @end example @noindent then the hyperlink will refer only to the variable documentation of @code{buffer-file-name}, and not to its function documentation. If a symbol has a function definition and/or a variable definition, but those are irrelevant to the use of the symbol that you are documenting, you can write the words @samp{symbol} or @samp{program} before the symbol name to prevent making any hyperlink. For example, @example If the argument KIND-OF-RESULT is the symbol `list', this function returns a list of all the objects that satisfy the criterion. @end example @noindent does not make a hyperlink to the documentation, irrelevant here, of the function @code{list}. Normally, no hyperlink is made for a variable without variable documentation. You can force a hyperlink for such variables by preceding them with one of the words @samp{variable} or @samp{option}. Hyperlinks for faces are only made if the face name is preceded or followed by the word @samp{face}. In that case, only the face documentation will be shown, even if the symbol is also defined as a variable or as a function. To make a hyperlink to Info documentation, write the name of the Info node (or anchor) in single quotes, preceded by @samp{info node}, @samp{Info node}, @samp{info anchor} or @samp{Info anchor}. The Info file name defaults to @samp{emacs}. For example, @smallexample See Info node `Font Lock' and Info node `(elisp)Font Lock Basics'. @end smallexample Finally, to create a hyperlink to URLs, write the URL in single quotes, preceded by @samp{URL}. For example, @smallexample The home page for the GNU project has more information (see URL `'). @end smallexample @item Don't write key sequences directly in documentation strings. Instead, use the @samp{\\[@dots{}]} construct to stand for them. For example, instead of writing @samp{C-f}, write the construct @samp{\\[forward-char]}. When Emacs displays the documentation string, it substitutes whatever key is currently bound to @code{forward-char}. (This is normally @samp{C-f}, but it may be some other character if the user has moved key bindings.) @xref{Keys in Documentation}. @item In documentation strings for a major mode, you will want to refer to the key bindings of that mode's local map, rather than global ones. Therefore, use the construct @samp{\\<@dots{}>} once in the documentation string to specify which key map to use. Do this before the first use of @samp{\\[@dots{}]}. The text inside the @samp{\\<@dots{}>} should be the name of the variable containing the local keymap for the major mode. It is not practical to use @samp{\\[@dots{}]} very many times, because display of the documentation string will become slow. So use this to describe the most important commands in your major mode, and then use @samp{\\@{@dots{}@}} to display the rest of the mode's keymap. @item For consistency, phrase the verb in the first sentence of a function's documentation string as an imperative---for instance, use ``Return the cons of A and B.'' in preference to ``Returns the cons of A and B@.'' Usually it looks good to do likewise for the rest of the first paragraph. Subsequent paragraphs usually look better if each sentence is indicative and has a proper subject. @item The documentation string for a function that is a yes-or-no predicate should start with words such as ``Return t if,'' to indicate explicitly what constitutes ``truth.'' The word ``return'' avoids starting the sentence with lower-case ``t,'' which could be somewhat distracting. @item If a line in a documentation string begins with an open-parenthesis, write a backslash before the open-parenthesis, like this: @example The argument FOO can be either a number \(a buffer position) or a string (a file name). @end example This prevents the open-parenthesis from being treated as the start of a defun (@pxref{Defuns,, Defuns, emacs, The GNU Emacs Manual}). @item Write documentation strings in the active voice, not the passive, and in the present tense, not the future. For instance, use ``Return a list containing A and B.'' instead of ``A list containing A and B will be returned.'' @item Avoid using the word ``cause'' (or its equivalents) unnecessarily. Instead of, ``Cause Emacs to display text in boldface,'' write just ``Display text in boldface.'' @item When a command is meaningful only in a certain mode or situation, do mention that in the documentation string. For example, the documentation of @code{dired-find-file} is: @example In Dired, visit the file or directory named on this line. @end example @item When you define a variable that users ought to set interactively, you normally should use @code{defcustom}. However, if for some reason you use @code{defvar} instead, start the doc string with a @samp{*}. @xref{Defining Variables}. @item The documentation string for a variable that is a yes-or-no flag should start with words such as ``Non-nil means,'' to make it clear that all non-@code{nil} values are equivalent and indicate explicitly what @code{nil} and non-@code{nil} mean. @end itemize @node Comment Tips @section Tips on Writing Comments @cindex comments, Lisp convention for We recommend these conventions for where to put comments and how to indent them: @table @samp @item ; Comments that start with a single semicolon, @samp{;}, should all be aligned to the same column on the right of the source code. Such comments usually explain how the code on the same line does its job. In Lisp mode and related modes, the @kbd{M-;} (@code{indent-for-comment}) command automatically inserts such a @samp{;} in the right place, or aligns such a comment if it is already present. This and following examples are taken from the Emacs sources. @smallexample @group (setq base-version-list ; there was a base (assoc (substring fn 0 start-vn) ; version to which file-version-assoc-list)) ; this looks like ; a subversion @end group @end smallexample @item ;; Comments that start with two semicolons, @samp{;;}, should be aligned to the same level of indentation as the code. Such comments usually describe the purpose of the following lines or the state of the program at that point. For example: @smallexample @group (prog1 (setq auto-fill-function @dots{} @dots{} ;; update mode line (force-mode-line-update))) @end group @end smallexample We also normally use two semicolons for comments outside functions. @smallexample @group ;; This Lisp code is run in Emacs ;; when it is to operate as a server ;; for other processes. @end group @end smallexample Every function that has no documentation string (presumably one that is used only internally within the package it belongs to), should instead have a two-semicolon comment right before the function, explaining what the function does and how to call it properly. Explain precisely what each argument means and how the function interprets its possible values. @item ;;; Comments that start with three semicolons, @samp{;;;}, should start at the left margin. These are used, occasionally, for comments within functions that should start at the margin. We also use them sometimes for comments that are between functions---whether to use two or three semicolons depends on whether the comment should be considered a ``heading'' by Outline minor mode. By default, comments starting with at least three semicolons (followed by a single space and a non-whitespace character) are considered headings, comments starting with two or less are not. Another use for triple-semicolon comments is for commenting out lines within a function. We use three semicolons for this precisely so that they remain at the left margin. By default, Outline minor mode does not consider a comment to be a heading (even if it starts with at least three semicolons) if the semicolons are followed by at least two spaces. Thus, if you add an introductory comment to the commented out code, make sure to indent it by at least two spaces after the three semicolons. @smallexample (defun foo (a) ;;; This is no longer necessary. ;;; (force-mode-line-update) (message "Finished with %s" a)) @end smallexample When commenting out entire functions, use two semicolons. @item ;;;; Comments that start with four semicolons, @samp{;;;;}, should be aligned to the left margin and are used for headings of major sections of a program. For example: @smallexample ;;;; The kill ring @end smallexample @end table @noindent The indentation commands of the Lisp modes in Emacs, such as @kbd{M-;} (@code{indent-for-comment}) and @key{TAB} (@code{lisp-indent-line}), automatically indent comments according to these conventions, depending on the number of semicolons. @xref{Comments,, Manipulating Comments, emacs, The GNU Emacs Manual}. @node Library Headers @section Conventional Headers for Emacs Libraries @cindex header comments @cindex library header comments Emacs has conventions for using special comments in Lisp libraries to divide them into sections and give information such as who wrote them. This section explains these conventions. We'll start with an example, a package that is included in the Emacs distribution. Parts of this example reflect its status as part of Emacs; for example, the copyright notice lists the Free Software Foundation as the copyright holder, and the copying permission says the file is part of Emacs. When you write a package and post it, the copyright holder would be you (unless your employer claims to own it instead), and you should get the suggested copying permission from the end of the GNU General Public License itself. Don't say your file is part of Emacs if we haven't installed it in Emacs yet! With that warning out of the way, on to the example: @smallexample @group ;;; lisp-mnt.el --- minor mode for Emacs Lisp maintainers ;; Copyright (C) 1992 Free Software Foundation, Inc. @end group ;; Author: Eric S. Raymond <esr@@snark.thyrsus.com> ;; Maintainer: Eric S. Raymond <esr@@snark.thyrsus.com> ;; Created: 14 Jul 1992 ;; Version: 1.2 @group ;; Keywords: docs ;; This file is part of GNU Emacs. @dots{} ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, ;; Boston, MA 02110-1301, USA. @end group @end smallexample The very first line should have this format: @example ;;; @var{filename} --- @var{description} @end example @noindent The description should be complete in one line. If the file needs a @samp{-*-} specification, put it after @var{description}. After the copyright notice come several @dfn{header comment} lines, each beginning with @samp{;; @var{header-name}:}. Here is a table of the conventional possibilities for @var{header-name}: @table @samp @item Author This line states the name and net address of at least the principal author of the library. If there are multiple authors, you can list them on continuation lines led by @code{;;} and a tab character, like this: @smallexample @group ;; Author: Ashwin Ram <Ram-Ashwin@@cs.yale.edu> ;; Dave Sill <de5@@ornl.gov> ;; Dave Brennan <brennan@@hal.com> ;; Eric Raymond <esr@@snark.thyrsus.com> @end group @end smallexample @item Maintainer This line should contain a single name/address as in the Author line, or an address only, or the string @samp{FSF}. If there is no maintainer line, the person(s) in the Author field are presumed to be the maintainers. The example above is mildly bogus because the maintainer line is redundant. The idea behind the @samp{Author} and @samp{Maintainer} lines is to make possible a Lisp function to ``send mail to the maintainer'' without having to mine the name out by hand. Be sure to surround the network address with @samp{<@dots{}>} if you include the person's full name as well as the network address. @item Created This optional line gives the original creation date of the file. For historical interest only. @item Version If you wish to record version numbers for the individual Lisp program, put them in this line. @item Adapted-By In this header line, place the name of the person who adapted the library for installation (to make it fit the style conventions, for example). @item Keywords This line lists keywords for the @code{finder-by-keyword} help command. Please use that command to see a list of the meaningful keywords. This field is important; it's how people will find your package when they're looking for things by topic area. To separate the keywords, you can use spaces, commas, or both. @end table Just about every Lisp library ought to have the @samp{Author} and @samp{Keywords} by blank lines from anything else. Here is a table of them: @table @samp @item ;;; Commentary: This begins introductory comments that explain how the library works. It should come right after the copying permissions, terminated by a @samp{Change Log}, @samp{History} or @samp{Code} comment line. This text is used by the Finder package, so it should make sense in that context. @item ;;; Documentation: This was used in some files in place of @samp{;;; Commentary:}, but it is deprecated. @item ;;; Change Log: This begins change log information stored in the library file (if you store the change history there). For Lisp files distributed with Emacs, the change history is kept in the file @file{ChangeLog} and not in the source file at all; these files generally do not have a @samp{;;; Change Log:} line. @samp{History} is an alternative to @samp{Change Log}. @item ;;; Code: This begins the actual code of the program. @item ;;; @var{filename} ends here This is the @dfn{footer line}; it appears at the very end of the file. Its purpose is to enable people to detect truncated versions of the file from the lack of a footer line. @end table @ignore arch-tag: 9ea911c2-6b1d-47dd-88b7-0a94e8b27c2e @end ignore
http://opensource.apple.com/source/emacs/emacs-78.2/emacs/lispref/tips.texi
CC-MAIN-2014-42
refinedweb
6,242
60.95
* A friendly place for programming greenhorns! Big Moose Saloon Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login JavaRanch » Java Forums » Engineering » Design Author Learning To Design Alvin Parker Ranch Hand Joined: Oct 01, 2013 Posts: 38 posted Dec 20, 2013 23:47:15 0 I am doing my best to write better software. Having been a long-time Java programmer and then learning ActionScript, I've come to appreciate some of the workings of ActionScript. I'm a self-taught programmer (about 13 years ago I learned not counting BASIC in high school). AS quickly taught me what async means and was a shock having worked in Java. Now I've been into AS for a number of years and there are some lessons I have learned from it that I have applied to my latest server-side workings. I want to be able to identify and learn design patterns better. I want to know when I should use them and when I should not (or when better alternatives are available). If any are inclined to help me, I'd like to post what I did for this latest project and to get feedback on if I could do it better and what is right and wrong about my design. Here are the bullets. 1. The program has an entry point which starts a Thread pool and a ServerSocket . 2. Client connects to ServerSocket - ServerSocket gets a Thread and starts "MainService" 3. One MainService exists for each Client that connects. MainService is an IService: public interface IService extends Runnable{ /** * Gets the service started. Should only be called once * all items have been initialized */ public void startService() throws ServiceNotInitializedException; /** * Reports on the run state of the service. * @return */ public boolean isServiceRunning(); /** * If the service has results, they will be available when the * service is done running and will be put in the callback object. * Setting this object will also cause the service to report on * percentages of service completion for long running services. * * @return */ public void setServiceCallback(IServiceCallback callbackObject); /** * Once the service is done, you can get any objects it should * return by calling this method. If no objects should be returned, * this method returns null. * @return */ public Object getServiceResult(); /** * If the service cannot be stopped it may throw * an UninteruptableException * * @throws UninteruptableException */ public void stopService() throws UninteruptableException, Exception; /** * This is the IMessage the service will act on, modify and * send back to the caller (if caller is not null). * * @param message */ public void setServiceMessage(IMessage message); } 4. A single handler is created by MainService. That handler is MainServiceHandler and it's an IServiceHandler public interface IServiceHandler { /** * Does whatever needs doing for the message at hand * @param message the IMessage to act on * @param callbackListener the Observer who should be notified */ public void handleMessage(IMessage message, AbstractCallback callbackListener); } 5. MainServiceHandler is sort of a "super handler" in that it has a reference to every kind of handler (in a Map) that is needed for my implementation. In each IServiceHandler's handleMessage() I implement any custom flow needed and then invoke the service. 6. When the service is done running, the MainService is notified. It in turn simply hands the message off to MainServiceHandler which causes some other handler to fire which causes some other IService to run and so forth until the workflow has been completed. By designing in this way, I feel I've created a fully async flow. In each of my IService.startService() methods, I get a Thread from the Thread pool and then have it execute the IService runnable in question. Nothing moves forward until that Thread is done. There are awkward parts to my design, I'm sure. I could have made another layer of abstraction and added IServiceHandlers to that object, for instance. But, in general, is my design sensible? I did it this way for a few reasons : 1. I can report where I am in process with this flow so I can feedback to the client as to percent done. 2. I have created a flow graph so to speak. If I have to modify anything, it will be contained to three objects - the MainServiceHandler, the IServiceHandler and IService in question. MainServiceHandler pretty well describes the entire implementation. 3. It should be obvious and simple to future developers how to extend the system with more services - even though it's probably a more verbose process than it has to be. 4. I can be sure that some long running processes complete before the system moves on. 5. I should never have deadlock issues as there's only one Thread in service (per client) per IService and they run iteratively. Besides helping me understand if there's a better way to accomplish software construction, I have a question about frameworks as well. For the first time, I integrated Guice into this process. I was excited to use it and I see some benefits to it. However, it seems Guice primarily gives you a centralized Object map and makes code really verbose and take longer to develop. Given that all of my objects, other than the IServiceHandler implementations don't take dependencies in their constructors, does it make any sense for a framework like Guice to be introduced to the process I describe above? What do I gain by this? //Injector public class AMFReaderModule extends AbstractModule { /* (non-Javadoc) * @see com.google.inject.AbstractModule#configure() */ @Override protected void configure() { bind(IAMFMessageReaderService.class).to(AMFMessageReaderService.class); } //and in the calling class: Injector readModule = Guice.createInjector(new AMFReaderModule()); IAMFMessageReaderService amfReader = readModule.getInstance(IAMFMessageReaderService.class); } Versus this : IAMFMessageReaderService service = new AMFMessageReaderService(); Thanks for entertaining my questions. Jeanne Boyarsky internet detective Marshal Joined: May 26, 2003 Posts: 30293 150 I like... posted Dec 26, 2013 17:27:33 0 You gain the ability to make the code easier to test . With dependency injection , the code just knows about the interface IAMFMessageReaderService. Which means your test class is free to pass in a mock object rather than the one your code happens to be using. I bolded the keywords that you can google for more information on those subjects. Sometimes part of learning is just finding out the right questions to ask or terms to look up! [ ] [ JavaRanch FAQ ] [ How To Ask Questions The Smart Way ] [ Book Promos ] Blogging on Certs: SCEA Part 1 , Part 2 & 3 , Core Spring 3 , OCAJP , OCPJP beta , TOGAF part 1 and part 2 Alvin Parker Ranch Hand Joined: Oct 01, 2013 Posts: 38 posted Jan 01, 2014 23:36:05 0 Thanks Jeanne. I can see how DI can make testing and extending easier. I appreciate your feedback. Kim Chen Greenhorn Joined: Jan 06, 2014 Posts: 1 I like... posted Jan 07, 2014 22:42:18 0 This is not work for me, please check and update. Thanks Junilu Lacar Bartender Joined: Feb 26, 2001 Posts: 4456 6 I like... posted Jan 13, 2014 15:17:10 0 The first design choice that jumps out at me that I would question is having IService extend Runnable. This is related to design principles that deal with the separation of concerns: Interface Segregation Principle and Single Responsibility Principle. Requiring implementations of the IService interface to also be Runnable seems like you're inappropriately coupling/mixing two different concerns. After all, a class can implement more than one interface in Java so why force a Service implementation to be Runnable as well? Also, I'm not a big fan of the "I" prefix for interfaces convention, but that's a personal preference. I prefer to use packages and concrete prefixes, e.g. JdbcFooDao, Hib3FooDao, XmlFooDao (possible implementation classes of the FooDao interface). In the same way that the Java Collections has ArrayList and HashMap as implementations of the List and Map interfaces, respectively. Junilu - [ How to Ask Questions ] [ How to Answer Questions ] Junilu Lacar Bartender Joined: Feb 26, 2001 Posts: 4456 6 I like... posted Jan 13, 2014 15:29:31 0 Another smell is that all the method names have "Service" in them -- kind of redundant since the interface itself is already called "IService" (again, I'd prefer just "Service" for the interface). Code that results from such a definition tends to be repetitious and wordy: IService myService = new MyServiceImpl(); myService.startService(); if (myService.isServiceRunning()) { // ... whatever } // vs Service myService = new FooService(); myService.start(); if (myService.isRunning()) { // ... whatever } Junilu Lacar Bartender Joined: Feb 26, 2001 Posts: 4456 6 I like... posted Jan 13, 2014 15:59:24 0 Another smell: stopService() is declared to throw Exception -- this seems too general for this particular method and suggests that you don't know what the exact behavior is you want. Maybe leave Exception out of the throws clause until you have more specific checked exceptions that you can specify for this particular method. I agree. Here's the link: subject: Learning To Design Similar Threads Socket Server only processing one request, then it just queues them up Doubt in Maxs' Socket solution Looper Handler in java Configure Portlet request attributes for Weblogic 10.2 Null pointer exception in client side when calling a web service method in JBoss 5 All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/625689/design/Learning-Design
CC-MAIN-2014-35
refinedweb
1,541
53.61
Resent with sign-off. If you pick the patches that use the dynamic allocation of locks you can pick it. The patches for the annotation does not apply for the selinux-next at the moment so have to be for selinuxns. I will send the patches to pauls next tree. Im abit confused on when that is appropriate. Obviously there will be collisions with the namespace, but the patches also solves few of my prerequisite topics. Advertising On 02/02/2018 03:10 PM, Stephen Smalley wrote: > On Fri, 2018-02-02 at 09:05 +0100, Peter Enderborg wrote: >> The locks are moved to dynamic allocation, we need to >> help the lockdep system to classify the locks. >> This adds to lockdep annotation for the page mutex and >> for the ss lock. > Thanks, but missing a Signed-off-by: line. Also, just to be clear, you > shouldn't re-base your work on top of the entire selinuxns branch, > since I only expect the first few patches to be mergeable in the near > term. > > I also will need to re-base again when the selinux next branch moves to > something 4.15-based, including fixing up the bpf hooks that were > introduced there. > >> --- >> security/selinux/ss/services.c | 5 +++++ >> 1 file changed, 5 insertions(+) >> >> diff --git a/security/selinux/ss/services.c >> b/security/selinux/ss/services.c >> index abc5383..ba463c0 100644 >> --- a/security/selinux/ss/services.c >> +++ b/security/selinux/ss/services.c >> @@ -70,6 +70,9 @@ >> #include "ebitmap.h" >> #include "audit.h" >> >> +static struct lock_class_key selinux_ss_class_key; >> +static struct lock_class_key selinux_status_class_key; >> + >> /* Policy capability names */ >> char *selinux_policycap_names[__POLICYDB_CAPABILITY_MAX] = { >> "network_peer_controls", >> @@ -88,7 +91,9 @@ int selinux_ss_create(struct selinux_ss **ss) >> if (!newss) >> return -ENOMEM; >> rwlock_init(&newss->policy_rwlock); >> + lockdep_set_class(&newss->policy_rwlock, >> &selinux_ss_class_key); >> mutex_init(&newss->status_lock); >> + lockdep_set_class(&newss->status_lock, >> &selinux_status_class_key); >> *ss = newss; >> return 0; >> }
https://www.mail-archive.com/selinux@tycho.nsa.gov/msg06342.html
CC-MAIN-2018-09
refinedweb
299
50.02
In the previous part 2 - First steps in computer vision, you built a neural network that could recognize items of clothing. Now that you've looked at fashion example for computer vision, you've probably noticed a big limitation for computer vision with these example. And that was that you could only have one item in the picture, and then it had to be centered, and it to be well-defined. So shoes had to face left, for example. A neural network type called a convolutional neural network can help here. It'll take us a little time to build up to it. And in this part, we'll talk all about what convolutions are and how they can be used in combination with something called pooling to help a computer understand the contents of an image. It's going to take a little while to put it all together. But let's start with just understanding what a convolution is before you can start using one. The idea behind the convolution is very similar to image processing with filters. If you use something like Photoshop before, it has filters to do things like sharpening an image or adding motion blur. So while the effect is complex, the process behind it is quite simple. So let's take a look at it in action. On the left, I have an image of a boot from the fashion MNIST dataset. On the right, I have a representation of nine of the pixels in the image. I'm going to call the center one my current pixel, and all of the others are its neighbors. I define a filter, which is a set of values in the same shape as my pixel and its neighbors. So for example, if I had one neighbor in each direction for a 3x3 grid of pixels, I'd have a 3x3 grid in my filter, too. Each value in the filter can be called a weight. So to calculate a new value for my pixel, all I have to do is multiply each neighbor by their weight, my current pixel by its weight, and then add them all up. And I'm going to do this process for every pixel in the image. The result will be a transformed image. So for example, if you look at the picture on the left if I apply the filter in the middle to it, I'll get the picture on the right. This filter has led to a huge emphasis on vertical lines. They really pop now. And similarly, this filter leads to an emphasis on horizontal lines. So you might be wondering at this point, what does this have to do with computer vision? Ultimately, the goal of trying to understand what an item is isn't just matching the raw pixels to labels like we did with the fashion example. But what if we could extract features from the image instead, and then when an image had this set of features, it was this class, or if it had that set of features it was that class? And that's the heart of what convolutional neural networks do. They process the images down into raw features, and then they find sets of features that will match the label. And they do this using filters. And just like neurons learned weights and biases to add up to what we needed, convolutions will learn the appropriate filters through an initial randomization, and then using the loss function and optimizer to tweak them for better results. So for example, take a look at these images. And you can see how they've been transformed by filters. And these filters learned how to isolate and abstract features within them. You can see, for example, that something like our horizontal line detector was able to detect a commonality in these images. And they're all shoes. And that line is the sole of the shoe. But if you consider these images with the same filter, they had different results. So if a lot of pixels are lighting up with the horizontal line filter, we could kind of sort of describe that as a sole detector. You might hear that phrase a lot -- "detector." But what it's referring to is ultimately a filter that can extract a feature that can be used to determine a class. I first heard it in the cats versus dogs classifier, which we'll look later, when somebody visualized a floppy ear detector, which determined something was a dog and not a cat. One other thing that you might have noticed in the previous picture was also that the resolution of the images was decreasing. This is achieved through something called a pooling. The idea here is pretty simple. If there is a way that we can extract the feature while removing extraneous information, we can actually learn much faster. Now, let's take a look at how this works. The concept is actually quite simple. Imagine this is a chunk of our pixels. To keep it simple, I'm just going to have them as monochrome. We then look at them in blocks of 2x2, and then we'll only keep the biggest value which in this case is 192. We then repeat the process for the next 2x2, and keep the biggest, which is 144; and the next, which yields 255; and the next, which yields 168. We then put these four results together to yield a new 2x2 block. And this contains what had been the largest values in the 2x2 constituents of the previous 4x4 block. We've now reduced the size by 75%, and maybe -- just maybe -- we've kept the important information. So let's see what this actually looks like. Here is the image that we had filtered earlier to detect vertical lines. On the left is what it looks like before pooling. And on the right is what it looks like after pooling in the way that we just demonstrated. Notice how the information hasn't just been maintained. You could argue that's also been emphasized. Pooling is an important way, also, of reducing the amount of information your model has to process. If you think about it, say you want to learn 100 filters. That means you would have to keep track of 101 versions of your image -- the original plus the results of what it would look like after the filters have been applied. If you have thousands of images, you'll soon start to eat memory. And that's just one layer. What if you had another layer beneath this that also learned 100 filters? That would mean each of your first 100 will also have 100 products from it, giving you 10,000 images for every image you need to train. Any technique that can reduce size while keeping this information is obviously very valuable. So now that we've seen what a convolution is, and how it works, as well as how it can go hand-in-hand with pooling, let's take some time to see how to code for them. So let's take a look at some convolutions in action. I want to talk about, for example, if you were going to classify a shoe instead of the one that you had in fashion MNIST. One of the ways of doing this is with convolutions. And in this part, you'll just take a quick experiment to see how the filters of convolutions work. So we'll start by importing some of the required Python libraries. import cv2 import numpy as np from scipy import misc i = misc.ascent() And one of the things that's built into these libraries is this image called ascent. So we can use the pyplot library to draw it, so we can see what it looks like. import matplotlib.pyplot as plt plt.grid(False) plt.gray() plt.axis('off') plt.imshow(i) plt.show() And it's a person walking up some stairs. I'm now copy that into a numpy array so you can manipulate it. i_transformed = np.copy(i) size_x = i_transformed.shape[0] size_y = i_transformed.shape[1] And here I've defined a number of different filters. # Remember the 3x3 filters that we were showing? I'm just implementing them as three arrays of three items. And one other thing that I've done is added a weight to this so that one of the things is that all the digits should add up to 1. But if they had to add up to something more than that, then you can multiply them out by a factor to normalize them. So for example, if they added up to 10, you could set the weight to 0.1 so the final result would be normalized back to 1. for x in range(1,size_x-1): for y in range(1,size_y-1): convolution = 0.0 convolution = convolution + (i[x - 1, y-1] * filter[0][0]) convolution = convolution + (i[x, y-1] * filter[0][1]) convolution = convolution + (i[x + 1, y-1] * filter[0][2]) convolution = convolution + (i[x-1, y] * filter[1][0]) convolution = convolution + (i[x, y] * filter[1][1]) convolution = convolution + (i[x+1, y] * filter[1][2]) convolution = convolution + (i[x-1, y+1] * filter[2][0]) convolution = convolution + (i[x, y+1] * filter[2][1]) convolution = convolution + (i[x+1, y+1] * filter[2][2]) convolution = convolution * weight if(convolution255): convolution=255 i_transformed[x, y] = convolution Now here's is just simply a loop going over the image and multiplying out the relevant pixel and its neighbors by the relevant item in the filter. Once it's done that, we can plot it to see the result. # Plot the image. Note the size of the axes -- they are 512 by 512 plt.gray() plt.grid(False) plt.imshow(i_transformed) #plt.axis('off') plt.show() And you can see the filter is really emphasizing the image's vertical lines. For example, if you change to a different filter like this one filter = [ [-1, 0, 1], [-2, 0, 2], [-1, 0, 1]] And we'll see the one that really emphasizes the horizontal lines. So you can consider following filter values and look at what their impact on the images is, or you can experiment with your own. So for example, this is implementation of a simple pooling.() If you look at the axis, the axis is now -- it's 256x256. And if we look at our original image, it was 512x512. This is the original image after the filter. So you've had a look at how filters can convolve images, providing the basis of convolutional layers, as well as how pooling can reduce the image size while maintaining the features of an image. In the next part, you'll start implementing convolutions and pooling in code, and you'll see how these can improve the fashion MNIST classifier. After that, you'll take on some more real-world and more challenging images. And you can learn how convolutions can help you to classify them. Next: Part 4 - Coding with Convolutional Neural Networks
https://techplanet.today/post/machine-learning-foundations-part-3-convolutions-and-pooling
CC-MAIN-2020-29
refinedweb
1,875
72.05
Tech Off Thread7 posts Forum Read Only This forum has been made read only by the site admins. No new threads or comments can be added. Problem with namespaces in ASP.NET Conversation locked This conversation has been locked by the site admins. No new comments can be made. Hello, I constructed a public class with a namespace named 'Data_Squeeze' and saved it in a .cs file and pushed it to App_Code folder of my website In one of my webpage's code behind, I referenced the namespace with the 'using' directive, and successfully test-ran the project on my local IIS server. However, when I tried it on my university's remote server it failed with the error message : CS0246: The type or namespace name 'Data_Squeeze' could not be found (are you missing a using directive or an assembly reference?) I followed some suggestions posted online, like checking for spelling mistakes, proper referencing, etc. But no success as yet. I am using MS Visual Studio 2008 with IIS 6.0. I don't have access to set directory settings for my website on the remote server. All I can do is upload my files and run the application. Appreciate you recommendations... -- Prasanna I ran into this problem recently, too. Make sure the Build action is set to "compile" in properties for the specific code-files or it wont get added to the assembly. I believe if you're using VS 2008, you don't need to place the files in an App_code directory anyway. Is your website's application root defined properly? Since you say it isn't your webserver you don't have control over the application scope. I'd look into that. "Is your website's application root defined properly? Since you say it isn't your webserver you don't have control over the application scope. I'd look into that" -- Can you please elaborate on that? My premises is based on the following error message which I got while trying to run the app on remote serve -- Parser Error Message: It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS. Source Error <In web.config>: Comment removed at user's request.
https://channel9.msdn.com/Forums/TechOff/464439-Problem-with-namespaces-in-ASPNET
CC-MAIN-2017-26
refinedweb
388
66.13
EJB AutoGenerated ID and Persistance Question (2 messages)Hello! Just started using EJB 3.0 so bare with me please.. The question is regarding an entity with an auto generated ID public class Appointment implements Serializable { ... private int appid; ... @Id @GeneratedValue @Column(name="APP_ID") public int getAppId( ) { return appid; } public void setAppId(int pk) { appid = pk; } ... } When I take an instance of this POJO entity and persist it entitymanager.persist(appointment); I would like to know what appId it was given since I need this value for the next step in my process. I cannot use entitymanager.find(..) since I don't know the PK and performing a query on all the other columns cant be done since they are not unique. There must be a better way.. Does anyone know? Thanks a lot! Scott Threaded Messages (2) - Re:Resolved by fdsa fdsa on August 04 2008 16:07 EDT - EJB AutoGenerated ID and Persistance Question - reply by Muthu Kumar on August 11 2008 00:10 EDT Re:Resolved[ Go to top ] Problem resolved.. Thanks anyways - Posted by: fdsa fdsa - Posted on: August 04 2008 16:07 EDT - in response to fdsa fdsa EJB AutoGenerated ID and Persistance Question - reply[ Go to top ] Hi, Suppose, 1 .Module in the entity-is having the getter/setter method 2. After Module entity is persisted, then you can get the Primary key value entitymanager.persist(module); By debug mode,check primary key value present/ or not in the module entity attributes after calling the above method. I think, this will solve your problem. - Posted by: Muthu Kumar - Posted on: August 11 2008 00:10 EDT - in response to fdsa fdsa
http://www.theserverside.com/discussions/thread.tss?thread_id=50222
CC-MAIN-2015-35
refinedweb
277
58.38
Introduction: Line Follower Robot Using Only One IR Sensor Hello everyone, Today we will make a line follower robot. Nope, its not like normal line followers with two sensors trying to keep the robot in the center of the line. Instead it will use only one sensor. I have mounted the sensor on a servo motor to get the readings from both the sides of a line. Note : This project is something that I tried for the first time and its working but not as per my expectations. So please send me your feedback on how I could make it better. Maybe using interrupts or timers will improve its performance. Do let me know in the comments section. Step 1: Working of the Project Now we all must be aware of how the basic line follower robot works. When both the sensors are on the white line, the robot moves forward. When one of the sensor is on the black line, the motor opposite to that sensor turns on and pushes it back to the other side of the line. This is how the basic line follower works. Now this one uses similar principle but it uses only one sensor. You might have a question, "Then how do you get the readings from the other side of the line?" Well, for that I mounted the sensor on a servo motor. When the motor is at 0 degrees, the sensor takes 1st reading and when the motor is at 180 degrees, the sensor takes the second reading. Both these readings are then compared and the robot is given instructions to move accordingly. Hope you like this project. Do support me by liking this video. Also comment your views on this project. Let's get started !!! Step 2: Gather the Supplies I would suggest you guys to buy the components from UTSource.net . They provide high quality components at reasonable rates with on time delivery. If you need a professional PCB, then they also provide PCB Services at affordable rates. Do check them out. The things we need for this project are - 2. L293D Motor Driver Module 3. IR Sensor 4. Servo Motor 5. 9 V Battery x 2 6. Robot Chassis with Wheels and Motors 7. Breadboard 8. Header Wires That's just it. Once you gather all the supplies we are good to go. Step 3: Circuit Diagram Follow the circuit diagram from above to make all the connections. The motors are connected to the motor driver module. And the motor driver receives input from the Arduino Board. The Ir sensor is connected to the digital pin 3 and the Servo motor is connected to the digital pin 5. I used two batteries to power the Arduino and the motor driver module separately. You can also go with lithium ion packs instead. Do check your connections twice to make sure everything is good. Once you do that we can move forward. Step 4: Coding Now download the code or you can just copy it from here. #include <servo.h> int sensorValue1; int sensorValue2; //Motor A right const int motorPin1 = 6; const int motorPin2 = 9; //Motor B left const int motorPin3 = 10; const int motorPin4 = 11; void setup() { Serial.begin(9600); myservo.attach(5); myservo.write(180); pinMode(motorPin1, OUTPUT); pinMode(motorPin2, OUTPUT); pinMode(motorPin3, OUTPUT); pinMode(motorPin4, OUTPUT); } void loop() { digitalWrite(motorPin1, LOW);//RIGHT WHEEL digitalWrite(motorPin2, LOW);//STOP digitalWrite(motorPin3, LOW );//LEFT WHEEL digitalWrite(motorPin4, LOW); myservo.write(180); //0 = right 180 = left sensorValue1 = digitalRead(3);//read at 180 (left) delay(1000); myservo.write(0); sensorValue2 = digitalRead(3);//read at 0 (right) // Serial.println("S1"); // Serial.println(sensorValue1);//LEFT // Serial.println("S2"); // Serial.println(sensorValue2);//RIGHT // ADJUST THE DELAYS FOR BETTER SPEEDS. BUT MORE THE SPEED THE HIGHER IS THE // CHANCE OF THE SENSOR SKIPPING A READING delay(500); check(); delay(100); } void check() { if(sensorValue1==HIGH && sensorValue2==HIGH)//WW { Serial.println("Go Fwd"); digitalWrite(motorPin1, LOW);//RIGHT WHEEL digitalWrite(motorPin2, HIGH);//FORWARD digitalWrite(motorPin3, LOW );//LEFT WHEEL digitalWrite(motorPin4, HIGH); } else if(sensorValue1==LOW && sensorValue2==HIGH)//BW { Serial.println("Go RIGHT"); digitalWrite(motorPin1, HIGH);//RIGHT WHEEL digitalWrite(motorPin2, LOW);//RIGHT digitalWrite(motorPin3, LOW );//LEFT WHEEL digitalWrite(motorPin4, HIGH); } else if(sensorValue1==HIGH && sensorValue2==LOW)//WB { Serial.println("Go LEFT"); digitalWrite(motorPin1, LOW);//RIGHT WHEEL digitalWrite(motorPin2, HIGH);//LEFT digitalWrite(motorPin3, HIGH );//LEFT WHEEL digitalWrite(motorPin4, LOW); } else if(sensorValue1==LOW && sensorValue2==LOW)//BB { Serial.println("STOP"); digitalWrite(motorPin1, LOW);//RIGHT WHEEL digitalWrite(motorPin2, LOW);//STOP digitalWrite(motorPin3, LOW );//LEFT WHEEL digitalWrite(motorPin4, LOW); } }</servo.h> As I explained in the working the code is pretty straight forward. The motor is initially at 180 degree when it takes first reading and then the motor rotates to 0 degrees and takes the second reading. Both these readings are used to see if the robot is following the line accurately or not. If you have trouble understanding this code, feel free to drop a comment below. I will try my best to help you out. Now compile and upload the code to your Arduino Board and then connect the batteries. Attachments Step 5: Final Project Remember to adjust the preset pot such that it can detect the white and black lines without any problem. I have attached few images and a video to show you how the project works. I faced few problems at the turns with the sensor missing a reading. And I want you guys to solve that problem. Also update me if you make this project. I would like to hear your experience about it. Hope you enjoyed this kind of revised version of the line follower with just one sensor. Do show your support. Also follow me for more projects like this. That's it for today. See you guys with another instructable soon. Thank you. Be the First to Share Recommendations Discussions
https://www.instructables.com/Line-Follower-Robot-Using-Only-One-Sensor/
CC-MAIN-2021-04
refinedweb
976
58.69
We use the const qualifier to declare a variable as constant. That means that we cannot change the value once the variable has been initialized. Using const has a very big benefit. For example, if you have a constant value like the value of PI, you wouldn't like any part of the program to modify that value. So you should declare that as a const. Objects declared with const-qualified types may be placed in read-only memory by the compiler, and if the address of a const object is never taken in a program, it may not be stored at all. For example, #include<iostream> using namespace std; int main() { const int x = 10; x = 12; return 0; } This program would produce an error as we have tried to reassign a const value.
https://www.tutorialspoint.com/What-is-the-const-Keyword-in-Cplusplus
CC-MAIN-2021-43
refinedweb
135
60.95
Bishwock is a chess figure that consists of three squares resembling an "L-bar". This figure can be rotated by 90, 180 and 270 degrees so it can have four possible states: XX XX .X X. X. .X XX XX Bishwocks don't attack any squares and can even occupy on the adjacent squares as long as they don't occupy the same square. Vasya has a board with 2×n2×n squares onto which he wants to put some bishwocks. To his dismay, several squares on this board are already occupied by pawns and Vasya can't put bishwocks there. However, pawns also don't attack bishwocks and they can occupy adjacent squares peacefully. Knowing the positions of pawns on the board, help Vasya to determine the maximum amount of bishwocks he can put onto the board so that they wouldn't occupy the same squares and wouldn't occupy squares with pawns. The input contains two nonempty strings that describe Vasya's board. Those strings contain only symbols "0" (zero) that denote the empty squares and symbols "X" (uppercase English letter) that denote the squares occupied by pawns. Strings are nonempty and are of the same length that does not exceed 100100. Output a single integer — the maximum amount of bishwocks that can be placed onto the given board. 00 00 1 00X00X0XXX0 0XXX0X00X00 4 0X0X0 0X0X0 0 0XXX0 00000 2 题意:给出2*n的矩阵,0可放,X不可放,问能放多少个L形,L可旋转。 思路:从左往右遍历, 遇到一列都是0的 贪心的先往左放,再往右放,类似开关问题 #include <iostream> #include <cstring> #include <cstdio> #include <map> #include <algorithm> using namespace std; typedef long long ll; const int maxn = 1e2 + 5; char str[2][maxn]; int main() { int t; scanf("%s", str[0]); scanf("%s", str[1]); int len = strlen(str[0]); int ans = 0; for(int i = 0; i < len; i++) { if(str[0][i] == '0' && str[1][i] == '0') { if(i-1 >= 0 && str[0][i-1] == '0') { str[0][i-1] = 'X'; str[0][i] = 'X'; str[1][i] = 'X'; ans++; } else if(i-1 >= 0 && str[1][i-1] == '0') { str[1][i-1] = 'X'; str[0][i] = 'X'; str[1][i] = 'X'; ans++; } else if(str[0][i+1] == '0') { str[0][i+1] = 'X'; str[0][i] = 'X'; str[1][i] = 'X'; ans++; } else if(str[1][i+1] == '0') { str[1][i+1] = 'X'; str[0][i] = 'X'; str[1][i] = 'X'; ans++; } // cout << i << ' ' <<ans << endl; } } printf("%d\n", ans); return 0; }
https://blog.csdn.net/qq_34374664/article/details/80939313
CC-MAIN-2018-34
refinedweb
407
69.25
This post has a very slim target audience: developers who - are not familiar with gradle - are not familiar with android development - have some exposure to Java (enough to create a class) - have done mobile development (Windows Phone/iOS) - are interested in writing "pure" unit tests for Android - are working with an existing Android project that succesfully builds and runs If you meet all those criteria, come join me on a journey that seems (mostly) poorly documented. Perhaps I haven't been searching for the right terms, but regardless I'm going to put my findings here. I'm currently using Android Studio 0.8.9. We will assume the following project struture for the android app. The libraries folder is completely optional; the main thing is that the android-dependant app source code is in src. $/ |-app |-build |-libraries |-facebook |-src |-androidTest |-main |-assets |-java |-com..... |-res - build.gradle - build.gradle - settings.gradle Here's what we want to accomplish: - add a "regular" or "pure" Java module so that it can be used by the Android application - be able to write jUnit tests for this module and then run these tests from Android Studio 1. Adding the Java module - Create a puredirectory under libraries. - Create a src/main/javadirectory under pure(for source code). Under that, create the appropriate com.example.puredirectory. - Add an empty Java class to the last-created directory (for this example, I'm using MyClass) - Create a file called build.gradlein your puredirectory. It only needs to contain a single line: apply plugin: "java". (Note: if you have the 1.8 JDK installed, you have to force your pure Java module to use 1.7, as that's what Android currently supports. If you do not, you will get a very weird build message like [ERROR] bad class file magic (cafebabe) or version (0035.0000). To do this, add the following two lines to build.gradle: sourceCompatibility = 1.7 targetCompatibility = 1.7 We now have this: $/ |-app |-build |-libraries |-facebook |-pure |-src |-main |-java |-com... SampleClass.java - build.gradle |-src ... - build.gradle - settings.gradle - To get our module to build, update settings.gradlein the root folder. include ....., ':pure' project('pure').projectDir = new File('libraries/pure') At this point you should be able to build your app and new module successfully. Using the module from an Android app We can ensure the "pure" module is accessible from our Android application by attempting to use it. - In $/app/build.gradle, add compile project(':pure')to the dependenciessection. - Android Studio will probably tell you it needs to sync (let it). If you look at the Gradle Console, you should see :pure:compileJava, :pure:processResources, :pure:classesand :pure:jarin the output. - Reference your new object from any class in your Android application. It should still build and run as before. 2. Adding jUnit tests - Give your sample class an add()method that takes two integers and returns their sum. We need something to test :) - Add the following to build.gradle(the one in pure) dependencies { testCompile group: 'junit', name: 'junit', version: '4.11+' } (I'm assuming your main project already has repositories setup. If not, add repositories { jcenter() } as well.) - Create a new class in $/libraries/pure/src/test/java/com.... (For this example, I have MyClassTest). Make sure it is public. - Add a test to it. As an example, here's what I have: import org.junit.Test; import static org.junit.Assert.assertEquals; public class MyClassTest { @Test public void testAdd_CanAddTwoNumbers() { MyClass sut = new MyClass(); int result = sut.add(3, 4); assertEquals(7, result); } } - Make sure everything still builds. - Right-click on your class and choose 'Run {MyClassTest}'. The output should show "all tests passed."
http://www.jedidja.ca/author/jedidja-bourgeois/
CC-MAIN-2018-05
refinedweb
616
58.99
Today we’re excited to roll out our beta release of TypeScript 2.0. If you’re not familiar with TypeScript yet, you can start learning it today on our website. To get your hands on the beta, you can download TypeScript 2.0 Beta for Visual Studio 2015 (which will require VS 2015 Update 3), or just run npm install -g typescript@beta This release includes plenty of new features, such as our new workflow for getting .d.ts files, but here’s a couple more features just to get an idea of what else is in store.. let foo: string = null; // Error! What if you wanted to make something nullable? Well we’ve brought two new types to the scene: null and undefined. As you might expect, null can only contain null, and undefined only contains undefined. They’re not totally useful on their own, but you can use them in a union type to describe whether something could be null/ undefined. let foo: string | null = null; // Okay! Because you might often know better than the type system, we’ve also introduced a postfix ! operator that takes null and undefined out of the type of any expression. declare let strs: string[] | undefined; // Error! 'strs' is possibly undefined. let upperCased = strs.map(s => s.toUpperCase()); // 'strs!' means we're sure it can't be 'undefined', so we can call 'map' on it. let lowerCased = strs!.map(s => s.toLowerCase());. For instance, consider this function. /** * @param recipients An array of recipients, or a comma-separated list of recipients. * @param body Primary content of the message. */ function sendMessage(recipients: string | string[], body: string) { if (typeof recipients === "string") { recipients = recipients.split(","); } // TypeScript knows that 'recipients' is a 'string[]' here. recipients = recipients.filter(isValidAddress); for (let r of recipients) { // ... } } Notice that after the assignment within the if block, TypeScript understood that it had to be dealing with an array of strings. This sort of thing can catch issues early on and save you from spending time on debugging. let bestItem: Item; for (let item of items) { if (item.id === 42) bestItem = item; } // Error! 'bestItem' might not have been initialized if 'items' was empty. let itemName = bestItem.name; We owe a major thanks to Ivo Gabe de Wolff for his work and involvement in implementing this feature, which started out with his thesis project and grew into part of TypeScript itself. Easier Module Declarations Sometimes you want to just tell TypeScript that a module exists, and you might not care what its shape is. It used to be that you’d have to write something like this: declare module "foo" { var x: any; export = x; } But that’s a hassle, so we made it easier and got rid of the boilerplate. In TypeScript 2.0 you can just write declare module "foo"; declare module "bar"; When you’re ready to finally outline the shape of a module, you can come back to these declarations and define the structure you need. What if you you depend on a package with lots of modules? Writing those out for each module might be a pain, but TypeScript 2.0 makes that easy too by allowing wildcards in these declarations! declare module "foo/*"; Now you can import any path that starts with foo/ and TypeScript will assume it exists. You can take advantage of this if your module loader understands how to import based on a certain patterns too. For example: declare module "*!text" { const content: string; export = content; } Now whenever you import a path ending with !text, TypeScript will understand that the import should be typed as a string. import text = require("./hello.txt!text"); text.toLowerCase(); Next Steps One feature you might be wondering about is support for async functions in ES3 & ES5. Originally, this was slated for the 2.0 release; however, to reasonably implement async/ await, we needed to rewrite TypeScript’s emitter as a series of tree transformations. Doing so, while keeping TypeScript fast, has required a lot of work and attention to detail. While we feel confident in today’s implementation, confidence is no match for thorough testing, and more time is needed for async/ awaitto stabilize. You can expect it in TypeScript 2.1, and if you’d like to track the progress, the pull request is currently open on GitHub. TypeScript 2.0 is still packed with many useful new features, and we’ll be coming out with more details as time goes on. If you’re curious to hear more about what’s new, you can take a look at our wiki. In the coming weeks, a more stable release candidate will be coming out, with the final product landing not too far after. We’d love to hear any feedback you have, either in the comments below or on GitHub. Happy hacking! Join the conversationAdd Comment The only thing I wanted was ES5 async/await, this is what has been holding me back since the beginning. Boo 🙁 Boo indeed. I was anticipating this release for async \ await for many reasons. This WAS on the roadmap for 1.6 from memory and we’re still waiting. Maybe just delete the roadmap to stop pissing people off when you don’t deliver the major feature a lot of devs have been waiting for. Or at least retrospectively change the roadmap so we have nothing to base our arguments on. You still can make you own language, here() the mine with async capabilities. async/await can be used now by targeting ES6 and compiling the result with Babel. It’s inconvenient, but it works fine and using async/await in the browser is a real joy. 🙂 You can also use async/await now now if you use Dart instead. 😀 Does anybody still use Dart? That one guy at Google If only google had done a better job advocating Dart. It is a fantastic language Not having async/await shouldn’t be holding you back. Just use promises. A call in a for loop that you want to call await on is very hard to do with just promises. It’s a bit inconvenient but not very hard. You can have an array of promises use a recursive function to loop through it. I’ve used a reduce function to chain promises together to accomplish that. It reads as well as a FOR OF loop, especially if you can use fat arrow syntax. Non nullable types are HUGE. Thanks guys. Pity that async await has missed 2.0 I’ve been waiting for it since October 2012. 🙂 I use async/await in ts since 1.6 or something.. Or you mean async/await for ES5? It’s emulated by ES6 generators now. +1 for all the new features, and especially the improved control flow analysis. Awesome work TS team! Agreed! Nice work! Great news, the improved type checking will definitely help make our company’s codebase more robust! Too bad ES5 generators didn’t make it in 2.0, but I understand that the new transformation-based emitter needs some more work. We already have a workaround in place by transpiling to ES6 and piping through Babel to get ES5 generators. Looks like we’ll keep that extra Babel step in our build chain for just a bit longer. Can someone explain this feature to me: “import text = require(“./hello.txt!text”);”? I’m not that familiar with TS but why was this implemented in this way and not with an additional argument? This is a common format for JS module loader to represent plugins. For instance requirejs, uses the the prefix to detonate the plugin name, so `text!./hello.txt` would be a request to load the file `./hello.txt` using the `text` loader plugin, which returns you the file contents as a string. similarly `json!./resource.json` returns you the result of calling `json.parse` on `./resource.json` as an object. you can find more details in: Great news! I’ve been anxious for TS 2.0 for months now. Non-null types is *HUGE*! And is really a requirement for modern languages, IMO. It makes perfect sense in TypeScript, since nullability is really part of the type system. Bummed about async/await delayed. But only until 2.1, which I’d imagine will still be released this year. Gut feeling is that async/await will make the largest impact on my codebases. Great job, TS team and contributors. 2.0 is a HUGE release! Congrats, there is so much goodness: null checks, flow analysis, better lib management… One question, you say: “or just run npm install -g typescript@beta” Does it mean VS uses the global command-line TS when there is one, or is this intended for people not using VS? For VS 2015 please use the standalone installer as per the link above. If you are using the commandline compiler through npm then use the npm install command. How do I enable the strict null checks in Visual Studio? I’m not seeing a compiler option in the project property page. I figured it out. It looks like we need to modify the .csproj to include the flag. I blogged how to do it here: You have two options, the easiest is to add a tsconfig.json file to your project, if you do not have one already, and set `”strictNullChecks”: true`. The other as noted in your blog is to set the MSBuild property `true` in your project. you can find more information about MSBuild propeorties in I prefer to have tsconfig.json in my projects. By the way thank you for an update docs for MSBuild! is there a download for the VS15 Preview? No. TypeScript 2.0-beta will be published in box for the next preview of VS15. Not excited at all. null-check and type analysis are barely usefull. Without async / await ES3/ES5 does not make sense to release any new version. Strict null checks, readonly flags, discriminated unions, and specifying the type of “this” are all HUGE DEALS. Can’t wait for this release. Which, by the way, when is? Guys, really well done. On top of the non-nullable types, I also really like the glob support in tsconfig.json and “baseUrl” module support enhancement — thanks for those. Non-nullable types are fantastic, it’ll make a big difference to our large code base. As will wildcards in module names. Thanks team TypeScript! Absolutely an amazing work! The web will never be the same after TypeScript. We can wait a little bit more for the async/await. For now, better encapsulation and non-nullables types are a great gift. Improved control flow analysis is cool and useful. I’m not sure about the nullable types though. I’d preferred if you could declare it the other way round, e.g. let s: string not null; The way it is now, it can turn out hard to use the –strictNullChecks option in an existing code basis. it is very great. Great news! Small question. There is this example in wiki, Shouldn’t “b” in “let b = x && f(x);” be type of “number | string| undefined | null”, because it might be, 0, null, undefined, of string value from function? As a matter of fact, we will consider amending this behavior in 2.1 when numeric literal types come in and we can express ‘0’ as a type. Nice! you guy amaze me! It can NaN as well. BTW, are you going to distinguish between +0 and -0? WTF! I was eagerly waiting for ES5 async/await. This is so disappointing 🙁 Can someone explain me, why is async/await so much desired ? Maybe I’m shortsighted and closed in my browser-side programming cage, but I can’t see it as enabler for some new continent of stunning possibilities. In fact I can imagine it only a bit simplifying AJAX requests… Aysnc/await just cleans up a lot of asynchronous code instead of chaining callbacks or promises. It really boils down to cleaner syntax for the developer that reads more easily and IMO is easier to debug. You can target ES6 right now with typescript and see how they compile async/await into promises and generators, its pretty cool. This is a good example of the difference in syntax for the same behavior. AJAX is one example of an asynchronous process but there are more JS libraries taking advantage of Promises so I think this feature will become more important for the future of Javascript. Just waiting for async/await. Not present, 🙁 why the null aware operator couldn’t have ? instead of ! the elvis operator is more obvious @noor – In C# for example the x?.y operator is the null conditional member access, and returns null if the left hand operand is null. This means the compiler introduces a null check for us in the code. The new TypeScript x!.y operator seems to be slightly different – you are telling the compiler that you are sure x is not null, so just go ahead and make the call stifling the possible null compiler warning. The compiler is not introducing a null check for us. Robert It’s more like Apple Swift ! operator WIN 10, VS /w update3, just installed TypeScript_Dev14full. VS now highlighting “document.body” and “document.createElement” with red underline as if this properties does not exist on type Document. In error list: Error TS2339 Property ‘body’ does not exist on type ‘Document’. Error TS2339 Property ‘createElement’ does not exist on type ‘Document’. Error TS2339 Property ‘fillStyle’ does not exist on type ‘CanvasRenderingContext2D’. Error TS2339 Property ‘fillRect’ does not exist on type ‘CanvasRenderingContext2D’. … Is it a bug, or should I install additional typings to fix this? Deviating from the ES standard syntax-wise is a dangerous path. Maybe I can understand keywords like ‘readonly’ that are self-explanatory and have limited impact on the syntax, but the postfix operator crosses that line. The whole argument for using TypeScript was that it built upon standard EcmaScript syntax. I can’t help but wonder what will happen when the postfix operator will be added to EcmaScript, but with a different meaning. How will TypeScript reconcile its special operator with the standard one? Typescript is designed to be a super-set of the language, so it should be allowed and expected to *add* syntax when allowed. The postfix ! operator appears to just be a shorthand for type assertions which are already non-standard. strs!.map(s => s.toLowerCase()); is the same as (strs as string[]).map(s => s.toLowerCase()) which is the same as (strs).map(s => s.toLowerCase()). Actually, the ‘as’ syntax for type assertions is a good example of what happens when syntax collides. It was added to resolve the syntactic ambiguity between jsx and existing typescript syntax. I’d also hope that as typescript becomes more popular the ES standard process would take things like this into account when developing features. Nice work guys! Non-nullables are huge for me. I encountered this exact problem, and now you provided a solution. Perfect. ===== PLEASE DO NOT DELETE COMMENTS!!!!!! ========= You may want to take a look at Scala.js () which translates Scala to JavaScript (A safer way to build robust front-end web applications!). There is a comparison table which compares Scala.js against Typescript. Look like demand for async (and disappointment by not implementing) is huge. So, if adding it is really few weeks away, as githubs states, then it will be wise to create intermediate version TS 2.05 which is 2.0 + async, than forcing devs for another months to wait, when rest of 2.1 features will be implemented, polished and tested. TypeScript has nightly releases out of the master branch. Once the feature lands in the master branch, it will be available to every one to give it a try. We always love to get feedback for new features. You can find more information about nightly releases and how to use them at: I’ve been able to use async await with Typescript… The key is to transpile Typescript to ES6 and then use Babel to go from ES6 to ES5. Sounds ugly but it’s not so bad; our webpack setup with awesome-typescript-loader actually makes it fairly easy due to webpack’s chainable loaders. Aslo, non-nullable types FTW. I also like the new module feature; rehabilitating with legacy code just got a lot easier. Webpack does help in that regard, but the performance is horrible. You have to parse each file 3 times (first pass = TS, second pass = Babel, third pass = Webpack) and because of loader abstraction there is no way to cache results between passes. Even with incremental compilation the performance degrades as you also need to generate source maps on each pass. It adds complexity to an already complicated build process and makes it harder to debug when something goes wrong either in the build process or with the generated code. Perhaps – It hasn’t been problematic for me yet. That said, then the typescript compiler supports it natively I’ll happily switch. For now, slow but working is still better than not working 🙂 Of course the feature I really want in the short term is object spread 🙂 To all those complaining about the async/await delay, go take a look at and see some of the issues/discussions/blockers that are actually causing the delay. It’s taking time because they’re doing it properly. Aw, that’s no fun! Can’t we carry on complaining bitterly about something completely awesome that we get entirely for free? Good job guys! I was waiting for this for a while and I’m so damn excited to finally try it out. Heads up: there appears to be a rather serious bug in TypeScript 2.0 beta for Visual Studio that prevents web apps from publishing. The issue is described here: Unfortunately, this is a blocker for me, so in lieu of a workaround, I’ll be uninstalling TS 2.0 beta for VS. Switch to WebStorm or IDEA. Is there a way to restrict the strict null checks only to *my* code, so that library d.ts files are not affected? Does this release add support for `npm install @types\package` to visual studio? I upgraded to tsc 2.1.0-dev.20160919 in my linux / npm /webpack environment, and I’m getting a myriad of @type errors (core-js, webpack, node, etc), such as: ERROR in [default] /home/username/node_modules/@types/core-js/index.d.ts:21:13 Duplicate identifier ‘PropertyKey’. ERROR in [default] /home/username/node_modules/@types/node/index.d.ts:110:12 Subsequent variable declarations must have the same type. Variable ‘Buffer’ must be of type ‘{ new (str: string, encoding?: string): Buffer; new (size: number): Buffer; new (array: Uint8Arra…’, but here has type ‘{ new (str: string, encoding?: string): Buffer; new (size: number): Buffer; new (array: Uint8Arra…’. Not even I’m barking up the right tree at this point.
https://blogs.msdn.microsoft.com/typescript/2016/07/11/announcing-typescript-2-0-beta/?replytocom=21146
CC-MAIN-2018-09
refinedweb
3,178
67.25
We have realized a simple haarcascade-based face detection with openCV. Images are acquired from a Basler dart camera. You can use that example also for any Basler 2D cameras. This is a simple example of running face detection with OpenCV on images acquired from a Basler camera. Please ensure you have pylon, PyPylon and OpenCV installed. See the guide here on how to set up the required software on your system. With the launch of Imaginghub Basler is releasing a fully functional Python 3 wrapper for the Pylon C++ API called PyPylon. In this demo I would like to give you an impression of the simplicity of writing an image processing application straight forward with Python. Furthermore I will run the project on an ultra-low budget setup like the Raspberry Pi to give you a feeling of how easy and affordable embedded vison can be. So let’s dive right in! Basically there are only two things needed for the basic setup. One the one side you need an Basler camera to be able to use the Python Wrapper. And on the other side some sort of single-board-computer. As we are talking about an embedded setup I suggest one of the dart USB3 Vison cameras which are perfect for a low-budget setup like this. You can choose most of the available SBCs out there. It just has to have an ARMv7 architecture because PyPylon is only released therefore. I will use Raspbian Jessie as operating system, but any Linux distribution should work equally. Just make sure that you use at least a 16GB SD-Card because we need a lot of disk storage for compiling. After initial setup I recommend setting the Pi to ”boot only to command line” to save some resources. You can do this under “sudo raspi-config” and then “boot_behaviour”. From now on you can do every command of this guide via SSH as well so the choice is up to you. For that you will only need the IP Address by writing “ip addr show”. For this setup I recommend Python 3.5 which already is fully compatible with PyPylon. Follow this guide to get PyPylon and OpenCV up and running: From Zero to Image A very smart way of writing Python code is using Jupyter Notebook. It lets you connect to a Web-based Python IDE from any machine in your network. So when you’re not working directly on the Pi, this is great way to write your first samples very straight forward. Here is a good tutorial for getting it done. When you are familiar with Pylons C++ API you will feel very familiar with the Python Wrapper. All functions are the same but only in Python typical syntax. When you are searching for more advanced features, just check out the detailed C++ Programmers-guide. Grabbing an image only requires very few steps. I recommend just using this short demo as a first impression and using the sample code afterwards. First the InstantCamera has to be initialized: import pypylon.pylon as py icam = py.InstantCamera(py.TlFactory.GetInstance().CreateFirstDevice()) Then just open the Camera and grab an image: icam.Open() img = icam.GrabOne(4000) Now you’ve got the image as an object. To get it as an numpy array for OpenCV just do the following: img = img.Array You can change each camera parameter within PyPylon, but it’s a lot easier to create a profile in Pylon Viewer and load it like this: icam.UserSetSelector="UserSet1" icam.UserSetLoad.Execute() One important setting I would like to mention is the PixelFormat. The Dart supports RGB8 output, which makes the handling in OpenCV a lot easier. Safe this setting in the profile or set it within Python by: icam.PixelFormat = "RGB8" If you want to see the picture in Python you can use for example Matplotlibs pylab class and just write sudo apt-get install python-matplotlib sudo apt-get install python3-matplotlib import matplotlib.pyplot as plt import cv2 plt.imshow(cv2.cvtColor(img, cv2.COLOR_RGB2BGR)) The color-conversion is needed, because plt expects the image to be in BGR format. plt.show() With OpenCV face recognition gets pretty simple with the Haar Cascade class. If you want to understand the used algorithm I recommend the OpenCV docs site and this video. You will need an Haar Cascade XML file, which contains the parameters of all kinds of faces. You can find a ton of them for different kinds of objects in the internet or even create your own. First import it with this code: face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') In some cases the classifier doesn't load succefully from the file. In these cases you should add the whole path (f.e. '/opt/opencv-3.2.0/data/haarcascades/haarcascade_frontalface_default.xml'). Now you can run the face_cascade function. It will return a list of faces which we print into the image for illustration. faces = face_cascade.detectMultiScale(img, 1.3, 5) for (x,y,w,h) in faces: cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) Now just show the edited image: plt.imshow(cv2.cvtColor(img, cv2.COLOR_RGB2BGR)) plt.show() As I mentioned I recommend using Jupyter Notebook for your first PyPylon approaches. I will provide not only a Python but also a Jupyter Notebook code sample. Therefore click on the "Code" tab.
https://imaginghub.com/projects/97-face-detection-on-raspberry-pi
CC-MAIN-2018-17
refinedweb
903
65.93
I can't seem to declare a map in certain places: is fine at the top of main(), but I get one of two kinds of error when I use it in an included file:is fine at the top of main(), but I get one of two kinds of error when I use it in an included file:Code: map<string,int> testdata; error: ISO C++ forbids declaration of ‘map’ with no type I tried adding spaces inside the angle brackets, same thing. The other error is: error: expected primary-expression before ‘,’ token error: expected primary-expression before ‘>’ token which is what I would get if I failed to #include<map>, except then I would also get "error: ‘map’ was not declared in this scope". Everything is within scope of using namespace std. Anyone seen this before? I'm using gcc 4.3.2. I thot maybe I had a bracket missing somewhere, but it compiles and runs fine...just I can't use a map :(
http://cboard.cprogramming.com/cplusplus-programming/125280-wacko-map-error-printable-thread.html
CC-MAIN-2014-42
refinedweb
167
66.07
So, recently deciding that I want try and learn C++, I picked up "Teach Yourself C++ in 24 Hours" for a starting point. All works well, until Hour 2 ( ) where I come to a problem - I type in the code exactly as it is in the book, compile it, and when I run the program, the output is different than what is shown in the book.) where I come to a problem - I type in the code exactly as it is in the book, compile it, and when I run the program, the output is different than what is shown in the book. Here is the code: Here is what is supposed to come out:Here is what is supposed to come out:Code:#include <iostream> int Add (int x, int y) { std::cout << "In Add(), recieved " << x << " and " << y << "\n"; return (x+y); } int main() { std::cout << "I'm in main()!\n"; std::cout << "\nCalling Add() \n"; std::cout << "The value returned is: " << Add(3,4); std::cout << "\nBack in main().\n"; std::cout << "\nExiting...\n\n"; return 0; } I'm in main()! Calling Add() In Add(), received 3 and 4 The value returned is: 7 Back in main(). Exiting... And, finally, here is what I get: Calling Add() The value returned is: In Add(), received 3 and 4 7 Back in main(). Exiting... A few notes - I use Mac OS X 10.4.6, write the code in Xcode, and use the Terminal to compile. I thought maybe the output was different because I am running OS X, but that does not make any sense to me. I have read the code over and over, just to make sure I typed everything correctly. Sorry for the long post, and not sure if I broke any rules by posting code on here, if I did, just left me know. Any help at all on this issue would be greatly appreciated! Thanks, ~eros
https://cboard.cprogramming.com/cplusplus-programming/79228-new-cplusplus.html
CC-MAIN-2017-09
refinedweb
323
76.35
Hey guys, I've done alot of work coding a script that works great in Python. I hope to move it into java then hopefully into an android app. Any advice on getting started? I have searched and searched and cannot really find a good way to do this. I had thought about compiling the script in Jython and going from there but not sure how to use Jython or if it supports the libraries I am using: import sys import csv import re import json import time import string import random import urllib import urllib2 Any pointers would be great. I can send the code to you if you want to see it. It's a script for a game I play and wanted to let friends use it. Thanks
https://www.daniweb.com/programming/software-development/threads/431760/python-to-java-question
CC-MAIN-2018-17
refinedweb
131
78.18
User:Dsventura Contents - 1 Information - 2 OSD600 - 3 GAM670 - XAnimation - 3.1 Source Code - 3.2 Overview - 3.3 Putting It Into The Framework - 3.4 Known Issues - 3.5 References Information Name: Dan Ventura IRC name: danman GAM670 Team: GAM670 Slap Your Grandma Blog: dsventura.blogspot.com GitHub Repository: DanVentura@github OSD600 Firefox Build Building Firefox 4 - Minefield 0.1 Processing.js 946-Converting Char to String Popcorn.js 127-Make it easier to specify subtitles Note: this bug is invalid, however I created subtitle unit tests in the process. (popcorn.subtitle.unit.js and popcorn.subtitle.unit.html) 305-Create Unit tests for subtitle plugin 0.2 Popcorn.js 321-Create plugins/index.html 331-Create a Facebook plugin GAM670 - XAnimation Source Code MeshHierarchy, MeshStructs and XObject Note: add xObject code to Object.h and Object.cpp Overview Animation in DirectX9 can be done using .X files. The .X extension refers to a file containing a Microsoft proprietary format for exported 3D models. This format is similar to COLLADA, except the file parsing is handled by DirectX internally. To export a model in .X format in 3Ds MAX, I used a plugin from PandaSoft called the Panda DirectX Max exporter (link on last page). Once exported, the file contains information each object and maintains their hierarchical relationships between each object. Each object has a frame container and a mesh container. The frame contains information for positioning, while the mesh contains mesh related information such as: bones, textures, etc. To perform skeletal information, the frames must be arranged in an inheritance hierarchy so that the frame's matrix transformations would be relative to it's parent, respectively (Figure 1). (*Source -) Figure 1: Inheritance hierarchy consisting of a body and two arms. (“Left Arm Frame” would be a shoulder or joint. The name in this diagram may be misleading) This hierarchy would be established in 3Ds MAX through linking. For more information on how to use bones and make skeletal animations in 3Ds MAX, refer to the references. In order to properly load this information, we first need to do a little inheritance of some structs to make our lives easier (refer to MeshStructs.h). We need to extend D3DXMESHCONTAINER and D3DXFRAME with some extra data so we can support skinning. Basically, skinning is a technique where you combine the frame (bone) and mesh (skin) matrices so that the mesh's vertex positions will be altered depending on the frame's movement; making the mesh stretch and contract like actual skin. For more information on skinning, refer to the “X File Hierarchy Loading” link in references. Once we have extended the structures, we have to implement the ID3DXAllocateHierarchy interface to support the extra information we've put into these structures and load the file properly. These functions are called internally as the D3DXloadMeshHierarchyFromX function parses the .X file. (refer to MeshHierarchy.h) To put all of this into the framework, we create an XObject class which is derived from Object. This will hold model information as well as the animation controller. It will also hold information that allows us to change animation sets and the speed of the animation. (refer to XObject.h) Putting It Into The Framework Configuration.h Assuming you put your animations into ../../resources/animations, put this into config: #define ANIMATION_DIRECTORY L"resources\\animations" The utilities function will handle going up 2 directory levels. Display.cpp Pass the display device to XObject (Display::setup()): XObject::connectDevice(d3dd); Utilities.cpp 1. Add a prototype to iUtilities.h: void UpALevel(wchar_t* dir, int numOfLvls = 1); 2. Include this in Utilities.cpp: #define WIN32_LEAN_AND_MEAN #include <windows.h> // for SetCurrentDirectory() 3. Here's the Utilities.cpp function: void UpALevel(wchar_t* dir, int numOfLvls){ int i = 0; for(int x = 0; x < numOfLvls; x++){ i = strlen(dir)-1; if(dir[i] == L'\\'){ dir[i] = NULL; i--; } for(i; dir[i] != L'\\'; i--) dir[i] = NULL; SetCurrentDirectory(dir); } } Object 1. Make some virtual functions for iObject.h and Object.h to control the animation from Design.cpp. Controls include changing the animation set as well as the animation speed. From iObject.h: virtual void animateFaster() = 0; virtual void animateSlower() = 0; virtual void nextAnimation() = 0; virtual void previousAnimation() = 0; ... extern "C" iObject* CreateXObject(wchar_t* filename); Also, make empty virtual functions for the Object class in Object.h 2. Throw this into Object.h: #include "MeshHierarchy.h" 3. Make a default contructor for Object. Textures and what-not are handled already. (Note: May want to change parameters if, for example, you want to make a non-opaque XObject) Object::Object(Colour c) : category(OPAQUE_OBJECT), graphic(NULL), texture(NULL), material(NULL), shine(NULL) { if (!coordinator) error(L"Object::00 Couldn\'t access the Scene Coordinator"); else if(!coordinator->add(this)) error(L"Object::01 Couldn\'t add object to the Scene Coordinator"); } Known Issues CreateFrame() and CreateMeshContainer In both CreateFrame and CreateMeshContainer, name was never set in the original code. If you were to implement this code yourself, make sure you set the frame or mesh container's name to the Name parameter. Forgetting to do this will make the animation controller always return NULL from the D3DXLoadMeshHierarchyFromX call. // for CreateFrame if(Name){ newFrame->Name = new char[strlen(Name)+1]; strcpy(newFrame->Name, Name); newFrame->Name[strlen(Name)] = 0; } DestroyFrame() and DestroyMeshContainer() if(meshContainer->Name) delete []meshContainer->Name; XObject::Draw() This line used to be in the draw function: static DWORD lastTime=timeGetTime(); The problem arose when I put multiple instances of XObject in design. Due to the static keyword, this variable would be shared among all of the animated objects. The first animation would run smoothly, while any animations added afterwords would be extremely slow. This is because this variable tells the function when the last time it drew the object's state along the animation time-line, and each object's time-line is different. To fix this, I made lastTime a data member and initialized it to 0 in the constructor. Scene.cpp - ViewingFrustum() I found an error in Scene.cpp's ViewingFrustum constructor float far = context->get(GF_FR_FAR); float near = context->get(GF_FR_NEAR); Turns out far and near are reserved names from waaay back. Visual Studio won't tell you that though... Throw an underscore at the end of the variable name to fix the problem. float far_ = context->get(GF_FR_FAR); float near_ = context->get(GF_FR_NEAR); ... plane[0] = new Plane(heading, - n_p - near_); plane[1] = new Plane(-heading, n_p + far_); References Panda Exporter (32-bit) XAnimator - Source code and Reference Ditchburn, Keith. “X File Hierarchy Loading”. Toymaker. <> Skeletal Animation in 3Ds MAX Tutorial 3dcognition. “Super Simple Humanoid Character Skeleton using Bones in 3ds Max”. YouTube. <>
https://wiki.cdot.senecacollege.ca/w/index.php?title=User:Dsventura&oldid=61663
CC-MAIN-2020-34
refinedweb
1,113
50.33
The Vaadin Wiki is temporarily in read only mode due to large recent spam attacks. Vaadin TouchKit - Create iPhone applications using Vaadin Note: This article discusses older versions of the Vaadin TouchKit. Please follow the documentation links on the Directory page of Vaadin TouchKit for more up-to-date information. What is TouchKit? # TouchKit is a tool kit that lets you develop applications that look and feel like native iPhone applications using only Vaadin. Let's get started with a short video so you get an idea of what TouchKit can do. Click the image below to view the video (opens in this window). You can browse the actual demo here Should I use TouchKit? # TouchKit has been developed with two main usages in mind. The first usage is, following Vaadin philosophy, to allowing Java developers to create iPhone web applications without having to worry about the underlying HTML and CSS. The other purpose is to give current Vaadin users a possibility to create mobile versions of their existing Vaadin applications. This way, they can use the same server-side code and work with familiar components and tools. TouchKit is still under development, so I don't recommend it yet for production environments. It should, however, be stable enough and have enough features for building simple web apps and getting you started with mobile Vaadin development. Advantages # TouchKit is a purely Java based way of creating web applications that look and feel much like native iPhone applications. TouchKit also supports Gecko based browsers, allowing you to serve a big portion of your mobile users with a single solution. TouchKit applications can be added to the iPhone home screen with a custom icon and splash screen to give a native application feel to them. Disadvantages # As TouchKit applications are web based, there will always be a need for applications to be able to connect to the internet to work. TouchKit is fairly JavaScript heavy, so it may feel slow on older devices. Requirements # TouchKit requires Vaadin 6.3 or above. What does TouchKit contain? # Classes # - TouchPanelis the main component when working with TouchKit. This is the container that takes care of navigation and layout on the client side. You use it by giving it a TouchLayoutto navigate to. The TouchPanelremembers previous layouts, so it can navigate back. It handles the back button for the layout internally. This is also the component that handles animations on supported browsers. - TouchLayoutis a layout for the page content. It can contain any other Vaadin components and layouts. - TouchMenuis the iPhone style menu used by TouchKit. It is built and used similar to the Vaadin MenuBar component. A TouchMenuis built by adding TouchMenuItemsto it. Each TouchMenuItemhas a command that is run when the item is tapped by a user. - MobileApplicationServletextends the default Vaadin ApplicationServletto add a few meta-tags into the generated HTML page header. These meta tags disable resizing of the page and define the location of both application icon and splash screen. These classes also have a client side GWT counterpart, as shown in the class diagram. As a user, you do not have to work with these. You can simply use the server side components and let Vaadin take care of the rest. CSS Theme # TouchKit comes with a theme that minimally overrides the Reindeer theme. It allows the Vaadin content wrapper to expand, as it would otherwise cut of content that is outside the initially visible area. It also hides the default spinner used by Vaadin, as it does not look right in an iPhone application. Images # There are two images in the "touch" theme, icon.pngand startup.png. These are used as the application icon and startup screen, respectively. How do I use TouchKit? # If you skipped the longer description above to just get to programming, here are the main things you need to know. TouchKit is consists of three main parts: - A modified ApplicationServlet that modifies the HTML header with custom tags - A theme that overrides some of the default Vaadin functionality to suit mobile applications - A custom set of Vaadin components for building iPhone-like interfaces Install # Download the latest version of TouchKit from the Vaadin Directory. I will assume here that you are using the Eclipse with the Vaadin Eclipse plugin installed. Start off by adding the downloaded TouchKit JAR to your project lib folder ( /WebContent/WEB_INF/lib). You can just drag and drop the jar from your file system. The Vaadin Eclipse plugin should now ask you to rebuild your Widgetset, do so. If not, press the build Widgetset icon in the tool bar. Compiling the widgetset will take a few minutes even on a fast machine, so wait patiently. You'll only have to do this once. After that, you need to override the default Vaadin ApplicationServlet. Open the file web.xmlunder /WebContent/WEB_INF(switch to source view to see XML). Change #!xml<servlet-class> com.vaadin.terminal.gwt.server.ApplicationServlet </servlet-class> }}} to #!xml<servlet-class> com.vaadin.touchkit.mobileapplication.MobileApplicationServlet </servlet-class> }}} You are now ready to start using TouchKit. The following section will take you through a sample program to get you started. Sample program # To get you started with TouchKit, let's start off with a small sample program. I assume that you have used Vaadin before, so I'll skip the Vaadin related details here. The Book of Vaadin and the Wiki article on starting Vaadin development are worth reading if you are new to Vaadin. The main application will look like this: #!javapublic class TouchKitApplication extends Application { private static final long serialVersionUID = 5474522369804563317L; @Override public void init() { final Window mainWindow = new Window("Sampler"); final TouchPanel panel = new TouchPanel(); panel.navigateTo(new SamplerHome()); mainWindow.setContent(panel); setMainWindow(mainWindow); setTheme("touch"); } } }}} There are three main things that you should note here. First, unlike you would probably do in a normal Vaadin application, you will call mainWindow.setContent(...)instead of addComponent(...). This is because adding a component will add some margins around our component which we want to avoid. Second, the TouchPanelis given an initial TouchLayoutto display. Finally, the main theme of the application is set to "touch". Ready to move on? Good. Now let's take a look at that SamplerHomewe passed to our TouchPanel. This is the page we want to create: The source of the completed page looks like this: #!javapublic class SamplerHome extends TouchLayout { public SamplerHome() { setCaption("Vaadin Sampler"); addComponent(new Label("<p>This is the mobile version of the Vaadin " + "sampler. It showcases some of the Vaadin components " + "that are suited for use in mobile applications. </p>" + "<p>You can add the application to you home screen to make " + "the application feel more native. </p>", Label.CONTENT_XHTML)); TouchMenu menu = new TouchMenu("Samples"); menu.addItem("UI Basics", new TouchCommand() { @Override public void itemTouched(TouchMenuItem selectedItem) { getParent().navigateTo(new UiBasics()); } }); menu.addItem("Value Input Components", new TouchCommand() { @Override public void itemTouched(TouchMenuItem selectedItem) { getParent().navigateTo(new ValueInputComponents()); } }); menu.addItem("Forms and Data Model", new TouchCommand() { @Override public void itemTouched(TouchMenuItem selectedItem) { getParent().navigateTo(new Forms()); } }); menu.addItem("Grids and Trees", new TouchCommand() { @Override public void itemTouched(TouchMenuItem selectedItem) { getParent().navigateTo(new GridsAndTrees()); } }); menu.addItem("Layouts and Component Containers", new TouchCommand() { @Override public void itemTouched(TouchMenuItem selectedItem) { getParent().navigateTo(new LayoutsAndContainers()); } }); addComponent(menu); } } }}} That's probably a bit to take in at once, so let's take a look at it in smaller pieces. I started off by creating a standard Vaadin Labelfor the introduction text. I used Label.TYPE_XHTMLfor the label as I wanted to add several paragraphs to the same label. I then added the component to the layout with addComponent. The second part of the page is the menu. To create a TouchKit menu, you simply make a new TouchMenu. Here, I also added a caption that is shown above the menu. #!javaTouchMenu menu = new TouchMenu("Samples"); }}} Then, you can add as many menu items to this menu like this: #!javamenu.addItem("UI Basics", new TouchCommand() { @Override public void itemTouched(TouchMenuItem selectedItem) { getParent().navigateTo(new UiBasics()); } }); }}} You simply tell the menu to add an item with a given text and a TouchCommandthat will run when a user touches the menu item. TouchMenuItems can optionally also have a description and an icon. When the TouchCommandis triggered, it will get the parent TouchPaneland tell it to navigate to a new TouchLayoutthat is constructed in a similar manner as this one. To make the user interface feel more responsive, TouchKit uses the text of the TouchMenuItem as the caption of the next page and animates it in while waiting for content from the server. To finish the page, add the menu to the layout: #!javaaddComponent(menu); }}} This is just a small sampler application to show off some of the functionality in TouchKit and Vaadin components. You can see the rest of the source code for creating the Vaadin Mobile Sampler at the TouchKit SVN. The finished application, also shown in the above video can be browsed here. Things to consider # When working with TouchKit, it is essential to remember that you are working with an user interface that is meant to be used with a finger as the input device. This means that you should be sure to make your components large enough to hit with a finger. It also limits the use of functionality that is dependent on a mouse, like mouse over effects. Components that are dependent on scrolling will also be cumbersome to use because scrolling is handled by moving around the view with a finger. Just try out the Grid example in the sampler to see what I mean. As a final tip, try to keep the amount of elements on your page to a bare minimum as processing power and memory is limited on mobile devices. Take a look at the Optimizing Sluggish UI article for some tips on keeping your app lightweight and fast. License # TouchKit is licensed under the AGPL 3.0 license. I've found a bug/I want a new feature! Where can I report it? # Great! I'm more than happy for your help in testing TouchKit. You can report bugs and check up on my progress at the TouchKit issue tracker.
https://vaadin.com/wiki/-/wiki/Main/Vaadin%20TouchKit%20-%20Create%20iPhone%20applications%20using%20Vaadin
CC-MAIN-2017-04
refinedweb
1,701
57.57
Opened 4 years ago Closed 21 months ago #4947 enhancement closed wontfix (wontfix) Routes dispatching in twisted.web.server Description (last modified by tom.prince) It would be nice to have an option to use Routes-based dispatching in twisted.web.server. Something like: from twisted.web.server import Site class Controller(object): def index(self, request): return '<html><body>Hello World!</body></html>' c = Controller() dispatcher = Dispatcher() dispatcher.connect(name='index', route='/', controller=c, action='index') factory = Site(dispatcher) You would then also be able to do stuff like this: from twisted.web.static import File dispatcher.putChild('static', File(static_path)) We could adapt something like; we're using this for several internal webservices at work and it's quite nice to program in. : ) Change History (6) comment:1 Changed 4 years ago by DefaultCC Plugin - Cc jknight added comment:2 Changed 4 years ago by glyph comment:3 Changed 4 years ago by glyph Would you mind renaming 'twistedroutes' to 'txroutes' until we include it in the core? comment:4 Changed 4 years ago by steiza Not at all, you can now find it here: comment:5 Changed 22 months ago by tom.prince is also related. I think given the diversity of implementations, this is perhaps something that should live outside twisted proper. comment:6 Changed 21 months ago by exarkun - Resolution set to wontfix - Status changed from new to closed Such an API could be part of Twisted, if anyone demonstrates they have a good implementation that a lot of people were happy with, and which many people would benefit from having included in Twisted (simplified deployment story or some implementation enhancement which is only possible by maintaining the code in lockstep with the rest of Twisted Web). Otherwise there doesn't seem to be much problem caused by distributing these things separately. Please feel free to re-open in case something qualifies according to my first paragraph. Fixing markup
http://twistedmatrix.com/trac/ticket/4947
CC-MAIN-2014-42
refinedweb
324
53.21
KTHREAD(9) BSD Kernel Manual KTHREAD(9) kthread_create, kthread_exit, kthread_create_deferred - kernel threads #include <sys/kthread.h> int kthread_create(void (*func)(void *), void *arg, struct proc **newpp, const char *fmt, ...); void kthread_exit(int ecode); void kthread_create_deferred(void (*func)(void *), void *arg); Kernel threads are system light-weight processes: cloned from process 0 (the swapper), sharing its memory map and limits, but with a copy of its file descriptor table. They don't receive broadcast nor group signals and they can't be swapped. Any process can call kthread_create() to create a kernel thread. The new process starts up executing func with argument arg. If newpp is not NULL, it is filled with the address of the new process. fmt and the remaining arguments are used to name the process. A kernel thread will terminate by calling kthread_exit(), with exit code ecode. Since the system has to be up and running for creating new processes, device drivers that want to create kernel threads early (e.g., at attach time) may use kthread_create_deferred() instead. The system will call back the function func with argument arg when it can create threads, so it is up to func to call kthread_create() at that point. Upon successful completion, kthread_create() returns 0. Otherwise, the following error values are returned: [EAGAIN] The limit on the total number of system processes would be ex- ceeded. fork1(9) There is currently no way to use ecode to any sensible purpose from kthread_exit()..
http://www.mirbsd.org/htman/i386/man9/kthread.htm
CC-MAIN-2017-09
refinedweb
242
64.51
I'm currently trying to read data from .csv files in Python 2.7 with up to 1 million rows, and 200 columns (files range from 100mb to 1.6gb). I can do this (very slowly) for the files with under 300,000 rows, but once I go above that I get memory errors. My code looks like this: def getdata(filename, criteria): data=[] for criterion in criteria: data.append(getstuff(filename, criteron)) return data def getstuff(filename, criterion): import csv data=[] with open(filename, "rb") as csvfile: datareader=csv.reader(csvfile) for row in datareader: if row[3]=="column header": data.append(row) elif len(data)<2 and row[3]!=criterion: pass elif row[3]==criterion: data.append(row) else: return data You are reading all rows into a list, then processing that list. Don't do that. Process your rows as you produce them. If you need to filter the data first, use a generator function: import csv def getstuff(filename, criterion): with open(filename, "rb") as csvfile: datareader = csv.reader(csvfile) count = 0 for row in datareader: if row[3] in ("column header", criterion): yield row count += 1 elif count < 2: continue else: return I also simplified your filter test; the logic is the same but more concise. You can now loop over getstuff() directly. Do the same in getdata(): def getdata(filename, criteria): for criterion in criteria: for row in getstuff(filename, criterion): yield row Now loop directly over getdata() in your code: for row in getdata(somefilename, sequence_of_criteria): # process row You now only hold one row in memory, instead of your thousands of lines per criterion. yield makes a function a generator function, which means it won't do any work until you start looping over it.
https://codedump.io/share/4LKebV3kn9d6/1/reading-a-huge-csv-file
CC-MAIN-2017-13
refinedweb
292
64.61
Elastic Load Balancing (ELB) is an AWS service used to dispatch incoming web traffic from your applications across your Amazon EC2 backend instances, which may be in different availability zones. ELB helps ensure a smooth user experience and provide increased fault tolerance, handling traffic peaks and failed EC2 instances without interruption. Datadog collects metrics and metadata from all three flavors of Elastic Load Balancers that AWS offers: Application, Classic, and Network Load Balancers. If you haven’t already, set up the Amazon Web Services integration first. In the AWS integration tile, ensure that ELB is checked under metric collection. Check also ApplicationELB checkbox for Application ELB metrics, and the NetworkELB checkbox for Network ELB metrics. Add the following permissions to your Datadog IAM policy to collect Amazon ELB metrics. For more information on ELB policies, review the documentation on the AWS website. Install the Datadog - AWS ELB integration. Enable the logging on your ELB or your ALB first to collect your logs. ALB and ELB logs can be written in a AWS S3 bucket and consumed by a Lambda function. For more information, refer to the AWS documentation. Set interval to 5 minutes and define your s3 buckets: Object Created (All)then click on the add button. Once done, go in your Datadog Log section to start exploring your logs! Metrics are collected under the following namespaces: Each of the metrics retrieved from AWS is assigned the same tags that appear in the AWS console, including but not limited to host name, security-groups, and more. The AWS Elastic Load Balancing integration does not include any events. The AWS Elastic Load Balancing integration does not include any service checks. Need help? Contact Datadog support. Learn more about how to monitor ELB performance metrics thanks to our series of posts. We detail the key performance metrics, how to collect them, and how to use Datadog to monitor ELB.
https://docs.datadoghq.com/integrations/amazon_elb/
CC-MAIN-2019-51
refinedweb
317
55.54
Drag and Drop sortable lists with Rails & Stimulus JS Discussion Chris, thank you so much for this! I was actually going through the old drag and drop tutorial yesterday and today to update it for Rails 6. I seem to be having an issue both with this tutorial and the other where the Rails.ajax line in both of them is causing the error message: Uncaught ReferenceError: Rails is not defined In the old tutorial, I was able to get it to work by changing Rails.ajax to $.ajax but that only works with jQuery and not Stimulus. Do you know what might be causing this? Add import Rails from "@rails/ujs"; to the top of your drag_controller.js file and it should work fine. I believe Chris starts apps with his Jumpstart template, which includes this by default. Tim, you may need to register Rails globally inside webpack config. Than you will not need to import it inside every controller. // config/webpack/environment.js const { environment } = require('@rails/webpacker') const webpack = require('webpack') environment.plugins.prepend('Provide', new webpack.ProvidePlugin({ Rails: ['@rails/ujs'] }) ) module.exports = environment Thanks John and Dino! That fixed both the old and new versions. I've been trying to figure that out for awhile now. Much appreciated! What would this look like when used with Stimulus Reflex? I've got a question on this. What if the todo is nested within another model. Like todolist has many todos. I'm having trouble setting up the data-drag-url to be something like /todolist/:id/todos/:id/move. How do you bring the todolist :id? hey, I have an image model. image belongs to product, and product has many images. this is how I did it. <div data- and in the stimulus controller, I replaced the url by this let id = event.item.dataset.id let product_id = event.item.dataset.productId let data = new FormData() data.append("position", event.newIndex + 1) let url = this.data.get("url") let mapUrl = { product_id: product_id, id: id} url = url.replace(/product_id|id/gi, function(matched){ return mapUrl[matched]; }) Rails.ajax({ url: url, type: 'PATCH', data: data }) Just coming back to this now. I set it up similar to what you did. Instead of products I have compitems. Instead of images I have tasks. It can't seem to find the correct task to update the position on. I get the error ActiveRecord::RecordNotFound (Couldn't find Task with 'id'=:3 [WHERE "tasks"."compitem_id" = $1]): 13:16:20 web.1 | 13:16:20 web.1 | app/controllers/tasks_controller.rb:81:in "set_task" Any thoughts on why that is? drag controller: import { Controller } from "stimulus" import Sortable from "sortablejs" export default class extends Controller { connect() { this.sortable = Sortable.create(this.element, { group: 'shared', animation: 150, onEnd: this.end.bind(this) }) } end(event) { let id = event.item.dataset.id let compitem_id = event.item.dataset.compitemId let data = new FormData() data.append("position", event.newIndex + 1) let url = this.data.get("url") let mapUrl = { compitem_id: compitem_id, id: id} url = url.replace(/compitem_id|id/gi, function(matched){ return mapUrl[matched]; }) Rails.ajax({ url: url, type: 'PATCH', data: data }) } } Task.html.erb <div data- <div class="border border-gray-400 mx-4 my-4 p-6 w-1/2" data- <div><%= check_box_tag nil, nil, task.completed_date?, data: { reflex: "click->ExampleReflex#toggle", id: task.id } %></div> <div><h3 class="text-gray-900 text-sm leading-5 font-medium truncate"><%= task.description %></h3></div> <div><h3 class="text-gray-900 text-sm leading-5 font-medium truncate"><%= task.completed_date %></h3></div> </div> </div> In compitems show: <div class="mt-5 border-t border-gray-200 pt-5"> <div id="taskitems_wrapper"> <%= render @compitem.tasks.order(position: :asc), :locals => {:compitem_id => @compitem.id} %> </div> </div> tasks controller: class TasksController < ApplicationController before_action :set_compitem before_action :set_task, except: [:create] # GET /tasks # GET /tasks.json def index @task = Task.all end # GET /tasks/1 # GET /tasks/1.json def show end # GET /tasks/new def new @task = Task.new end # GET /tasks/1/edit def edit end # POST /tasks # POST /tasks.json def create @task = @compitem.tasks.create(task_params) @task.user_id = current_user.id respond_to do |format| if @task.save format.html { redirect_to @task, notice: 'Task was successfully created.' } format.json { render :show, status: :created, location: @task } else format.html { render :new } format.json { render json: @task.errors, status: :unprocessable_entity } end end end # PATCH/PUT /tasks/1 # PATCH/PUT /tasks/1.json def update respond_to do |format| if @task.update(task_params) format.html { redirect_to @compitem, notice: 'Task was successfully updated.' } format.json { render :show, status: :ok, location: @task } else format.html { render :edit } format.json { render json: @task.errors, status: :unprocessable_entity } end end end # DELETE /tasks/1 # DELETE /tasks/1.json def destroy @task.destroy respond_to do |format| format.html { redirect_to tasks_url, notice: 'Task was successfully destroyed.' } format.json { head :no_content } end end def move @task.insert_at(params[:position].to_i) head :ok end def set_compitem @compitem = Compitem.find(params[:compitem_id]) end private # Use callbacks to share common setup or constraints between actions. def set_task @task = @compitem.tasks.find(params[:id]) end # Only allow a list of trusted parameters through. def task_params params.require(:task).permit(:description, :position, :user_id) end end I am having the same issue. I did find out that in the event, event.item.dataset.id is empty. I am not sure why. I was working on this today. I am rendering the partial from the compitem page in my case passing through the compitem_id as a locale. I get the error that the ID value is undefined so I'm not sure if I am passing it through correctly. It would be great to see a full working example of this. Will be great to see an updated version of this video with Stimulius Relfex and why not a demo with multiple list like Trello I get the following error when grabbing the url: TypeError: null is not an object (evaluating 'this.data.get('url').replace'). I set data: {drag_url: 'xx'} on the wrapper div (same div that has data-controller on it). For some reason this.data is always null. Any ideas why this would be? I just changed it up a bit. I assigned the drag-url to the item....not the container. That way I don't need to replace :id with id. And, then to get that url in the end method I use event.item.dataset.dragUrl. What would be the solution for the drag_controler.js code to make it serialized like it was with the jQuery sortable episode? The route would need to be updated to collect and the move action would need to use each_with_index. Just can't figure out how to serialize it correctly from the drag_controller.js
https://gorails.com/forum/drag-and-drop-sortable-lists-with-rails-stimulus-js-discussion
CC-MAIN-2021-17
refinedweb
1,123
62.54
grantb4 wrote:Wouldn't that be a host bug? Wouldn't that be a host bug? Yah, it’s BIOS bug.Try BIOS update, if any.ORTurn off "Legacy USB3.0 Support" on BIOS setting. Tsuneo Nov 07 2017, 4:10 PM I have discovered that my Full Speed HID device will hang a brand new Win7 PC on reboot Where does the hang occur, BIOS or Windows?Do you see Windows startup logo when hang occurs?I believe Windows should hang, because BIOS ignores the HID device, unless it would assign boot protocol in the interface triad. { // interface_descriptor hid_interface_descriptor 0x09, // bLength 0x04, // bDescriptorType 0x00, // bInterfaceNumber 0x00, // bAlternateSetting 0x02, // bNumEndpoints 0x03, // bInterfaceClass (3 = HID) 0x00, // bInterfaceSubClass <------ 0x00:No Subclass, 0x01: Boot Interface Subclass 0x00, // bInterfaceProcotol 0x00 // iInterface }, For Windows7, MS doesn't provide USB3.0 drivers, supplied by Intel in your case, ie. the manufacturer of the USB3.0 host controller. The USB3.0 drivers by manufacturers have been well established, but they differ slightly from MS original. This USB3.0 driver also affects to full-/low-speed device on the USB3.0 ports. Try driver update for any fix on this issue for your Intel chipset, for exampleUSB 3.0 Driver: Intel USB 3.0 eXtensible Host Controller Driver for Intel7 Series/C216 Chipset Family grantb4 wrote:The last "useful" transaction on EP0 is a SET IDLE (21 0A 00 00 00 00 00 00). The last "useful" transaction on EP0 is a SET IDLE (21 0A 00 00 00 00 00 00). This setup packet means Set_Idle(0); "indefinite" interval, which is always put by Windows at enumeration. In principle by this "indefinite" value, Windows expect a report, just when any change occurs. But actually, though it is bad practice, Windows should accept reports at every interval, even if they are identical reports. In this reason, report duration control have not been implemented positively. grantb4 wrote:Perhaps if your design NAKs on the data endpoints most of the time there is no issue? Perhaps if your design NAKs on the data endpoints most of the time there is no issue? I'm not sure NAKs would work around this issue (maybe not).But if you would like to be in good practice, it's easy Put to the interrupt IN endpoint, just when any change occurs on your firmware.You should show the version of SiLabs library, for detailed discussion of the code.Tsuneo I picked up old SiLabs IDE (and examples) v2.61 from my archive.Installed the IDE and tested USB_INT example on SiLabs 'F340 dev board.Changing EP0_PACKET_SIZE down, the example firmware was enumerated at 64 (default) and 32 successfully on Windows 7 (x86), but it failed at 16. A STALL occurred at the second IN transaction (DATA stage) of Get_Descriptor( Device ). The next retry of Get_Descriptor( Device ) succeeded. A couple of Get_Descriptor error were seen after above one. At last, Windows gave up enumeration.I remember this timing issue is caused by too early asserting of DATAEND bit, while DATA stage still continues, caused by SUEND process. In this post, I described on this issue and its fix. of this issue is, F34x_USB_ISR.c void Handle_Setup(void) { ... if (ControlReg & rbSUEND) // If last setup transaction was ended { // prematurely then set POLL_WRITE_BYTE(E0CSR, rbDATAEND); // <------------------ delete this line POLL_WRITE_BYTE(E0CSR, rbSSUEND); // Serviced Setup End bit and return EP0 Ep_Status[0] = EP_IDLE; // to idle state } Deleting "POLL_WRITE_BYTE(E0CSR, rbDATAEND);" line from above code made the USB_INT example enumerated successfully on all of possible EP0_PACKET_SIZE (bMaxPacketSize0), 64, 32, 16 and 8, on my side.Tsuneo I remember,the USB SIE on F32x/34x/38x has undocumented indexed registers, INMAX, OUTMAX // USB Core Registers #define BASE 0x00 #define FADDR BASE #define POWER BASE + 0x01 #define IN1INT BASE + 0x02 #define OUT1INT BASE + 0x04 #define CMINT BASE + 0x06 #define IN1IE BASE + 0x07 #define OUT1IE BASE + 0x09 #define CMIE BASE + 0x0B #define FRAMEL BASE + 0x0C #define FRAMEH BASE + 0x0D #define INDEX BASE + 0x0E #define CLKREC BASE + 0x0F #define INMAX BASE + 0x10 // <-- #define E0CSR BASE + 0x11 #define EINCSRL BASE + 0x11 #define EINCSRH BASE + 0x12 #define OUTMAX BASE + 0x13 // <-- #define EOUTCSRL BASE + 0x14 #define EOUTCSRH BASE + 0x15 #define E0CNT BASE + 0x16 #define EOUTCNTL BASE + 0x16 #define EOUTCNTH BASE + 0x17 #define FIFO_EP0 BASE + 0x20 #define FIFO_EP1 BASE + 0x21 #define FIFO_EP2 BASE + 0x22 #define FIFO_EP3 BASE + 0x23 While these registers are left in the default value (0), the SIE isn’t aware of Max Packet Size, at all. Actually, above F34x_MouseExample doesn’t touch to these registers. If your stack would set up these registers, your stack could be set them wrongly. What is the USB stack on which you are working? I tested F34x_MouseExample (Si8051 SDK v2.0.0) - Simplicity Studio v2, on SiLabs F34x dev board. It worked without any problem on 8, 16, 32 and 64 of bMaxPacketSize0 F3xx_USB0_InterruptServiceRoutine.h // Define Endpoint Packet Sizes #ifdef _USB_LOW_SPEED_ #define EP0_PACKET_SIZE 0x08 // This value can be 8,16,32,64 // depending on device speed, see // USB spec #else //#define EP0_PACKET_SIZE 0x40 //#define EP0_PACKET_SIZE 0x20 //#define EP0_PACKET_SIZE 0x10 #define EP0_PACKET_SIZE 0x08 #endif /* _USB_LOW_SPEED_ */ Oct 28 2017, 1:52 PM Oct 28 2017, 1:50 PM Oct 28 2017, 1:49 PM
https://www.silabs.com/community/profile.html/home/users/community/B/hQtNysi5_uMPeUSj2Mk8/profile
CC-MAIN-2018-05
refinedweb
863
54.73
We strive to provide a common scripting API and experience across all platforms Unity, we need to compile all of the managed code ahead-of-time (AOT). Often, this distinction doesn’t matter, but in a few specific cases, AOT platforms require additional consideration. An AOT platform cannot implement any of the methods in the System.Reflection.Emit namespace. Note that the rest of System.Reflection is acceptable, as long as the compiler can infer that the code used via reflection needs to exist at runtime. AOT platforms may encounter issues with serialization and deserlization due to the use of reflection. If a type or method is only used via reflection as part of serialization or deserialization, the AOT compiler cannot detect that code needs to be generated for the type or method. Generic methods require the compiler to do some additional work to expand the code written by the developer to the code actually executed on the device. For example, we need different code for List with an int or a double. In the presence of virtual methods, where behavior is determined at runtime rather than compile time, the compiler can easily require runtime code generation in places where it is not entirely obvious from the source code. Suppose we have the following code, which); } When this code is executed blissfully continues, skipping this method. When that method is called, and the runtime can’t find the proper code to execute, it gives up with this error message. To work around an AOT issue like this, we can often force the compiler to generate the proper code for us. If we add a method like this ever need to be called; it just needs to exist for the compiler to see it.. • 2017–05–16 Page amended with no editorial review Did you find this page useful? Please give it a rating:
https://docs.unity3d.com/2017.2/Documentation/Manual/ScriptingRestrictions.html
CC-MAIN-2021-25
refinedweb
313
52.19
Document Your JSON API Schema with PRMD On a recent project, my team agreed that we needed some way to validate and document the JSON coming in and out of our API. We had already settled on using JSON Schema as the means to describe the API, so determining how to validate (and document) JSON Schema was next on the to-do list. I did tons of research into how to best accomplish such noble tasks. OK, OK, “tons of research” really means “look for gems that do this already”. I also consulted my past experience with things like Grape and Swagger, but we aren’t using Grape here and I couldn’t find anything that would allow me to easily incorporate Swagger. Even if I did, that’s only docs, without and validation. The long and short of it (that’s “old person talk” for TL;DR) is, if you want to document your API, validate requests and responses, and use JSON Schema, it’s a bit of an effort. There are approaches, such as iodocs, but I didn’t want to have to install Redis, use Node, etc. just to get docs. Also, there are plenty of tools out there to generate docs once you have the schema, but they don’t give much help in creating the schema. I quickly learned that, no matter which tool or direction I chose, it was going to be a lot of manual effort to get this done. I am hoping this article gets anyone else with the same goal further up the path. Previously this year, I took a long, hard look at pliny as a possible platform for our APIs. Pliny comes from the good folks at Heroku, who know a little bit about APIs. It is Sinatra-based and comes with some opinionated (but very good) helpers for things like logging, request tracking, versioning, etc. I highly encourage you to check it out if you’re writing APIs in Ruby. I did, and I ended up answering our JSON Schema needs as a result. Pliny utilizes two other gems from Github user interagent: prmd and committee. Together, these two gems tag-team your JSON Schema/API needs. prmd focuses on JSON Schema creation and API doc generation, and it’s the focus of this post. Committee is a collection of methods and Rack middleware to validate your schema. A subsequent post will focus on Committee. JSON Schema and JSON Hyper Schema JSON Schema is one (of very many) attempts to create a way to define the structure of JSON data. The goal is to be able to document and verify a JSON provider/repository just like you would a database schema. There are specifications (currently on Draft version 4), but I prefer this online book by Michael Droettboom of the Space Telescope Science Institute (GREAT name) as a starting point. JSON Hyper Schema turns your Schema into “Hypertext”. In other words, JSON Hyper Schema describes the endpoints for your application, including what it will accept and provide. The Space Telescope book does not cover JSON Hyper Schema, so I suggest you scan the spec and read this post. Finally, the prmd gem provides this markdown file that is extremely useful when defining your schema and what prmd expects. I am not going to walk through the specification, so I encourage you to read that book. I will presume you understand the basics of JSON Schema and Hyper Schema for the rest of this post. PRMD PRMD’s tag line is “JSON Schema tools and doc generation for HTTP APIs”. In other words, prmd allows you to generate JSON Schema, which then must be manually changed/tweaked to match your API. Once the schema is fully defined, prmd provides tasks to verify the schema is JSON Schema-compliant, as well as generate docs for that API. The end game of using prmd is to have a defined JSON Schema for your API, along with supporting documentation. The documentation is generated in Markdown format, which is nice. prmd provides an executable ( prmd) with the following commands: init: Scaffold resource schemata combine: Combine schemata and metadata into single schema verify: Verify a schema doc: Generate documentation from a schema render: Render views from schema We will directly use each of these, either directly or via Rake task, except render, which I have not had a use for. Example In this post, our application provides account creation (registration) and authentication. We’ll define the resource ( account) and endpoints ( links). I am using Rails here, but Pliny is Sinatra-based, so you should be able to easily use the concepts covered here with any Ruby web framework. The schema will also expose endpoints for sessions and password reset. The Rails application uses rails-api, starting with Ruby 2.2.2, Rails 4.2.3. I have a repo that I am using, so you can check it out to see how it’s setup. PRMD Setup prmd needs a directory to store the schema and it’s supporting files. Make a schema/schemata directory: mkdir -p schema/schemata The top level schema files will live in schema and the individual schemata files (such as for account) will live in schema/schemata. This is simply our convention, so you can do what you like. The “top level” files I previously mentioned are files that describe the metadata for our overall API, unrelated to a specific resource. Here’s ours: { "description": "Account API", "id": "account-api", "links": [{ "href": "", "rel": "self" }], "title": "Accounts" } This is taken from the prmd README and satisfies the metadata requirements of JSON Schema. I feel I should mention that you can use JSON or YAML to define your API. I started with YAML and didn’t like it as much. I prefer doing this in JSON. One added bonus of doing this in JSON is that you can drop things in various online JSON and JSON Schema linters and catch typos or orphaned brackets. Account Schema Time to generate the schema scaffold: prmd init account > schema/schemata/account.json This creates a basic JSON Schema for our Account resource. Unfortunately, it doesn’t pull in anything from our model, if we had one (and, it probably shouldn’t), so the JSON schema has to be manually tweaked to match the API. Open up that file and quickly read through it. I’ll dissect it, section by section, so we’re on the same page. General Resource Information { "$schema": "", "title": "Account", "description": "The Account resource for the API", "stability": "prototype", "strictProperties": true, "type": [ "object" ], .... As you can see, the $schema is draft 4 of JSON Hyper Schema. There are a couple of “FIXME”s that need to be addressed in title and description, which I have fixed above. stability specifies the stability (duh) of the resource and is one of prototype, development, or production. strictProperties indicates that this object (the resource) ONLY has the properties defined in this object. There is an additionalProperties property that is mutually exclusive with strictProperties. Definitions The definitions are reference properties that will be used throughout the schema so it’s not necessary to constantly redefined id or The generated definitions have examples, such as name and id. I have changed the snippet below to match our resource by replacing name with "definitions": { "id": { "description": "unique identifier of account", "readOnly": true, "format": "uuid", "type": [ "string" ] }, "email": { "description": "unique email of account", "readOnly": true, "type": [ "string" ] }, "password": { "description": "account password", "readOnly": true, "type": [ "string" ] } "identity": { "anyOf": [ { "$ref": "/schemata/account#/definitions/id" }, { "$ref": "/schemata/account#/definitions/email" } ] }, "created_at": { "description": "when account was created", "format": "date-time", "type": [ "string" ] }, "updated_at": { "description": "when account was updated", "format": "date-time", "type": [ "string" ] } } Some important takeaways from the definitions are: - Each definition has a typethat represents the kind of data type. Acceptable values are: "array", "boolean", "integer", "number", "null", "object", "string". formatis what you think it is, and possible values are: "date-time", "email", "hostname", "ipv4", "ipv6", "uri". prmd actually supplies a custom uuid, which you can (should) use for IDs. - Speaking of identifying, the identityproperty is how the resource identifies specific instances. In this case, we can use idor $refproperty is a reference to the property in definitions. So, "$ref": "/schemata/account#/definitions/email"pulls in our email definition (technically called “dereferencing”). The remaining properties should be self-explanatory. Links The links section is part of the JSON Hyper Schema spec and explains the endpoints supported by the schema: "links": [ { "description": "Create a new account.", "href": "/accounts", "method": "POST", "rel": "create", "schema": { "properties": { }, "type": [ "object" ] }, "title": "Create" }, { "description": "Delete an existing account.", "href": "/accounts/{(%2Fschemata%2Faccount%23%2Fdefinitions%2Fidentity)}", "method": "DELETE", "rel": "destroy", "title": "Delete" }, { "description": "Info for existing account.", "href": "/accounts/{(%2Fschemata%2Faccount%23%2Fdefinitions%2Fidentity)}", "method": "GET", "rel": "self", "title": "Info" }, { "description": "List existing accounts.", "href": "/accounts", "method": "GET", "rel": "instances", "title": "List" }, { "description": "Update an existing account.", "href": "/accounts/{(%2Fschemata%2Faccount%23%2Fdefinitions%2Fidentity)}", "method": "PATCH", "rel": "update", "schema": { "properties": { }, "type": [ "object" ] }, "title": "Update" } ], A link can include the href, method, schema, and targetSchema. The latter two properties are what the API will accept and provide, respectively. rel is the relationship of the link to the resource, and should be one of create, destroy, self, instances, or update. I am sure you see some of that JSON vomit in the href for particular links. I am speaking of things like: "href": "/accounts/{(%2Fschemata%2Faccount%23%2Fdefinitions%2Fidentity)}", Basically, that is really /accounts/{identity}. Remember when we defined the identity in the definitions section? That long, weird string is just the URL encoded /schemata/account/#definitions/identity. You can see that prmd basically generated “typical” RESTful links, building out a CRUD-like API. In some cases, that’s a good start. In this case, we need to make some changes. Since this is for registration and authentication: - Let’s get rid of the “List existing accounts”, sounds like a security issue anyway. - Add links for the sessionand passwordflows. POSTto /accounts/session, accepts a token. - The password endpoints will require a reset token. - I am going to get pretty detailed with how I define what the links accept and return. As an example, here is the new account creation/registration schema: { "description": "Create a new account.", "href": "/account", "method": "POST", "rel": "create", "schema": { "properties": { "account" : { "type" : "object", "properties": { "email" : { "$ref": "/schemata/account#/definitions/email" }, "password": { "type": "string", "description": "The password" }, "remember_me": { "type": "boolean", "description": "True/false - generate refresh token (optional)" } }, "required" : [ "email", "password" ] } }, "type": [ "object" ] }, "title": "Create", "targetSchema": { "type": "object", "properties": { "token" : { "$ref": "/schemata/account#/definitions/token" } } } } So, what changed? - I expanded the schema/propertiesto take in an accountthat has an password, and an optional remember_meproperty. The email and password are references to the same items in the definitions, but the - Notice the requiredparameters that are nested in account. This is to allow you to define required and optional parameters at any level. I added the targetSchemaproperty, defining what will be returned by the call. In this case, it’s a tokendefinition that I added, which looks like: token": { "type": "string", "description": "The token", "example" : " }, Whoa! That’s ugly. Yes, it is. However, the example will be used when we generate the markdown documentation, so I’ll take ugly now to get that later. In a production app, there are many changes like this to get the schema well-defined. It is a manual, tedious process that no one likes to do. However, the payoff of having docs and being able to verify JSON schema in tests and on the production site is worth it. At least, we think it is. Also, our APIs are focused (think microservices) so the scope of each JSON Schema effort is smaller than, say, a large, monolithic API. Doc Generation Part of the reward that comes from painstakingly defining the JSON Schema is “easy” API documentation. And yes, I realize there are other ways to do this (RAML, Apiary, etc.), so if you have a good way to do it, I won’t talk you out of it. While prmd does offer an executable, I like having Rake tasks for combining the schema files and generating the docs. The README explains how to create the Rake tasks. In short, I created a lib/tasks/schema.rake with the following: require "prmd/rake_tasks/combine" require "prmd/rake_tasks/verify" require "prmd/rake_tasks/doc" namespace :schema do Prmd::RakeTasks::Combine.new do |t| t.options[:meta] = "schema/meta.json" # use meta.yml if you prefer YAML format t.paths << "schema/schemata" t.output_file = "schema/authentication-api.json" end Prmd::RakeTasks::Verify.new do |t| t.files << "schema/authentication-api.json" end Prmd::RakeTasks::Doc.new do |t| t.files = { "schema/authentication-api.json" => "schema/authentication-api.md" } end task default: ["schema:combine", "schema:verify", "schema:doc"] end Notice that I have changed some paths and file names from the examples in the README to match this project. Now, I can go rake schema:combine rake schema:verify rake schema:doc or rake schema If you have JSON errors, the combine will fail. Here, I deleted a : in the doc and got: unable to parse schema/schemata/account.json (#<JSON::ParserError: 795: unexpected token at '{ "$schema": "", "title": "Authentication API - Account", "description": "The Account Schema", "stability": "prototype", "strictProperties": true, "type": [ "object" ], "definitions": { "id": { "description": "unique identifier of account", "readOnly": true, ... Somes files have failed to parse. If you wish to continue without them,please enable faulty_load using --faulty-load So, you can force it to load, but I don’t know why you would. If you have JSON Schema errors, then the verify task will fail. Here, I made the password type a sting: schema/authentication-api.json: #/definitions/account/links/1: failed schema #/properties/properties/additionalProperties: Not all subschemas of "allOf" matched. Presuming the combine works and the verify doesn’t find anything, then the doc task with create a schema/authentication-api.md file. Here’s a snippet: The full schema docs can be found here. I can add this markdown docs to the Github Repo or add a route that uses something like Redcarpet to create HTML. The important point is the docs are available. If your team uses Github, they’re easy to share, too. But Wait! There’s More! I know what you’re thinking. “Why did this guy go through all this for some OK markdown documentation? Hasn’t he heard of Swagger?” I have heard of it, and it won’t do what I want. I don’t think. I have mentioned using the schema in specs/tests to validate JSON schema, as well as using middleware to validate requests based on what the schema will accept. This is beyond what prmd offers. However, the folks behind prmd write the committee gem for just that purpose. And that will be the subject of my next post. You can use the time between now and then to get your schema in order. ;)
https://www.sitepoint.com/document-your-json-api-schema-with-prmd/
CC-MAIN-2022-27
refinedweb
2,498
63.8
Launch Rockets through a queue¶ If your FireWorker is a large, shared resource (such as a computing cluster or supercomputing center), you probably won’t be able to launch Rockets directly. Instead, you’ll submit Rockets through an existing queueing system that allocates computer resources. The simplest way to execute jobs through a queue would be to write a templated queue file and then submit it as a two-task Firework, as in the Firetask tutorial. However, FireWorks then considers your “job” to only be queue submission, and will consider the job completed after the queue submission is complete. FireWorks will not know when the actual payload starts running, or is finished, or if the job finishes successfully. Thus, many of the useful management and monitoring features of FireWorks will not be available to you. A more powerful way to execute jobs through a queue is presented in this tutorial. In this method, the queue file runs rlaunch instead of running your desired program. This method is just like typing rlaunch into a Terminal window like in the core tutorials, except that now we are submitting a queue script that does the typing for us (it’s very low-tech!). In particular, FireWorks is completely unaware that you are running through a queue! The jobs we will submit to the queue are basically placeholder jobs that are asleep until the job starts running. When the job is actually assigned computer resources and runs, the script “wakes” up and runs the Rocket Launcher, which then figures out what Firework to run. The advantage of this low-tech system is that it is quite durable; if your queue system goes down or you delete a job from the queue, there are zero repercussions. You don’t have to tell FireWorks to run those jobs somewhere else, because FireWorks never knew about your queue in the first place. In addition, if you are running on multiple machines and the queue becomes backlogged on one of them, it does not matter at all. Your submission job stuck in the queue is not preventing high-priority jobs from running on other machines. There are also some disadvantages to this simple system for which you might want to tell FireWorks about the queue. We’ll discuss these limitations at the end of the tutorial and direct you on how to overcome them in the next tutorial. For now, we suggest that you get things working simply. Launch a single job through a queue¶ To get warmed up, let’s set up a Queue Launcher to run a single Firework through a queueing system. Configure the Queue Launcher¶ The Queue Launcher needs to write and submit a queue script that contains an executable (in our case, a Rocket Launcher). This is achieved through a QueueAdapter file. Move to the queuetutorial directory on your FireWorker: cd <INSTALL_DIR>/fw_tutorials/queue Locate an appropriate QueueAdapter file. The files are usually named qadapter_<QUEUE>.yamlwhere <QUEUE>is the supported queue system. Note If you cannot find a working QueueAdapter file for your specific queuing system, or the queue script needs modification, you can write/modify your own QueueAdapter. Or, simply contact us for help (see Contributing / Contact / Bug Reports) and we will help create one for your system. Copy your chosen QueueAdapter file to a new name: cp qadapter_<QUEUE>.yaml my_qadapter.yaml Navigate to clean working directory on the FireWorker. For example: mkdir ~/queue_tests cd ~/queue_tests Copy over your queue file and the test FW to this directory: cp <INSTALL_DIR>/fw_tutorials/queue/my_qadapter.yaml . cp <INSTALL_DIR>/fw_tutorials/queue/fw_test.yaml . Copy over your LaunchPad and FireWorker files from the worker tutorial: cp <INSTALL_DIR>/fw_tutorials/worker/my_fworker.yaml . cp <INSTALL_DIR>/fw_tutorials/worker/my_launchpad.yaml . Open my_qadapter.yamland modify it as follows: - In the part that specifies running rlaunch, modify the path/to/my_fworker.yamlto contain the absolute path of the my_fworker.yamlfile on your machine. - On the same line, modify the path/to/my_launchpad.yamlto contain the absolute path of the my_launchpad.yamlfile on your machine. - For the logdir parameter, modify the path/to/loggingtext to contain the absolute path of where you would like FireWorks logs to go. For example, you might create a fw_logsdirectory inside your home directory, and point the logdir parameter there. Note Be sure to indicate the full, absolute path name; do not use BASH shortcuts like ‘.’, ‘..’, or ‘~’, and do not indicate a relative path. You are now ready to begin! Add some FireWorks¶ Staying in your testing directory, let’s reset our database and add a new Firework, all from our FireWorker: lpad reset lpad add fw_test.yaml Submit a job¶ Try submitting a job using the command: qlaunch singleshot Tip Similar to the Rocket Launcher, if you use the names my_launchpad.yaml, my_fworker.yaml, and my_qadapter.yaml, then you don’t need to specify the -l, -w, and -qoptions explicitly. FireWorks will automatically search for these files in the current directory, or in a configuration directory that you specify with a single -cparameter, or in the directories specified by your FWConfig file. This should have submitted a job to the queue in the current directory. You can read the log files in the logging directory, and/or check the status of your queue to ensure your job appeared. After your queue manager runs your job, you should see the file howdy.txtin the current directory. Note In some cases, firewall issues on shared resources prevent your compute node from accessing the LaunchPad hosted on your FireServer. You should confirm that your compute nodes can access external database servers. You might try to submit an interactive job to your queue that allows you to type shell commands inside a running job. Once on the compute node, you can try accessing your LaunchPad: lpad -l my_launchpad.yaml get_fw 1. If you cannot access the LaunchPad from your compute node, the first thing to do is contact a system administrator for assistance. If you are convinced that there is no way for the compute nodes to access a network, you might try running FireWorks in offline mode. If everything ran successfully, congratulations! You just executed a Firework through a queue! Adding more power: using rapid-fire mode¶ While launching a single job to a queue is nice, a more powerful use case is to submit a large number of jobs at once, or to maintain a certain number of jobs in the queue. Like the Rocket Launcher, the Queue Launcher can be run in a “rapid-fire” mode that provides these features. Clean your working directory of everything but four files: fw_test.yaml, my_qadapter.yaml, my_fworker.yaml, and my_launchpad.yaml Let’s reset our database and add three new FireWorks, all from our FireWorker: lpad reset lpad add fw_test.yaml lpad add fw_test.yaml lpad add fw_test.yaml Submit several jobs with a single command: qlaunch rapidfire -m 3 Important The Queue Launcher sleeps between each job submission to give time for the queue manager to ‘breathe’. It might take a few minutes to submit all the jobs. Important The command above submits jobs until you have at most 3 jobs in the queue under your username. If you had some jobs existing in the queue before running this command, you might need to increase the -mparameter. The rapid-fire command should have created a directory beginning with the tag block_. Navigate inside this directory, and confirm that three directories starting with the tag launchwere created. The launchdirectories contain your individual jobs. You’ve now launched multiple Rockets with a single command, all through a queueing system! Continually submit jobs to the queue¶ You might want to set up your worker so that it maintains a certain number of jobs in the queue indefinitely. That way, it will continuously pull FireWorks from the LaunchPad. Let’s set this up. Clean your working directory of everything but four files: fw_test.yaml, my_qadapter.yaml, my_fworker.yaml, and my_launchpad.yaml. Let’s reset our database and add four new FireWorks this time: lpad reset lpad add fw_test.yaml lpad add fw_test.yaml lpad add fw_test.yaml lpad add fw_test.yaml Note We have omitted the -lparameter. You can use this shortcut when using the standard file name ( my_launchpad.yaml) for the LaunchPad. Run the queue launcher in infinite mode: qlaunch rapidfire -m 2 --nlaunches infinite This command will always maintain 2 jobs in the queue. When a job finishes, another will be submitted to take its place! Running multiple Rockets per queue job¶ So far, each queue script we submitted has only one job. We can also submit multiple jobs per queue script by running the rapidfire option of the Rocket Launcher inside the Queue Launcher. Then, a single queue script will run multiple Rockets. Clean your working directory of everything but four files: fw_test.yaml, my_qadapter.yaml, my_fworker.yaml, and my_launchpad.yaml. Copy your QueueAdapter file to my_qp_multi.yaml: cp my_qadapter.yaml my_qp_multi.yaml Edit my_qp_multi.yamlas follows: - In the part that specifies running rlaunch, modify the singleshottext to read rapidfire. Let’s add three FireWorks to the LaunchPad and submit a single queue script: lpad reset lpad add fw_test.yaml lpad add fw_test.yaml lpad add fw_test.yaml qlaunch -q my_qp_multi.yaml singleshot You should confirm that only a single job got submitted to the queue. However, when the job starts running, you’ll see that all three of your jobs completed in separate launcher_directories! Warning Note that when running in rapidfire mode, there is an increased likelihood that a Firework will be killed by the job walltime. To mitigate this, you can either limit the number of jobs executed by rapidfire (using either the nlaunches or timeout parameters), or you can let the Firework be killed and use the error recovery features (see docs on that topic) to rerun the killed Firework. Remote qlaunch¶ The qlaunch command also comes with options to do simple remote queue administration. This remote capability is extremely useful if you need to maintain jobs in queues across a number of computing resources from a single location (as opposed to ssh into each resource and doing qlaunch). A few recommendations: - It is helpful if you configure all your fireworks in all the resources you want to use similarly. For example, you can use the default $HOME/.fireworks location, or setup every resource in a similar location. - Passwordless ssh should ideally be configured for all clusters from the machine you want to run qlaunch from. While qlaunch provides a “-rp” option to specify the password, it is less secure and less powerful (e.g., you can’t manage lots of resources with a single command). Sample usage¶ All remote options start with “-r” or “–remote”. Running qlaunch rapidfire on one server: qlaunch -rh compute.host.gov -ru user rapidfire -m 50 Note that rapidfire options such as “-m 50” are automatically transmitted to the resource. Running qlaunch rapidfire on a host with multiple queue configurations. This is useful when you have multiple FireWorks configurations (e.g. different queue or FireWorker configurations) for a single resource. A single command runs qlaunch rapidfire on all configurations: qlaunch -rh compute.host.gov -rc /path/to/config1 /path/to/config2 -ru user rapidfire Running qlaunch rapidfire on multiple hosts with the same username. Without the rc option, it is assumed that $HOME/.fireworks is where the fireworks configuration is located on all hosts: qlaunch -rh compute.host1.gov compute.host2.gov -ru user rapidfire Limitations¶ To keep the code simple, qlaunch default remote options are limited to similar configurations across multiple resources. If you have more complicated setups, e.g., different users, different queue configurations across different computing resoruces, remote qlaunch will not be able to handle these. However, you can always write your own fabfile.py and use Fabric’s far more sophisticated execution model. A simple fabfile.py for different users on different hosts is given below. If you require Fabric’s sophistication, I encourage you to read Fabric’s official documentation: from fabric.api import run, env env.hosts = ["user1@compute.host1.gov", "user2@compute.host2.gov"] def qlaunch(): run('qlaunch -c $HOME/.fireworks rapidfire') More information¶ As with all FireWorks scripts, you can run the built-in help for more information: qlaunch -h qlaunch singleshot -h qlaunch rapidfire -h Limitations and Next Steps¶ The information in this tutorial might be all you need to automate your application. However, as we noted previously, there are some limitations to running under a model in which FireWorks is completely unaware of the existence of queues. In the simple queue execution model, limitations include: - You can’t track how many of your jobs are queued Since FireWorks is unaware of your queue, there’s no way to track how many of your jobs are queued up on various machines. You’ll have to wait until they start running before their presence is reported to FireWorks. - You might submit too many jobs to the queue It’s possible to submit more queue scripts than exist jobs in the database. Before submitting a queue script, the Queue Launcher checks that at least one unstarted job exists in the database. However, let’s take an example where you have one Firework in the database that’s ready to run. Nothing in the current system prevents you from using the Queue Launcher to rapid-fire 20 jobs to the queue. You won’t be prevented from submitting queue scripts until that Firework has actually started running. If the number of jobs in your database is kept much higher than the number of jobs you keep in your queues, then you shouldn’t run into this problem at all; all your submitted queue scripts will always find a job to run. Even if this is not the case, the additional queue scripts should pose only a minor penalty. Any extra queue scripts will wake up, find nothing to do, and exit without wasting more than few seconds of computer time. If you are using rapid-fire mode, you’ll also end up with an additional launcher_ directory. You can look at the REMOVE_USELESS_DIRS option of the FW config as a solution to this. - You can’t easily tailor queue parameters (e.g. walltime) individually for each the job Perhaps the most severe limitation is that the Queue Launcher submits queue scripts with identical queue parameters (e.g., all jobs will have the same walltime, use the same number of cores, etc.) If you have just two or three sets of queue parameters for your different job types, you can work around this limitation. First, recall that you can use the FireWorker file to restrict which jobs get run (see tutorial). If you have two types of jobs, you can run two Queue Launchers. Each of these Queue Launchers use different queue parameters, corresponding to the two types of jobs you’d like to run. In addition, each Queue Launcher should be run with a corresponding FireWorker that restricts that jobs for that launcher to the desired job type. While this solution works for a few different job types, it is not practical if you have many job types. In addition, it requires some coordination between Firework categories, FireWorkers, and Queue Launchers. Therefore, if setting multiple sets of queue parameters is needed for your application, we suggest that you read on for a solution. To solve these problems, you must *reserve* FireWorks in advance. Next step: reserving FireWorks to overcome limitations¶ If you feel these limitations impact your workflow, you should forge on to the next tutorial: Reserving FireWorks upon queue submission. We’ll explain how reserving FireWorks upon queue submission can solve the limitations of simple queue submission, at the expense of added complexity and introducing some new limitations and considerations. Note If you are planning to complete the next tutorial, you should save your working directory with the files: fw_test.yaml, my_qadapter.yaml, my_fworker.yaml, and my_launchpad.yaml. We’ll use it in the next tutorial.
https://pythonhosted.org/FireWorks/queue_tutorial.html
CC-MAIN-2017-13
refinedweb
2,674
64.41
Twisted Web serves Python objects that implement the interface IResource. HTTPChannelinstances to parse the HTTP request, and begin the object lookup process. They contain the root Resource, the resource which represents the URL /on the site. The Twisted Web server is started through the Twisted Daemonizer, as in: % twistd web Site objects serve as the glue between a port to listen for HTTP requests on, and a root Resource object. When using twistd -n web --path /foo/bar/baz , a Site object is created with a root Resource that serves files out of the given path. You can also create a Site instance by hand, passing it a Resource object which will serve as the root of the site: from twisted.web import server, resource from twisted.internet import reactor, endpoints class Simple(resource.Resource): isLeaf = True def render_GET(self, request): return "<html>Hello, world!</html>" site = server.Site(Simple()) endpoint = endpoints.TCP4ServerEndpoint(reactor, 8080) endpoint.listen(site) reactor.run() Resource objects represent a single URL segment of a site. During URL parsing, getChild is called on the current Resource to produce the next Resource object. When the leaf Resource is reached, either because there were no more URL segments or a Resource had isLeaf set to True, the leaf Resource is rendered by calling render(request) . See “Resource Rendering” below for more about this. During the Resource location process, the URL segments which have already been processed and those which have not yet been processed are available in request.prepath and request.postpath . A Resource can know where it is in the URL tree by looking at request.prepath , a list of URL segment strings. A Resource can know which path segments will be processed after it by looking at request.postpath . If the URL ends in a slash, for example , the final URL segment will be an empty string. Resources can thus know if they were requested with or without a final slash. Here is a simple Resource object: from twisted.web.resource import Resource class Hello(Resource): isLeaf = True def getChild(self, name, request): if name == '': return self return Resource.getChild(self, name, request) def render_GET(self, request): return "Hello, world! I am located at %r." % (request.prepath,) resource = Hello() Resources can be arranged in trees using putChild . putChild puts a Resource instance into another Resource instance, making it available at the given path segment name: root = Hello() root.putChild('fred', Hello()) root.putChild('bob', Hello()) If this root resource is served as the root of a Site instance, the following URLs will all be valid: Files with the extension .rpy are python scripts which, when placed in a directory served by Twisted Web, will be executed when visited through the web. An .rpy script must define a variable, resource , which is the Resource object that will render the request. .rpy files are very convenient for rapid development and prototyping. Since they are executed on every web request, defining a Resource subclass in an .rpy will make viewing the results of changes to your class visible simply by refreshing the page: from twisted.web.resource import Resource class MyResource(Resource): def render_GET(self, request): return "<html>Hello, world!</html>" resource = MyResource() However, it is often a better idea to define Resource subclasses in Python modules. In order for changes in modules to be visible, you must either restart the Python process, or reload the module: import myresource ## Comment out this line when finished debugging reload(myresource) resource = myresource.MyResource() Creating a Twisted Web server which serves a directory is easy: % twistd -n web --path /Users/dsp/Sites Resource rendering occurs when Twisted Web locates a leaf Resource object to handle a web request. A Resource’s render method may do various things to produce output which will be sent back to the browser: request.write("stuff")as many times as desired, then call request.finish()and return server.NOT_DONE_YET(This is deceptive, since you are in fact done with the request, but is the correct way to do this) Deferred, return server.NOT_DONE_YET, and call request.write("stuff")and request.finish()later, in a callback on the Deferred. The Resource class, which is usually what one’s Resource classes subclass, has a convenient default implementation of render . It will call a method named self.render_METHOD where “METHOD” is whatever HTTP method was used to request this resource. Examples: request_GET, request_POST, request_HEAD, and so on. It is recommended that you have your resource classes subclass Resource and implement render_METHOD methods as opposed to render itself. Note that for certain resources, request_POST = request_GET may be desirable in case one wants to process arguments passed to the resource regardless of whether they used GET ( ?foo=bar&baz=quux , and so forth) or POST. When using a Resource , one can specify wrap it using a EncodingResourceWrapper and passing a list of encoder factories. The encoder factories are called when a request is processed and potentially return an encoder. By default twisted provides GzipEncoderFactory which manages standard gzip compression. You can use it this way: from twisted.web.server import Site, GzipEncoderFactory from twisted.web.resource import Resource, EncodingResourceWrapper from twisted.internet import reactor, endpoints class Simple(Resource): isLeaf = True def render_GET(self, request): return "<html>Hello, world!</html>" resource = Simple() wrapped = EncodingResourceWrapper(resource, [GzipEncoderFactory()]) site = Site(wrapped) endpoint = endpoints.TCP4ServerEndpoint(reactor, 8080) endpoint.listen(site) reactor.run() Using compression on SSL served resources where the user can influence the content can lead to information leak, so be careful which resources use request encoders. Note that only encoder can be used per request: the first encoder factory returning an object will be used, so the order in which they are specified matters. HTTP is a stateless protocol; every request-response is treated as an individual unit, distinguishable from any other request only by the URL requested. With the advent of Cookies in the mid nineties, dynamic web servers gained the ability to distinguish between requests coming from different browser sessions by sending a Cookie to a browser. The browser then sends this cookie whenever it makes a request to a web server, allowing the server to track which requests come from which browser session. Twisted Web provides an abstraction of this browser-tracking behavior called the Session object . Calling request.getSession() checks to see if a session cookie has been set; if not, it creates a unique session id, creates a Session object, stores it in the Site, and returns it. If a session object already exists, the same session object is returned. In this way, you can store data specific to the session in the session object. A proxy is a general term for a server that functions as an intermediary between clients and other servers. Twisted supports two main proxy variants: a Proxy and a ReverseProxy . A proxy forwards requests made by a client to a destination server. Proxies typically sit on the internal network for a client or out on the internet, and have many uses, including caching, packet filtering, auditing, and circumventing local access restrictions to web content. Here is an example of a simple but complete web proxy: from twisted.web import proxy, http from twisted.internet import reactor, endpoints class ProxyFactory(http.HTTPFactory): def buildProtocol(self, addr): return proxy.Proxy() endpoint = endpoints.TCP4ServerEndpoint(reactor, 8080) endpoint.listen(ProxyFactory()) reactor.run() With this proxy running, you can configure your web browser to use localhost:8080 as a proxy. After doing so, when browsing the web all requests will go through this proxy. Proxy inherits from http.HTTPChannel . Each client request to the proxy generates a ProxyRequest from the proxy to the destination server on behalf of the client. ProxyRequest uses a ProxyClientFactory to create an instance of the ProxyClient protocol for the connection. ProxyClient inherits from http.HTTPClient . Subclass ProxyRequest to customize the way requests are processed or logged. A reverse proxy retrieves resources from other servers on behalf of a client. Reverse proxies typically sit inside the server’s internal network and are used for caching, application firewalls, and load balancing. Here is an example of a basic reverse proxy: from twisted.internet import reactor, endpoints from twisted.web import proxy, server site = server.Site(proxy.ReverseProxyResource('', 80, '')) endpoint = endpoints.TCP4ServerEndpoint(reactor, 8080) endpoint.listen(site) reactor.run() With this reverse proxy running locally, you can visit in your web browser, and the reverse proxy will proxy your connection to. In this example we use server.Site to serve a ReverseProxyResource directly. There is also a ReverseProxy family of classes in twisted.web.proxy mirroring those of the Proxy family: Like Proxy , ReverseProxy inherits from http.HTTPChannel . Each client request to the reverse proxy generates a ReverseProxyRequest to the destination server. Like ProxyRequest , ReverseProxyRequest uses a ProxyClientFactory to create an instance of the ProxyClient protocol for the connection. Additional examples of proxies and reverse proxies can be found in the Twisted web examples Non-trivial configurations of Twisted Web are achieved with Python configuration files. This is a Python snippet which builds up a variable called application. Usually, the twisted.application.strports.service function will be used to build a service instance that will be used to make the application listen on a TCP port (80, in case direct web serving is desired), with the listener being a twisted.web.server.Site . The resulting file can then be run with twistd -y . Alternatively a reactor object can be used directly to make a runnable script. The Site will wrap a Resource object – the root. from twisted.application import internet, service, strports from twisted.web import static, server root = static.File("/var/www/htdocs") application = service.Application('web') site = server.Site(root) sc = service.IServiceCollection(application) i = strports.service("tcp:80", site) i.setServiceParent(sc) Most advanced configurations will be in the form of tweaking the root resource object. Usually, the root’s children will be based on the filesystem’s contents. It is possible to override the filesystem by explicit putChild methods. Here are two examples. The first one adds a /doc child to serve the documentation of the installed packages, while the second one adds a cgi-bin directory for CGI scripts. from twisted.internet import reactor, endpoints from twisted.web import static, server root = static.File("/var/www/htdocs") root.putChild("doc", static.File("/usr/share/doc")) endpoint = endpoints.TCP4ServerEndpoint(reactor, 80) endpoint.listen(server.Site(root)) reactor.run() from twisted.internet import reactor, endpoints from twisted.web import static, server, twcgi root = static.File("/var/www/htdocs") root.putChild("cgi-bin", twcgi.CGIDirectory("/var/www/cgi-bin")) endpoint = endpoints.TCP4ServerEndpoint(reactor, 80) endpoint.listen(server.Site(root)) reactor.run() File resources, be they root object or children thereof, have two important attributes that often need to be modified: indexNames and processors . indexNames determines which files are treated as “index files” – served up when a directory is rendered. processors determine how certain file extensions are treated. Here is an example for both, creating a site where all .rpy extensions are Resource Scripts, and which renders directories by searching for a index.rpy file. from twisted.application import internet, service, strports from twisted.web import static, server, script root = static.File("/var/www/htdocs") root.indexNames=['index.rpy'] root.processors = {'.rpy': script.ResourceScript} application = service.Application('web') sc = service.IServiceCollection(application) site = server.Site(root) i = strports.service("tcp:80", site) i.setServiceParent(sc) File objects also have a method called ignoreExt . This method can be used to give extension-less URLs to users, so that implementation is hidden. Here is an example: from twisted.application import internet, service, strports from twisted.web import static, server, script root = static.File("/var/www/htdocs") root.ignoreExt(".rpy") root.processors = {'.rpy': script.ResourceScript} application = service.Application('web') sc = service.IServiceCollection(application) site = server.Site(root) i = strports.service("tcp:80", site) i.setServiceParent(sc) Now, a URL such as /foo might be served from a Resource Script called foo.rpy , if no file by the name of foo exists. Virtual hosting is done via a special resource, that should be used as the root resource – NameVirtualHost . NameVirtualHost has an attribute named default , which holds the default website. If a different root for some other name is desired, the addHost method should be called. from twisted.application import internet, service, strports from twisted.web import static, server, vhost, script root = vhost.NameVirtualHost() # Add a default -- htdocs root.default=static.File("/var/www/htdocs") # Add a simple virtual host -- foo.com root.addHost("foo.com", static.File("/var/www/foo")) # Add a simple virtual host -- bar.com root.addHost("bar.com", static.File("/var/www/bar")) # The "baz" people want to use Resource Scripts in their web site baz = static.File("/var/www/baz") baz.processors = {'.rpy': script.ResourceScript} baz.ignoreExt('.rpy') root.addHost('baz', baz) application = service.Application('web') sc = service.IServiceCollection(application) site = server.Site(root) i = strports.service("tcp:80", site) i.setServiceParent(sc) Since the configuration is a Python snippet, it is possible to use the full power of Python. Here are some simple examples: # No need for configuration of virtual hosts -- just make sure # a directory /var/vhosts/<vhost name> exists: from twisted.web import vhost, static, server from twisted.application import internet, service, strports root = vhost.NameVirtualHost() root.default = static.File("/var/www/htdocs") for dir in os.listdir("/var/vhosts"): root.addHost(dir, static.File(os.path.join("/var/vhosts", dir))) application = service.Application('web') sc = service.IServiceCollection(application) site = server.Site(root) i = strports.service("tcp:80", site) i.setServiceParent(sc) # Determine ports we listen on based on a file with numbers: from twisted.web import vhost, static, server from twisted.application import internet, service root = static.File("/var/www/htdocs") site = server.Site(root) application = service.Application('web') serviceCollection = service.IServiceCollection(application) with open("/etc/web/ports") as f: for num in map(int, f.read().split()): serviceCollection.addCollection( strports.service("tcp:%d" % num, site) ) In many cases, you’ll end up repeating common usage patterns of twisted.web. In those cases you’ll probably want to use Twisted’s pre-configured web server setup. The easiest way to run a Twisted Web server is with the Twisted Daemonizer. For example, this command will run a web server which serves static files from a particular directory: % twistd web --path /path/to/web/content If you just want to serve content from your own home directory, the following will do: % twistd web --path ~/public_html/ You can stop the server at any time by going back to the directory you started it in and running the command: % kill `cat twistd.pid` Some other configuration options are available as well: --port: Specify the port for the web server to listen on. This defaults to 8080. --logfile: Specify the path to the log file. The full set of options that are available can be seen with: % twistd web --help A Resource script is a Python file ending with the extension .rpy , which is required to create an instance of a (subclass of a) twisted.web.resource.Resource . Resource scripts have 3 special variables: __file__: The name of the .rpy file, including the full path. This variable is automatically defined and present within the namespace. registry: An object of class static.Registry . It can be used to access and set persistent data keyed by a class. resource: The variable which must be defined by the script and set to the resource instance that will be used to render the page. A very simple Resource Script might look like: from twisted.web import resource class MyGreatResource(resource.Resource): def render_GET(self, request): return "<html>foo</html>" resource = MyGreatResource() A slightly more complicated resource script, which accesses some persistent data, might look like: from twisted.web import resource from SillyWeb import Counter counter = registry.getComponent(Counter) if not counter: registry.setComponent(Counter, Counter()) counter = registry.getComponent(Counter) class MyResource(resource.Resource): def render_GET(self, request): counter.increment() return "you are visitor %d" % counter.getValue() resource = MyResource() This is assuming you have the SillyWeb.Counter module, implemented something like the following: class Counter: def __init__(self): self.value = 0 def increment(self): self.value += 1 def getValue(self): return self.value The Nevow framework, available as part of the Quotient project, is an advanced system for giving Web UIs to your application. Nevow uses Twisted Web but is not itself part of Twisted. One of the most interesting applications of Twisted Web is the distributed webserver; multiple servers can all answer requests on the same port, using the twisted.spread package for “spreadable” computing. In two different directories, run the commands: % twistd web --user % twistd web --personal [other options, if you desire] Once you’re running both of these instances, go to – you will see the front page from the server you created with the --personal option. What’s happening here is that the request you’ve sent is being relayed from the central (User) server to your own (Personal) server, over a PB connection. This technique can be highly useful for small “community” sites; using the code that makes this demo work, you can connect one HTTP port to multiple resources running with different permissions on the same machine, on different local machines, or even over the internet to a remote site. By default, a personal server listens on a UNIX socket in the owner’s home directory. The --port option can be used to make it listen on a different address, such as a TCP or SSL server or on a UNIX server in a different location. If you use this option to make a personal server listen on a different address, the central (User) server won’t be able to find it, but a custom server which uses the same APIs as the central server might. Another use of the --port option is to make the UNIX server robust against system crashes. If the server crashes and the UNIX socket is left on the filesystem, the personal server will not be able to restart until it is removed. However, if --port unix:/home/username/.twistd-web-pb:wantPID=1 is supplied when creating the personal server, then a lockfile will be used to keep track of whether the server socket is in use and automatically delete it when it is not. Everything related to CGI is located in the twisted.web.twcgi , and it’s here you’ll find the classes that you need to subclass in order to support the language of your (or somebody elses) taste. You’ll also need to create your own kind of resource if you are using a non-unix operating system (such as Windows), or if the default resources has wrong pathnames to the parsers. The following snippet is a .rpy that serves perl-files. Look at twisted.web.twcgi for more examples regarding twisted.web and CGI. from twisted.web import static, twcgi class PerlScript(twcgi.FilteredScript): filter = '/usr/bin/perl' # Points to the perl parser resource = static.File("/perlsite") # Points to the perl website resource.processors = {".pl": PerlScript} # Files that end with .pl will be # processed by PerlScript resource.indexNames = ['index.pl'] WSGI is the Web Server Gateway Interface. It is a specification for web servers and application servers to communicate with Python web applications. All modern Python web frameworks support the WSGI interface. The easiest way to get started with WSGI application is to use the twistd command: % twistd -n web --wsgi=helloworld.application This assumes that you have a WSGI application called application in your helloworld module/package, which might look like this: def application(environ, start_response): """Basic WSGI Application""" start_response('200 OK', [('Content-type','text/plain')]) return ['Hello World!'] The above setup will be suitable for many applications where all that is needed is to server the WSGI application at the site’s root. However, for greater control, Twisted provides support for using WSGI applications as resources twisted.web.wsgi.WSGIResource . Here is an example of a WSGI application being served as the root resource for a site, in the following tac file: from twisted.web import server from twisted.web.wsgi import WSGIResource from twisted.python.threadpool import ThreadPool from twisted.internet import reactor from twisted.application import service, strports # Create and start a thread pool, wsgiThreadPool = ThreadPool() wsgiThreadPool.start() # ensuring that it will be stopped when the reactor shuts down reactor.addSystemEventTrigger('after', 'shutdown', wsgiThreadPool.stop) def application(environ, start_response): """A basic WSGI application""" start_response('200 OK', [('Content-type','text/plain')]) return ['Hello World!'] # Create the WSGI resource wsgiAppAsResource = WSGIResource(reactor, wsgiThreadPool, application) # Hooks for twistd application = service.Application('Twisted.web.wsgi Hello World Example') server = strports.service('tcp:8080', server.Site(wsgiAppAsResource)) server.setServiceParent(application) This can then be run like any other .tac file: % twistd -ny myapp.tac Because of the synchronous nature of WSGI, each application call (for each request) is called within a thread, and the result is written back to the web server. For this, a twisted.python.threadpool.ThreadPool instance is used. It is common to use one server (for example, Apache) on a site with multiple names which then uses reverse proxy (in Apache, via mod_proxy ) to different internal web servers, possibly on different machines. However, naive configuration causes miscommunication: the internal server firmly believes it is running on “internal-name:port” , and will generate URLs to that effect, which will be completely wrong when received by the client. While Apache has the ProxyPassReverse directive, it is really a hack and is nowhere near comprehensive enough. Instead, the recommended practice in case the internal web server is Twisted Web is to use VHostMonster. From the Twisted side, using VHostMonster is easy: just drop a file named (for example) vhost.rpy containing the following: from twisted.web import vhost resource = vhost.VHostMonsterResource() Make sure the web server is configured with the correct processors for the rpy extensions (the web server twistd web --path generates by default is so configured). From the Apache side, instead of using the following ProxyPass directive: <VirtualHost ip-addr> ProxyPass / ServerName example.com </VirtualHost> Use the following directive: <VirtualHost ip-addr> ProxyPass / ServerName example.com </VirtualHost> Here is an example for Twisted Web’s reverse proxy: from twisted.application import internet, service, strports from twisted.web import proxy, server, vhost vhostName = 'example.com' reverseProxy = proxy.ReverseProxyResource('internal', 8538, '/vhost.rpy/http/'+vhostName+'/') root = vhost.NameVirtualHost() root.addHost(vhostName, reverseProxy) site = server.Site(root) application = service.Application('web-proxy') sc = service.IServiceCollection(application) i = strports.service("tcp:80", site) i.setServiceParent(sc) Sometimes it is convenient to modify the content of the Request object before passing it on. Because this is most often used to rewrite either the URL, the similarity to Apache’s mod_rewrite has inspired the twisted.web.rewrite module. Using this module is done via wrapping a resource with a twisted.web.rewrite.RewriterResource which then has rewrite rules. Rewrite rules are functions which accept a request object, and possible modify it. After all rewrite rules run, the child resolution chain continues as if the wrapped resource, rather than the RewriterResource , was the child. Here is an example, using the only rule currently supplied by Twisted itself: default_root = rewrite.RewriterResource(default, rewrite.tildeToUsers) This causes the URL /~foo/bar.html to be treated like /users/foo/bar.html . If done after setting default’s users child to a distrib.UserDirectory , it gives a configuration similar to the classical configuration of web server, common since the first NCSA servers. Sometimes it is useful to know when the other side has broken the connection. Here is an example which does that: from twisted.web.resource import Resource from twisted.web import server from twisted.internet import reactor from twisted.python.util import println class ExampleResource(Resource): def render_GET(self, request): request.write("hello world") d = request.notifyFinish() d.addCallback(lambda _: println("finished normally")) d.addErrback(println, "error") reactor.callLater(10, request.finish) return server.NOT_DONE_YET resource = ExampleResource() This will allow us to run statistics on the log-file to see how many users are frustrated after merely 10 seconds. Sometimes, you want to be able to send headers and status directly. While you can do this with a ResourceScript , an easier way is to use ASISProcessor . Use it by, for example, adding it as a processor for the .asis extension. Here is a sample file: HTTP/1.0 200 OK Content-Type: text/html Hello world
http://twistedmatrix.com/documents/current/web/howto/using-twistedweb.html
CC-MAIN-2017-13
refinedweb
4,076
51.34