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
Copyright ©2000 W3C® (MIT, INRIA, Keio), All Rights Reserved. W3C liability, trademark, document use and software licensing rules apply. This document introduces the XML Query Algebra as a formal basis for purpose of this document is to present the current state of the XML Query Algebra and to elicit feedback on its current state. The XML Query Working Group feels. This examples based on accessing a database of books. Consider the following sample data: <bib> <book year="1999" isbn="1-55860-622-X"> <title>Data on the Web</title> <author>Abiteboul</author> <author>Buneman</author> <author>Suciu</author> </book> <book year="2001" isbn="1-XXXXX-YYY-Z"> <title>XML Query</title> <author>Fernandez</author> <author>Suciu</author> </book> </bib> Here is a fragment of a XML Schema for such data: <xsd:group <xsd:element <xsd:complexType> <xsd:group </xsd:complexType> </xsd:element> </xsd:group> <xsd:group <xsd:element <xsd:complexType> <xsd:attribute <xsd:attribute <xsd:element <xsd:element </xsd:complexType> </xsd:element> </xsd:group> This data and schema is represented in our algebra as follows: type Bib = bib [ Book{0, *} ] type Book = book [ @year [ Integer ] & @isbn [ String ], title [ String ], author [ String ]{1, *} ] let bib0 : Bib = bib [ book [ @year [ 1999 ], @isbn [ "1-55860-622-X" ], title [ "Data on the Web" ], author [ "Abiteboul" ], author [ "Buneman" ], author [ "Suciu" ] ], book [ @year [ 2001 ], @isbn [ "1-XXXXX-YYY-Z" ], title [ "XML Query" ], author [ "Fernandez" ], author [ "Suciu" ] ] ] The expression above defines two types, Bib and Book, and defines one global variable, bib0. The Bib type corresponds to a single bib element, which contains a forest of zero or more Book elements. We use the term forest to refer to contains two book elements. The algebra is a strongly typed language, therefore the value of bib0 must be an instance of its declared type, or the expression is ill-typed. Here the value of bib0 is an instance of the Bib type, because it contains one bib element, which contains two book elements, each of which contain an integer-valued year attribute, a string-valued isbn attribute, a string-valued title element, and one or more string-valued author elements. For convenience, we define a second global variable book0 also bound to a literal value, which is equal to the first book in bib0. let book0 : Book = book [ @year [ 1999 ], @isbn [ "1-55860-622-X" ], title [ "Data on the Web" ], author [ "Abiteboul" ], author [ "Buneman" ], author [ "Suciu" ] ] The simplest operation is projection. The algebra uses a notation similar in appearance and meaning to path navigation in XPath. The following expression returns all author elements contained in book elements contained in bib0: bib0/book/author ==> author [ "Abiteboul" ], author [ "Buneman" ], author [ "Suciu" ], author [ "Fernandez" ], author [ "Suciu" ] : author [ String ] {0, *} Note that in the result, the document order of author elements is preserved and that duplicate elements are also preserved. The above example and the ones that follow have three parts. First is an expression in the algebra. Second, following the ==> is the value of this expression. Third, following the : is the type of the expression, which is (of course) also a legal type for the value. It may be unclear why the type of bib0/book/author contains zero or more authors, even though the type of a book element contains one or more authors. Let's look at the derivation of the result type by looking at the type of each sub-expression: bib0 : Bib bib0/book : Book{0, *} bib0/book/author : author [ String ]{0, *} Recall that Bib, the type of bib0, may contain zero or more Book elements, therefore the expression bib0/book might contain zero book elements, in which case, bib0/book/author would contain no authors. This illustrates an important feature of the type system: the type of an expression depends only on the type of its sub-expressions. It also illustrates the difference between an expression's. One may access atomic data (strings, integers, or booleans) using the keyword data(). For instance, if we wish to select all author names in a book, rather than all author elements, we could write the following. book0/author/data() ==> "Abiteboul", "Buneman", "Suciu" : String {1, *} Similarly, it is possible to project the atomic values of attributes. The following returns the year the book was published. book0/@year/data() ==> 1999 : Integer This notation is similar to the use of text() in XPath. We chose the keyword data() because, as the second example shows, not all data items are strings. Another common operation is to iterate over elements in a document so that their content can be transformed into new content. Here is an example of how to process each book to list the author before the title, and remove the year and isbn. for b in bib0/book do book [ b/author, b/title ] ==> book [ author [ "Abiteboul" ], author [ "Buneman" ], author [ "Suciu" ], title [ "Data on the Web" ] ], book [ author [ "Fernandez" ], author [ "Suciu" ], title [ "XML Query" ] ] : book [ author[ String ]{1, *}, title[ String ] ]{0, *} The for expression iterates over all book elements in bib0, and binds the variable b to each such element. For each element bound to b, the inner expression constructs a new book element containing the book's authors followed by its title. The transformed elements appear in the same order as they occur in bib0. In the result type, a book element is guaranteed to contain one or more authors followed by one title. Let's look at the derivation of the result type to see why: bib0/book : Book{0, *} b : Book b/author : author [ String ]{1, *} b/title : title [ String ] The type system can determine that b is always Book, therefore the type of b/author is author[ String ]{1, *}, and the type of b/title is title[ String ]. In general, the value of a for expression is a forest. If the body of the for expression itself yields a forest, then all of the forests are concatenated together. For instance, the expression: for b in bib0/book do b/author is exactly equivalent to the expression bib0/book/author. Here we have explained the typing of for expressions by example. In fact, the typing rules are rather subtle and will be explained in detail in [5 Type Rules]. To select values that satisfy some predicate, we use the where expression. For example, the following expression selects all book elements in bib0 that were published before 2000. for b in bib0/book do where b/@year/data() <= 2000 do b ==> book [ @year [ 1999 ], @isbn [ "1-55860-622-X" ], title [ "Data on the Web" ], author [ "Abiteboul" ], author [ "Buneman" ], author [ "Suciu" ] ] : Book{0, *} In general, an expression of the form: where e1 do e2 is converted to the form if e1 then e2 else () where e1 and e2 are expressions. Here () is an expression that stands for the empty sequence, a forest that contains no attributes or elements. We also write () for the type of the empty sequence. According to this rule, the expression above translates to for b in bib0/book do if b/@year/data() <= 2000 then b else () and this has the same value and the same type as the preceding expression. The following expression selects all book elements in bib0 that have some author named "Buneman". for b in bib0/book do for a in distinct(b/author/data()) do where a = "Buneman" do b ==> book [ @year [ 1999 ], @isbn [ "1-55860-622-X" ], title [ "Data on the Web" ], author [ "Abiteboul" ], author [ "Buneman" ], author [ "Suciu" ] ] : Book{0, *} In contrast, we can use the empty operator to find all books that have no author whose name is Buneman: for b in bib0/book do where empty(for a in b/author do where a/data() = "Buneman" do a) do b ==> book [ @year [ 2001 ], @isbn [ "1-XXXXX-YYY-Z" ], title [ "XML Query" ], author [ "Fernandez" ], author [ "Suciu" ] ] : Book{0, *} The empty expression checks that its argument is the empty sequence (). We can also use the empty operator to find all books where all the authors are Buneman, by checking that there are no authors that are not Buneman: for b in bib0/book do where empty(for a in b/author do where a/data() <> "Buneman" do a) do b ==> () : Book{0, *} There are no such books, so the result is the empty sequence. Appropriate use of empty (possibly combined with not) can express universally or existentially quantified expressions. Here is a good place to introduce the let expression, which binds a local variable to a value. Introducing local variables may improve readability. For example, the following expression is exactly equivalent to the previous one. for b in bib0/book do let nonbunemans = (for a in b/author do where a/data() <> "Buneman" do a) do where empty(nonbunemans) do b Local variables can also be used to avoid repetition when the same subexpression appears more than once in a query. Another common operation is to join values from one or more documents. To illustrate joins, we give a second data source that defines book reviews: type Reviews = reviews [ book [ title [ String ], review [ String ] ]{0, *} ] let review0 : Reviews = reviews [ book [ title [ "XML Query" ], review [ "A darn fine book." ] ], book [ title [ "Data on the Web" ], review [ "This is great!" ] ] ] The Reviews type contains one reviews element, which contains zero or more book elements; each book contains a title and a review. We can use nested for expressions to join the two sources review0 and bib0 on title values. The result combines the title, authors, and reviews for each book. for b in bib0/book do for r in review0/book do where b/title/data() = r/title/data() do book [ b/title, b/author, r/review ] ==> book [ title [ "Data on the Web" ], author [ "Abiteboul" ], author [ "Buneman" ], author [ "Suciu" ] review [ "A darn fine book." ] ], book [ title [ "XML Query" ], author [ "Fernandez" ], author [ "Suciu" ] review [ "This is great!" ] ] : book [ title [ String ], author [ String ] {1, *}, review [ String ] ] {0, *} Note that the outer-most for expression determines the order of the result. Readers familiar with optimization of relational join queries know that relational joins commute, i.e., they can be evaluated in any order. This is not true for the/data()) do biblio [ author[a], for b in bib0/book do for a2 in b/author/data() do where a = a2 do b/title ] ==> biblio [ author [ "Abiteboul" ], title [ "Data on the Web" ] ], biblio [ author [ "Buneman" ], title [ "Data on the Web" ] ], biblio [ author [ "Suciu" ], title [ "Data on the Web" ], title [ "XML Query" ] ], biblio [ author [ "Fernandez" ], title [ "XML Query" ] ] : biblio [ author [ String ], title [ String ] {0, *} ] {0, *} Readers may recognize this expression as a self-join of books on authors. The expression. The type of the result expression may seem surprising: each biblio element may contain zero or more title elements, even though in bib0 every author co-occurs with a title. Recognizing such a constraint is outside the scope of the type system, so the resulting type is not as precise as we would like. Often it is useful to query the order of elements in.) To sort a forest, the algebra provides a sort expression, whose form is: sort Var in Exp1 by Exp2. The variable Var ranges over the items in the forest Exp1 and sorts those items using the key value defined by Exp2. For example, this expression sorts book elements in review0 by their titles. Note that the variable b, and sort. In addition to these functions, the algebra has five built-in aggregation functions: avg, count, max, min, and sum. This expression selects books that have more than two authors: for b in bib0/book do where count(b/author) > 2 do b ==> book [ @year [ 1999 ], @isbn [ "1-55860-622-X" ], title [ "Data on the Web" ], author [ "Abiteboul" ], author [ "Buneman" ], author [ "Suciu" ] ] : Book{0, *} All the aggregation functions take a forest with repetition type and return an integer value; count returns the number of elements in the forest. So far, all our examples of attributes and elements use unqualified local names, i.e., names that do not include an explicit namespace URI. It is also possible to specify and match on the expanded name of an attribute or element. The expanded name {Namespace}LocalName consists of a namespace URI Namespace and a local name LocalName. Consider an inventory of books that contains data from both and. In this example, the first element contains values whose names are defined in the BooksRUs.com namespace, and the second element contains values whose names are defined in the cheapBooks.com namespace: let inventory = inv [ {}book [ @{}year [ 1999 ], @{}isbn [ "1-55860-622-X" ], {}title [ "Data on the Web" ], {}author [ "Abiteboul" ], {}author [ "Buneman" ], {}author [ "Suciu" ] ], {}book [ @{}year [ 2001 ], {}title [ "XML Query" ], {}author [ "Fernandez" ], {}author [ "Suciu" ] {}isbn [ "1-XXXXX-YYY-Z" ], ] ] ] : Inventory type Inventory = inv [ InvBook{0, *}] In this example, elements imported from existing schemas each refer to a single namespace, thus the definition of InvBook is: type BooksRUBook = {}book [ @{}year [ Integer ] & @{}isbn [ String ], {}title [ String ], {}author [ String ]{1, *} ] type CheapBooksBook = {}book [ @{}year [ Integer ], {}title [ String ], {}author [ String ]{1, *}, {}isbn [ String ], ] type InvBook = BooksRUBook | CheapBooksBook Here vertical bar ( |) is used to indicate a choice between types: each InvBook is either a BooksRUBook or a CheapBooksBook. We have already seen how to project on the constant name of an attribute or element. It is also useful to project on wildcards, which are used to match names with any namespace and/or any local name. For example, this expression matches elements with any local name and with namespace URI: inventory/{}* ==> {}book [ {}title [ "Data on the Web" ], {}author [ "Abiteboul" ], {}author [ "Buneman" ], {}author [ "Suciu" ] ] : {}book [ {}title [ String ], {}author [ String ] {0, *}, ] Similarly, this expression first projects elements in any namespace whose local name is book and then projects on their year attributes: inventory/{*}book/@{*}year ==> @{}year [ 1999 ], @{}year [ 2001 ], : (@{}year [ Integer ] | @{}year [ Integer ]){0,*} In general, the expression Exp/a is shorthand for Exp/{*}a, that is, the namespace wildcard can be omitted. Similarly, * is shorthand for {*}*. Functions can make queries more modular and concise. Recall that we used the following query to find all books that do not have "Buneman" as an author. for b in bib0/book do where empty(for a in b/author do where a/data() = "Buneman" do a) do b ==> book [ @year [ 2001 ], @isbn [ "1-XXXXX-YYY-Z" ], title [ "XML Query" ], author [ "Fernandez" ], author [ "Suciu" ] ] : Book{0, *} A different way to formulate this query is to first define a function that takes a string s and a book b as arguments, and returns true if book b does not have an author with name s. fun notauthor (s : String; b : Book) : Boolean = empty(for a in b/author do where a/data() = s do a) The query can then be re-expressed as follows. for b in bib0/book do where notauthor("Buneman"; b) do b ==> book [ @year [ 2001 ], @isbn [ "1-XXXXX-YYY-Z" ], title [ "XML Query" ], author [ "Fernandez" ], author [ "Suciu" ] ] : Book{0, *} We use semicolon rather than comma to separate function arguments, since comma is used to concatenate forests. Note that a function declaration includes the types of all its arguments and the type of its result. This is necessary for the type system to guarantee that applications of functions are type correct. In general, any number of functions may be declared at the top-level. The order of function declarations does not matter, and each function may refer to any other function. Among other things, this allows functions to be recursive (or mutually recursive), which supports structural recursion, the subject of the next section. Functions make the algebra extensible. We have seen examples of built-in functions ( sort and distinct) and examples of user-defined functions ( notauthor). In addition to built-in and user-defined functions, the algebra could support externally defined functions, i.e., functions that are not defined in the algebra itself, but in some external language. This would make special-purpose implementations of, for example, full-text search functions available in the algebra. We discuss support for externally defined functions in [B.2 Issues list]. XML documents can be recursive in structure, for example, it is possible to define a part element that directly or indirectly contains other part elements. In the algebra, we use recursive types to define documents with a recursive structure, and we use recursive functions to process such documents. (We can also use mutually recursive functions for more complex recursive structures.) For instance, here is a recursive type defining a part hierarchy. type Part = Basic | Composite type Basic = basic [ cost [ Integer ] ] type Composite = composite [ assembly_cost [ Integer ], subparts [ Part{1, *} ] ] And here is some sample data. let part0 : Part = composite [ assembly_cost [ 12 ], subparts [ composite [ assembly_cost [ 22 ], subparts [ basic [ cost [ 33 ] ] ] ], basic [ cost [ 7 ] ] ] ] Here vertical bar ( |) is used to indicate a choice between types: each part is either basic (no subparts), and has a cost, or is composite, and includes an assembly cost and subparts. We might want to translate to a second form, where every part has a total cost and a list of subparts (for a basic part, the list of subparts is empty). type Part2 = part [ total_cost [ Integer ], subparts [ Part2{0, *} ] ] Here is a recursive function that performs the desired transformation. It uses a new construct, the match expression. fun convert(p : Part) : Part2 = match p case b : Basic do part [ total_cost [ b/cost/data() ], subparts [] ] case c : Composite do let s = (for y in children(c/subparts) do convert(y)) do part [ total_cost [ q/assembly_cost/data() + sum(s/total_cost/data()) ], subparts[ s ] ] else error Each branch of the match expression is labeled with a type, Basic or Composite, and with a corresponding variable, b or c. The evaluator checks the type of the value of p at run-time, and evaluates the corresponding branch. If the first branch is taken then b is bound to the value of p, and the branch returns a new part with total cost the same as the cost of b, and with no subparts. If the second branch is taken, then c is bound to the value of p. The function is recursively applied to each of the subparts of c, giving a list of new subparts s. The branch returns a new part with total cost computed by adding the assembly cost of c to the sum of the total cost of each subpart in s, and with subparts s. One might wonder why b and c are required, since they have the same value as p. The reason why is that p, b, and c have different types. p : Part b : Basic c : Composite The types of b and c are more precise than the type of p, because which branch is taken depends upon the type of value in p. Applying the query to the given data gives the following result. convert(part0) ==> part [ total_cost [ 74 ], subparts [ part [ total_cost [ 55 ], subparts [ part [ total_cost [ 33 ], subparts [] ] ] ], part [ total_cost [ 7 ], subparts [] ] ] ] Of course, a match expression may be used in any query, not just in a recursive one. Recursive types allow us to define a type that matches any well-formed XML document. This type is called AnyTree : type AnyTree = AnyScalar | AnyElement | AnyAttribute type AnySimpleType = AnyScalar | AnyScalar{0,*} type AnyAttribute = @*[ AnySimpleType ] type AnyElement = *[ AnyComplexType ] type AnyComplexType = AnyTree{0, *} type AnyType = AnySimpleType | AnyComplexType AnyTree stands for any scalar, element, or attribute value. Here AnyScalar is a built-in scalar type. It stands for the most general scalar type, and all other scalar types (like Integer or String) are subtypes of it. AnySimpleType stands for the most general simple type, which is a scalar or a list of scalars. AnyAttribute stands for the most general attribute type. The asterisk ( *) is used to indicate a wild-card type, i.e., a type whose name is not known statically. The type AnyAttribute may have any name, and its content must have type AnySimpleType, i.e., it may contain atomic values, but no elements. The AnyElement stands for the most general element type, which may have any name, and its content must be a complex type, which is a repetition of zero or more AnyTrees. Finally, an AnyTree is either an AnySimpleType or an AnyComplexType. In other words, any element, attribute, or atomic value has type AnyType. The use of * is a significant extension to XML Schema, because XML Schema has no type corresponding to *[t], where t is some type other than AnyComplexType. It is not clear that this extension is necessary, since the more restrictive expressiveness of XML Schema wildcards may be adequate. In particular, our earlier data also has type AnyTree. book0 : AnyTree ==> book [ @year [ 1999 ], @isbn [ "1-55860-622-X" ], title [ "Data on the Web" ], author [ "Abiteboul" ], author [ "Buneman" ], author [ "Suciu" ] ] : AnyTree A specific type can be indicated for any expression in the query language, by writing a colon and the type after the expression. As an example of a function that can be applied to all well-formed documents, we define a recursive function that converts any XML data into HTML. We first give a simplified definition of HTML. type HTML_body = ( AnyScalar | b [ HTML_body ] | ul [ (li [ HTML_body ]){0, *} ] ) {0, *} An HTML body consists of a sequence of zero or more items, each of which is either a scalar, or a b element, where the content is an HTML body, or an ul element, where the children are li elements, each of which has as content an HTML body. Now, here is the function that performs the conversion. fun html_of_xml( x : AnyTree ) : Html_Body = match x case s : AnyScalar do s case v1 : AnyAttribute do b [ name(v1) ], ul [ for y in match expression checks whether the value of x is a subtype of AnyScalar, and if so then s is bound to that value, so if this branch is taken then s is the same as x, but with a more precise type (it must be a scalar, not an element). This branch returns the scalar. The second branch checks whether the value of x is a subtype of AnyAttribute. As before, v1 is the same as x but with a more precise type (it must be an attribute, not a scalar). This branch returns a b element containing the name of the attribute, and a ul element containing one li element for each value of the attribute. The function is recursively applied to get the content of the li element. The last branch is analogous to the second, but it matches an element instead of an attribute, and it applies html_of_xml to each of the element's attributes and children. Applying the query to the book element above gives the following result. html_of_xml(book0) ==> b [ "book" ], ul [ li [ b [ "year" ], ul [ li [ 1999 ] ] ], li [ b [ "isbn" ], ul [ li [ "1-55860-622-X" ] ] ], li [ b [ "title" ], ul [ li [ "Data on the Web" ] ] ], li [ b [ "author" ], ul [ li [ "Abiteboul" ] ] ], li [ b [ "author" ], ul [ li [ "Buneman" ] ] ], li [ b [ "author" ], ul [ li [ "Suciu" ] ] ] ] : HTML_Body A query consists of a sequence of top-level expressions, or query items, where each query item is either a type declaration, a function declaration, a global variable declaration, or a query expression. The order of query items is immaterial; all type, function, and global variable declarations may be mutually recursive. Each query expression is evaluated in the environment specified by all of the declarations. (Typically, all of the declarations will precede all of the query expressions, but this is not required.) We have already seen examples of type, function, and global variable declarations. An example of a query expression is: query html_of_xml(book0) To transform any expression into a top-level query, we simply precede the expression by the query keyword. In this section, we summarize the algebra and present the grammars for types and expressions. We start by defining the non-terminal and terminal symbols that appear in the type and expression grammars. A Namespace is a URI, and a LocalName is an NCName, as in the Namespace recommendation [XML Names]. We let Namespace range over namespaces and the null value, which represents the absence of a namespace, and LocalName range over NCNames. The symbol Name ranges over expanded names. An expanded name is either a local name for which the namespace is absent or namespace, local name pairs. Ed. Note: MF (Oct-13-2000): We need to add the data model accessors that extract the namespace and the local name from an expanded name. A wildcard denotes a set of names. A wildcard item is of the form {*}* denoting any name in any namespace, {Namespace} * denoting any name in namespace Namespace, { *}LocalName denoting the local name LocalName in any namespace, or {Namespace}LocalName denoting just the name with namespace Namespace and local name LocalName. A wildcard consists of wildcard items, union of wildcards, or difference of wildcards. We let WItem range over wildcard items, and Wild range over wildcard expressions. For example, the wildcard {*}*!{}*!{}String denotes any name in any namespace except for names in namespace and for local name String in namespace. Wildcards denote sets of expanded names, so we can define a containment relation, <:wild that relate sets of wildcards. The inequalities that hold for this relation include: The last inequality holds by transitivity. Note, however, that {*}LocalName <:wild {Namespace}* does not necessarily hold. The Algebra takes as given the atomic datatypes from XML Schema Part 2 [XSchema2]. We let p range over all atomic datatypes. Typically, an atomic datatype is either a primitive datatype, or is derived from another atomic datatype by specifying a set of facets. A type hierarchy is induced between scalar types by containment of facets. Note that lists of atomic datatypes are specified using repetition and unions are specified using alternation, as defined in [3.4 Types : abstract syntax] The built-in atomic data type AnyScalar stands for the most general scalar type, and all other scalar types (like Integer or String) are subtypes of it. [Figure 1] contains the abstract syntax for the Algebra's type system. A type is closely related to a model group as defined in [MSL]. MSL uses standard regular expression notation for model groups and we do the same for algebra types. This type system captures the essence of . The bounds on a repetition type will be either a natural number (that is, either a positive integer or zero) or the special value *, meaning unbounded. We extend arithmetic to include * in the obvious way: For technical reasons, we allow the lower bound of a repetition to be *. A repetition t {m, n} is equivalent to the empty choice Ø if m > n or if m is *. The algebra's external type system, that is, the type definitions associated with input and output documents, is XML Schema. The internal types are in some ways more expressive than XML Schema, for example, XML Schema has no type corresponding to {*}*[t] where t is some type other than AnyComplexType. In general, mapping XML Schema types into internal types will not lose information, however, mapping internal types into XML Schema may lose information. It is useful to define a concrete syntax for the Algebra's types using syntactic categories that specify various subsets of types. Syntactic classes can indicate, for example, that the content of an attribute should be a simple type and that the content of an element should consist of attributes followed by elements. These restrictions guarantee that errors in type construction can be caught during parsing of a query. In the concrete syntax for types, we capitalize non-terminal symbols. We first distinguish between type variables used to name attribute groups, element groups, and the content types of elements. A simple type is either an atomic type, a list of atomic types, or a choice of atomic types, which allows a choice of atomic lists. An attribute group defines the syntactic form of attributes: their content may only be a simple type and they are combined only in all groups, not sequences. An element group contains elements with constant or wildcard names and they are combined in sequences, choices, all groups, and repetitions. The content type of an element is either an attribute group, an element group, a sequence of an attribute group followed by an element group, or a content-type variable. Finally, a type in an algebraic expression may be an attribute group, an element group, or a content type: Ed. Note: MF (Nov-16-2000): This needs work. [Figure 2] contains the concrete syntax for of the element book0, namely, a title element and three author elements (the order is preserved). The for expression binds the variable v successively to each of these elements. Then the match expression selects a branch based on the type of v. If it is an author element then the first branch is evaluated, otherwise the second branch. If the first branch is evaluated, it returns a. The variable a contains the same value as v, but the type of a is author[String], which is the intersection of the type of v and the type author[AnyComplexType]. If the second branch is evaluated, then the branch returns (), the empty sequence. To compose several expressions using /, we again use for expressions. For example, the expression: bib0/book/author is equivalent to the expression: for b in children(bib0) do match b case b : book[AnyComplexType] do for d in children(b) do match d case a : author[AnyComplexType] do a else () else () The for expression iterates over all book elements in bib0 and binds the variable b to each such element. For each element bound to b, the inner expression returns all the author elements in b, and the resulting forests are concatenated together in order. In general, an expression of the form e / a is converted to the form for v1 in e do for v2 in children(v1) do match v2 case v3 : a[AnyComplexType] do v3 else () where e is an expression, a is an element name, and v1, v2, and v3 are fresh variables (ones that do not appear in the expression being converted). According to this rule, the expression bib0/book translates to for v1 in bib0 do for v2 in. In Rule 1, the projection expression e / Wild is rewritten as a for expression, which binds v to each element in the forest e, and returns the children elements of v whose name is in Wild. Similarly, Rule 2 rewrites the attribute projection expression e / @Wild as a match embedded in a for expression. Rule 3 rewrites the e /: Definitions In this section, we describe some laws that hold for the algebra. These laws are important for defining rules that simplify algebraic expressions, such as eliminating unnecessary for or match expressions. The iteration construct of the algebra is closely related to an important mathematical object called a monad. A monad, among other things, generalizes set, bag, and list types. In functional languages, the comprehension construct is used to express iteration over set, bag, and list types. A comprehension corresponds directly to a monad [Wad92], [Wad93], [Wad95]. The correspondence between the algebra's iteration construct and a monad is close, but not exact. Each monad is based on a unary type constructor, such as Set{t} or List{t}, representing a homogenous set or list where all elements are of type t. In the algebra, we have more complex and heterogenous types, such as a forest consisting of a title, a year, and a sequence of one or more authors. Also, one important component of a monad is the unit operator, which converts an element to a set or list. If x has type t, then set{x} is a unit set of type Set{t} or [x] is a unit list of type List{t}. In the algebra, we simply write, say, author["Buneman"], which stands for both a tree and for the unit forest containing that tree. Monads satisfy three laws, and three corresponding laws are satisfied by the the Algebra's for expression. First, iteration over a unit forest can be replaced by substition. This is called the left unit law. for v in e1 do e2 = e2{v := e1} provided that e1 is a unit type (e.g., is an element or a scalar constant). We write e2{v := e1} to denote the result of taking expression e2 and replacing occurrences of the variable v by the expression e1. For example, for v in author["Buneman"] do auth[v/data()] = auth["Buneman"] The iteration over a forest of one item can always be eliminated using variable substitution. Second, an iteration that returns the iteration variable is equivalent to the identity. This is called the right unit law. for v in e do v = e For example for v in book0 do v = book0 An important feature of the type system described here is that the left side of the above equation always has the same type as the right side. Third, there are two ways of writing an iteration over an iteration, both of which are equivalent. This is called the associative law. for v2 in (for v1 in e1 do e2) do e3 = for v1 in e1 do (for v2 in e2 do e3) For example, a projection over a forest includes an implicit iteration, so e / a = for v in e do v / a. Say we define a forest of bibliographies, bib1 = bib0, bib0. Then bib1/book/author is equivalent to the first expression below, which in turn is equivalent to the second. for b in (for a in bib1 do a/book) do b/author = for a in bib1 do (for b in a/book do b/author) With nested relational algebra, the monad laws play a key role in optimizing queries. Similarly, the monad laws can also be exploited for optimization in this context. For example, if b is a book, the following finds all authors of the book that are not Buneman: for a in b do where a/data() != Buneman do a If l is a list of authors, the following renames all author elements to auth elements: for a' in l do auth[ a'/data() ] Combining these, we select all authors that are not Buneman, and rename the elements: for a' in (for a in b do where a/data() != Buneman do a) do auth[ a'/data() ] Applying the associative law for a monad, we get: for a in b do for a' in (where a/data() != Buneman do a) do auth[ a'/data() ] Expanding the where clause to a conditional, we get: for a in b do for a' in (if a/data() != Buneman then a else ()) do auth[ a'/data() ] Applying a standard law for distributing loops over conditionals gives: for a in b do if a/data() != Buneman then for a' in a do auth[ a'/data() ] else () Applying the left unit law for a monad, we get: for a in b do if a/data() != Buneman then auth[ a/data() ] else () And replacing the conditional by a where clause, we get: for a in b do where a/data() != Buneman do auth[ a/data() ] Thus, simple manipulations, including the monad laws, fuse the two loops. [4.1 Relating projection to iteration] ended with two examples of simplification. Returning to these, we can now see that the simplifications are achieved by application of the left unit and associative monad laws. [Figure 5] contains a dozen algebraic simplification laws. In a relational query engine, algebraic simplifications are often applied by a query optimizer before a physical execution plan is generated; algebraic simplification can often reduce the size of the intermediate results computed by a query evaluator. The purpose of our laws is similar -- they eliminate unnecessary for or match expressions, or they enable other optimizations by reordering or distributing computations. The set of laws given is suggestive, rather than complete. Figure 5: Optimization Laws Rules 8, 9, and 10 simplify iterations. Rule 8 rewrites an iteration over the empty sequence as the empty sequence. Rule 9 distributes iteration through sequence: iterating over the sequence (e1, e2) is equivalent to the sequence of two iterations, one over e1 and one over e2. Rule 10 eliminates an iteration over a single element or scalar. If e1 is a unit type, then e1 can be substituted for occurrences of v in e2. Ed. Note: MF (Oct-18-2000) The rules for eliminating trivial matchexpressions need to be written. They are more complex than those for the old caseexpressions. Rule 11 eliminates an iteration when the result expression is simply the iteration variable v. : We explain our type system in the form commonly used in the programming languages community. The rules for typing expressions are described with an inference rule notation. Originally developed by logicians, this notation is now widely used for describing type systems and semantics of programming languages. For a textbook introduction to type systems, see, for example, [Mitchell]. In inference notation, when all judgements above the line hold, then the judgement below the line holds as well. Here is an example of a rule used later on: Data is the subset of expressions that consists only of scalar content, attribute, element, sequence, and empty sequence expressions. The judgement "|- Data : t" is read as "in the empty environment, the value Data has type t." The symbol |- is called a turnstyle, and is usually preceded by an environment symbol, which represents a mapping from variables to values. In this example, there is no environment symbol, which means the judgement holds in the empty environment. In [5.5 Expressions], we will see examples of rules that have non-empty environments. The rule states that if both Data1 : t1 and Data2 : t2 hold, then (Data1, Data2): (t1, t2) holds as well. For instance, take Data1 = a[1], Data2 = b["two"], t1 = a[Integer], and t2 = b[String]. Then since both a[1] : a[Integer] and b["two"] : b[String] hold, we may conclude that ( a[1], b["two"]) : ( a[Integer], b[String]) holds. The following type rules relate Data values to types. The next rule states that any constant whose lexical form defines a value of type p, then the constant has type p: The next rule states that any constant also has type AnyScalar: The next two rules are for attribute and element construction. The first rule states that if Data has type t, then the attribute expression @Name[Data] has type @Name[t]. The subsequent rule is analogous for element expressions. The next rule is for typing sequences and was already described at the beginning of [5 Type Rules]. The next rule states that the empty sequence value always has the empty sequence type: The rules above associate the most specific type possible with a Data value. The remaining rules in this section associate more general types with a Data value, which are necessary when the type system must determine whether a Data value with most specific type t is permissible when a value of type t' is expected. This occurs during type checking of a query. The next two rules are also for attribute and element construction, but these rules specify more general types. The first rule states that if Data has type t, and Name is in the set of names defined by the wildcard expression Wild, then the given attribute expression also has type @Wild[t]. The subsequent rule is analogous for element expressions. The next rule states that if the value Data has type t1, then it also has type t1| t2. The subsequent rule is analogous and states that the choice operator is associative. The next rule states that the sequence of one value with type t followed by a value with repetition type t{m,n} has repetition type t{m+1,n +1}. The next rule states that the sequence of one value with type t followed by a value with repetition type t{0,n} has repetition type t{0,n +1}. The next rule states that the empty sequence is a repetition of any type with lower bound 0: The symbol <: denotes the subtype relation. We write t1<: t2 if for every data Data such that |- Data : t1, it is also the case that |- Data : t2, i.e., is t1 is a subtype of t2. The subtyping relation is used in many of the type rules that follow. It is easy to see that the subtype relation <: is a partial order, i.e., it is reflexive, t <: t, and it is transitive, if t1<: t2and t2<: t3then t1<: t3. Here are some of the inequalities that hold: Further, if Name <:wild Wild and t <: t', then If t <: t' and m ³ m' and n £ n' then If t1<: t1' and t2<: t2' then We write t1= t2 if t1<:t2 and t2<: t1. Here are some of the equalities that hold: We also have that t1<: t2 if and only if t1| t2= t2. We define the intersection t1 /\ t2 of two types t1 and t2 to be the largest type t that is smaller than both t1 and t2. That is, t = t1 /\ t2 if t <: t1 and t <: t2 and if for any t' such that t' <: t1 and t' <: t2, we have t' <: t. Before giving the remaining type rules, we introduce factoring: Many of the operations in the algebra have an operand that should be of a repetition type. This is true for the built-in operators index, sort and distinct. For example, consider the following. index (children (book0)) ==> pair [ fst [ 1 ], snd [ title [ "Data on the Web" ] ], pair [ fst [ 2 ], snd [ author [ "Abiteboul" ] ] ], pair [ fst [ 3 ], snd [ author [ "Buneman" ] ] ], pair [ fst [ 4 ], snd [ author [ "Suciu" ] ] ], pair [ fst [ 5 ], snd [ year [ 1999 ] ] How should we describe the type of the result? By nesting the children of book0 under snd the original sequence of title, author+, year gets lost. snd can contain either a title, an author, or a year. More formally, we need to find q, m, and n such that children(book0) : q{m, n} and then the type is given by index(children(book0)) : pair [ fst [ String ], snd [q] ]{m, n} In the case of books, the values of q are: title [ String ] | author [ String ] | year [ Integer] the value of m is 3 (because there will be one title, at least one author, and one year element) and the value of n is * (because there may be any number of author elements). We call a type like q a prime type. In general, it may contain scalar, attribute, element, choice, and empty choice types, but it will not contain repetition, sequence, or empty sequence types (except, perhaps, within an element or attribute type). The definition of prime types appears in [Figure 1]. Figure 6: Definition of factoring factor, as shown in [Figure 6], converts any type t to a type of the form q {m, n}, where t <: q {m, n}, so that any value that has type t also has type q {m, n}. For example, We can see here that the factored type is less specific than the unfactored type. For mnemonic convenience we write q {m, n} = factor (t), but one should actually think of the function as returning a triple consisting of a prime type q and two bounds m and n. Just as factoring a number yields a product of prime numbers, factoring a type yields a repetition of prime types. Further, the result yielded by factoring is in some sense optimal. If q {m, n} = factor (t) then t <: q {m, n} and furthermore for any q', m', and n' such that t <: q'{m', n'} we have that q <: q' and m >= m' and n <= n'. Also, if t = t', then factor (t) = factor (t'). In particular, the choice of the lower bound * for factor (Ø) guarantees that factor (t) = factor (t | Ø), since m min * = m. Note that factor is only used by the type inference rules, and thus is not part of the algebra expressions. The type rules make use of an environment that specifies the types of variables and functions. The type environment is denoted by G, and is composed of a comma-separated list of variable types, Var : t or function types, FuncName :(t1 ; ... ; tn) : t. We retrieve type information from the environment by writing (Var : t) Î G to look up a variable, or by writing (FuncName : (t1;...; tn) : t) Î G to look up a function. The type checking starts with an environment that contains all the types declared for functions and global variables. For instance, before typing the first query of [2.2 Projection], the environment contains: G = bib0 : Bib, book0 : Book While doing the type-checking, new variables will be added in the environment. For instance, when typing the query of [2.4 Iteration], variable b will be typed with Book, and added in the environment. This will result in a new environment: G' = G, b : Book We write G |- Exp : t if in environment G the expression Exp has type t. Below are all the rules except those for for and match expressions, which are discussed in later subsections. The next rule states that in any environment G, a constant whose lexical form defines a value of type p has type p. So, for example, G |- 1 : Integer and G |- "two" : String. The next five rules are for typing expressions that define names. The next rule is a trivial definition of the variable Var having type t in environment G: The next two rules are for attribute and element construction with a constant tag name. The first rule states that if Exp has type t, then the attribute expression @Name[Data] has type @Name[t]. The subsequent rule is analogous for element expressions. The next two rules are for attribute and element construction in which the tag name is computed. The first rule states that if Exp1 is in the set of names defined by Wild, and Exp2 has type t, then the given computed attribute expression has type @Wild[t]. The subsequent rule is analogous for element expressions. The following two rules are analogous to the sequence and empty sequence rules in [5.1 Relating data to types]. Note that in the type rule for a conditional expression, the result type is the choice (t2|t3). A let expression extends the current environment G with the variable Var with type t. Note that Exp2, the body of the let expression, is typed in the extended environment, and the type of the entire let expression is t2. The next rule is for function application. In a function application, the type of each actual argument to the function must be a subtype of the corresponding formal argument to the function, i.e., it is not necessary for the actual and formal types to be equal. The next rule states that is always permissible to explicitly type an expression with a type t' that is a supertype of the expression's type t. In programming-language terminology, this operation is sometimes called an ``upcast''. The error expression always has the empty choice type. The attributes, children, and name operators only apply to values with element type. The first two rules require that the content type t is equal to an attribute group followed by an element group. This constraint permits extraction of the appropriate result type. Ed. Note: MF, Oct 23/2000: I'm not sure if using the abstract syntax for types here is fair game. An alternative is defining two type functions attrgroupand elemgroup, which extract the constituent types, but that seemed overkill given that we already specify the constraint on content type in the abstract syntax. The next rule extracts the type of the element's name from the element's type Wild[t]. The complete set of operators are not yet defined, so it is not possible to give the typing rules for operators. In general, however, arithmetic operators will have a type rule such as the following, in which t1 and t2 are numeric types and appropriate conversion exist between the two: Equality and inequality operators are typed similarly. The type rule for index requires that its argument be a factored type. The second expression above the judgement line converts t into a factored type. Similarly, the type rule for sort also requires a factored type. Note that the key expression Exp2 is typed in the extended environment G |- Var : q. Ed. Note: MF, Oct 23/2000: This definition assumes that the equality operator on t is defined. An alternative is requiring Exp2 to have AnyScalar, but that seems too restrictive. The types of aggregated expressions must be factored, and their prime type must be a numeric type. The distinct operator also requires an expression with a factored type, and because distinct removes duplicates, the minimum bound of the result type is the minimum of 1 and the minimum bound of the factored type. The last two rules are for name expressions: they extract the constituent parts of a name. The typing of for expressions is rather subtle. We give an intuitive explanation first and then the detailed typing rules below. A unit type is defined in [Figure 1]; it is either an atomic type, or an attribute or element type with a constant or wildcard name. A for expression for Var in Exp1 do Exp2 is typed as follows. First, one finds the type of expression Exp1. Next, for each unit type in this type one assumes the variable Var has the unit type and one types the body Exp2. Note that this means we may type the body of Exp2 several times, once for each unit type in the type of Exp1. Finally, the types of the body Exp2 are combined, according to how the types were combined in Exp1. That is, if the type of Exp1 is formed with sequencing, then sequencing is used to combine the types of Exp2, and similarly for choice or repetition. For example, consider the following expression, which selects all author elements from a book. for c in children(book0) do match c case a : author[AnyType] do a else () The type of children(book0) is title[String], year[Integer], author[String]{1,*} This is composed of three unit types, and so the body is typed three times. The three result types are then combined in the same way the original unit types were, using sequencing and iteration. (), (), author[String]{1,*} as the type of the iteration, and simplifying yields author[String]{1,*} as the final type. As a second example, consider the following expression, which selects all title and author elements from a book, and renames them. for c in children(book0) do match c case t : title[String] do titl [ t/data() ] case y : year[Integer] do () case a : author[String] do auth [ a/data() ] else error() Again, the type of children(book0) is title[String], year[Integer], author[String]{1,*} This is composed of three unit types, and so the body is typed three times. The three result types are then combined in the same way the original unit types were, using sequencing and iteration. This yields titl[String], (), auth[String]{1,*} as the type of the iteration, and simplifying yields titl[String], auth[String]{1,*} as the final type. Note that the title occurs just once and the author occurs one or more times, as one would expect. As a third example, consider the following expression, which selects all basic parts from a sequence of parts. for p in children(part0/subparts) do match p case b : Basic do b case c : Composite do () else error() The type of children(part0/subparts) is (Basic | Composite){1,*} This is composed of two unit types, and so the body is typed two times. The two result types are then combined in the same way the original unit types were, using sequencing and iteration. This yields (Basic | ()){1,*} as the type of the iteration, and simplifying yields Basic{0,*} as the final type. Note that although the original type involves repetition one or more times, the final result is a repetition zero or more times. This is what one would expect, since if all the parts are composite the final result will be an empty sequence. In this way, we see that for expressions can be combined with match expressions to select and rename elements from a sequence, and that the result is given a sensible type. In order for this approach to typing to be sensible, it is necessary that the unit types can be uniquely identified. However, the type system given here satisfies the following law. a [t1 | t2] = a [t1] | a [t2] This has one unit type on the left, but two distinct unit types on the right, and so might cause trouble. Fortunately, our type system inherits an additional restriction from XML Schema: we insist that the regular expressions can be recognized by a top-down deterministic automaton. In that case, the regular expression must have the form on the left, the form on the right is outlawed because it requires a non-deterministic recognizer. With this additional restriction, there is no problem. The method of translating projection to iteration described in the previous section combined with the typing rules given here yield optimal types for projections, in the following sense. Say that variable x has type t, and the projection x / a has type t'. The type assignment is sound if for every value of type t, the value of x / a has type t'. The type assignment is complete if for every value y of type t' there is a value x of type t such that x / a = y. In symbols, we can see that these conditions are complementary. Any sensible type system must be sound, but it is rare for a type system to be complete. But, remarkably, the type assignment given by the above approach is both sound and complete. The type rule for for expressions uses the following auxiliary judgement. We write G |- for Var : t do Exp : t', if in environment G when the bound variable Var of an iteration has type t then the body Exp of the iteration has type t'. Given the above rules, the type rule for for expressions is immediate. The typing of match expressions is closely related to the typing of for expressions. Due to the typing rules of for expressions, it is possible that the body of an iteration is checked many times. Thus, when a match expression is checked, it is possible that quite a lot is known about the type of the expression being matched, and one can determine that only some of the clauses of the match apply. The definition of match uses the auxiliary judgments to check whether a given clause is applicable. We write G |- case Var : t do Exp : t', if in environment G, the bound variable Var of the case has type t, then the body Exp of case has type t'. Note the type of the body is irrelevant if t = Ø. We write G |- t <: t' else Exp: t'' if in environment G when t <: t' does not hold, then the body Exp of the match expression's else clause has type t''. Note that the type of the body is irrelevant if t < t'. Given the above, it is straightforward to construct the typing rule for a match expression. Recall that we write t /\ t' for the intersection of two types. We write G |- Query if in environment G, the query item Query is well-typed. A type declaration is always well typed: A function declaration is well-typed if in the environment extended with the type assignments for its formal variables, its body is well-typed. A top-level let expression is well-typed if the type of its body, t', is a subtype of the bound variable's type. Finally, a top-level query expression is well-typed if its body is well-typed. We extract the relevant component of a type environment from a query item Query with the function environment (Query). We write |- Query1 ... Queryn if the sequence of query items Query1 ... Queryn is well typed. The XML Query Algebra uses the XML Query Data Model [XQDM00]. Because the XML examples in this document do not use many of the features of the data model, such as attributes, declared namespaces, comments, the algebra uses an abbreviated notation. Here, we give the mapping from the abbreviated algebraic expressions to complete expressions in the XML Query Data Model: s = ref (stringValue (s, ref Def_string, ref [])); i = ref (integerValue(i, ref Def_integer)); a[ kids ] = ref (elemNode (qnameValue (null, a, ref Def_string), {}, {}, kids, (ref Def_t)) ); For example, the string s constructs a string value and the integer i constructs an integer value. The term a[ kids ] constructs an ElemNode with the tag a, an empty set of namespaces, an empty set of attributes, the forest of children nodes kids, and the XML Schema type t, where t is the type of the expression a[ kids ]. Again, to simplify presentation, types do not include attributes, but they can be added easily. Subtyping or containment relationships exist between types. We discuss subtyping in [5 Type Rules]. Ed. Note: MF (Aug-11-2000): This section needs to be completed. The issues in . Ed. Note: PF (Aug-05-2000): For the sake of archival, there are some duplicate issues raised in multiple instances. Duplicate issues are marked as "resolved" with reference to the representative issue. Unless stated explicitly otherwise, [Issue-0001: Attributes] through [Issue-0039: Dereferencing semantics] have been raised in (W3C-members only). Issue-0001: Attributes Date: Jul-26-2000 Description: One example of the need for support of [Issue-0049: Unordered Collections], but also: Attributes need to be constrained to contain white space separated lists of simple types only. Resolution: Attributes are represented by @attribute-name[content]. See [3.4 Types : abstract syntax], [3.5 Types : concrete syntax] for the constraint on white space seperated lists of simple types, and [3.6 Expressions] for selecting and constructing attributes. Issue-0002: Namespaces Date: Jul-26-2000 Resolution: Namespaces are represented by {uri-of-namespace}localname. See [3.1 Expanded names] and [3.2 Wildcards]. Issue-0003: Global Order Date: Jul-26-2000 Description: The data model and algebra do not define a global order on documents. Querying global order is often required in document-oriented queries. See the thread starting at (W3C-members only). Issue-0004: References vs containment Date: Jul-26-2000) As [A The XML Query Data Model] points out, all child-elements are (implicit) references to nodes. (2) Thus, having resolved [Issue-0005: Element identity] this issue is resolved too. Issue-0005: Element identity Date: Jul-26-2000 Description: Another term for "source and join syntax" is "comprehension". See [4.3 Laws] for a discussion of the relationship between iteration by for and comprehension syntax.). Issue-0008: Fixed point operator or recursive functions Date: Jul-26-2000 See for the subproblem of typing "//" or desc() (W3C-members only). Issue-0009: Externally defined functions Date: Jul-26-2000 Description: There is no explicit support for externally defined functions. The set of built-in functions may be extended to support other important operators. See also (W3C-members only). Issue-0010: Construct values by copy Date: Jul-26-2000 Description: Need to be able to construct new types from bits of old types by reference and by copy. Related to [Issue-0005: Element identity]. Resolution: The WG wishes to support both: construction of values by copy, as well as references to original nodes ( (W3C-members only)) See also (W3C-members only). Description: XPath provides as a shorthand syntax [integer] to select child-elements by their position on the sibling axes, whereas the xml-query algebra uses a combination of a built-in function index() and iteration. See (W3C-members only) for a suggestion to to support indexed iteration in the form "for v sub i in e1 do e2", and to express index() as a function (or macro). Issue-0012: GroupBy - needs second order functions? Date: Jul-26-2000 (see also (W3C-members only) and [Issue-0042: GroupBy]):. Description: Collations identify the ordering to be applied for sorting strings. Currently, it is considered to have an (optional parameter) collation "name" as follows: "SORT variable IN exp BY +(expression {ASCENDING|DESCENDING} {COLLATION name}) (see (W3C-members only)). XML Query Algebra that involves string comparison, among them: sort, distinct, "=" and "<". Issue-0014: Polymorphic types Date: Jul-26-2000. See also thread around (W3C-members only). Issue-0015: 3-valued logic to support NULLs Date: Jul-26-2000 Issue-0016: Mixed content Date: Jul-26-2000?) Issue-0017: Unordered content Date: Jul-26-2000 Description: All-groups in XML-Schema, not to be mixed up with [Issue-0049: Unordered Collections] Resolution: The type system has been extended with the support of all-groups - see [3.4 Types : abstract syntax]. Issue-0018: Align algebra types with schema Date: Jul-26-2000 Description: The algebra's internal type system is the type system of XDuce. A potentially significant problem is that the algebra's types may lose information when converted into XML Schema types, for example, when a result is serialized into an XML document and XML Schema. Description: The current type system does not support user defined type hierarchies (by extension or by restriction). Issue-0020: Structural vs. name equivalence Date: Jul-26-2000 Description: The subtyping rules in [5.1 Relating data to types] only define structural subtyping. We need to extend this with support for subtyping via user defined type hierarchies - this is related to [Issue-0019: Support derived types]. Issue-0021: Syntax Date: Jul-26-2000 Description: (e.g. for.<-.in vs for.in.do) Resolution: The WG has voted for several syntax changes (see also (W3C-members only), [3.6 Expressions]: "for v in e do e", "let v = e do", "sort v in e by e ...", "distinct", "match case v:t e ... else e". Issue-0022: Indentation, Whitespaces Date: Jul-26-2000 Description: Is indentation significant? Resolution: The WG has consensus that indentation is not significant (see (W3C-members only)), i.e., all documents are white space normalized. Issue-0023: Catch exceptions and process in algebra? Date: Jul-26-2000 Description: Does the algebra give explicit support for catching exceptions and processing them? Resolution: Subsumed by new issue [Issue-0064: Error code handling in Query Algebra]. Issue-0024: Value for empty forests Date: Jul-26-2000 Description: What does "value" do with empty forests? Resolution: The definition of value(e) has changed to: value(e) = match example in (W3C-members only) would be typed as follows: query for b in b0/book do value(b/year): Integer{0,*} rather than leading to an error. Issue-0025: Treatment of empty results at type level Date: Jul-26-2000 Description: According to (W3C-members only) this is closely related to [Issue-0024: Value for empty forests]. Resolution: Resolved by resolution of [Issue-0025: Treatment of empty results at type level]. Issue-0026: Project - one tag only Date: Jul-26-2000 Description: Project is only parameterized by one tag. How can we translate a0/(b | c)? Resolution: With the new syntax (and type system) a0/(b | c) can be translated to "for v in a0 do match case v1:b[AnyType] do v1 case v2:c[AnyType] do c else ()" - see also [4.1 Relating projection to iteration]. Issue-0027: Case syntax Date: Jul-26-2000 Description: N-ary case can be realized by nested binary cases. For design alternatives of case see: (W3C-members only) Resolution: New (n-ary) case syntax is introduced in [3.6 Expressions]. Issue-0028: Fusion Date: Jul-26-2000 Description: Does the algebra support fusion as introduced by query languages such as LOREL? This is related to [Issue-0005: Element identity], because fusion only makes sense with support of element identity. Issue-0029: Views Date: Jul-26-2000 Description: One of the problems in views: Can we undeclare/hide things in environment? For example, if we support element-identity, can we explicitly discard a parent, and/or children from an element in the result-set? Related to [Issue-0005: Element identity]. See also description in (W3C-members only). Issue-0030: Automatic type coercion Date: Jul-26-2000 Description: What do we do if a value does not have a type or a different type from what is required? See also thread around (W3C-members only). This link also contains a recommendation, which has been agreed as the general direction to go in (W3C-members only):. Issue-0031: Recursive functions Date: Jul-26-2000 Resolution: subsumed by [Issue-0008: Fixed point operator or recursive functions] Issue-0032: Full regular path expressions Date: Jul-26-2000]. Issue-0033: Metadata Queries Date: Jul-26-2000 Description: Metadata queries are queries that require runtime access to type information. See also discussion starting at (W3C-members only). Issue-0034: Fusion Date: Jul-26-2000 Resolution: Identical with [Issue-0028: Fusion] Issue-0035: Exception handling Date: Jul-26-2000 Resolution: Subsumed by [Issue-0023: Catch exceptions and process in algebra?] and [Issue-0064: Error code handling in Query Algebra]. Issue-0036: Global-order based operators Date: Jul-26-2000 Resolution: Subsumed by [Issue-0003: Global Order] Issue-0037: Copy vs identity semantics Date: Jul-26-2000 Resolution: subsumed by [Issue-0005: Element identity] Issue-0038: Copy by reachability Date: Jul-26-2000 Description: Is it possible to copy children as well as IDREFs, Links, etc.? Related to [Issue-0005: Element identity] and [Issue-0008: Fixed point operator or recursive functions] Issue-0039: Dereferencing semantics Date: Jul-26-2000 Resolution: subsumed by [Issue-0005: Element identity] [Issue-0040: Case Syntax] through [Issue-0047: Attributes] are raised in (W3C-members only) Issue-0040: Case Syntax Date: Aug-01-2000. (see (W3C-members only), [2.10 Sorting]). Issue-0042: GroupBy Date: Aug-01-2000 Description: We do not think the algebra needs an explicit grouping operator. Quilt and other high-level languages perform grouping by nested iteration. The algebra can do the same. related to [Issue-0012: GroupBy - needs second order functions?] Resolution: The WG has decided (see (W3C-members only)) to skip groupBy for the time being (see also revised [2.8 Restructuring and grouping] and raise [Issue-0069: Organization of Document] for a possible future revision of this resolution. Issue-0043: Recursive Descent for XPath Date: Aug-01-2000] (see (W3C-members only)). Issue-0044: Keys and IDREF Date: Aug-01-2000 Description: We think the algebra needs some facility for dereferencing keys and IDREFs (exploiting information in the schema.) Resolution: Subsumed by [Issue-0007: References: IDREFS, Keyrefs, Joins] Issue-0045: Global Order Date: Aug-01-2000 Description: We are concerned about absence of support for operators based on global document ordering such as BEFORE and AFTER. Resolution: subsumed by [Issue-0003: Global Order] Issue-0046: FOR Syntax Date: Aug-01-2000 Description: See [Issue-0001: Attributes]. Resolution: subsumed by [Issue-0001: Attributes] [Issue-0048: Explicit Type Declarations] through [Issue-0050: Recursive Descent for XPath] are raised in (W3C-members only) Issue-0048: Explicit Type Declarations Date: Jul-27-2000 (see [3.6 Expressions]). For run-time casts an issue has been raised in [Issue-0062: Open questions for constructing elements by reference]. Issue-0049: Unordered Collections Date: Jul-27-2000 Description: Currently, all forests in the data model are ordered. It may be useful to have unordered forests. The distinct operator,. See also thread around (W3C-members only). Our request to Schema to represent insignificance of ordering at schema level has not been fulfilled - see (W3C-members only). Thus we need to be aware that this information may get lost, when mapping to schema. Issue-0050: Recursive Descent for XPath Date: Jul-27-2000. See [4.1 Relating projection to iteration]. Issue-0052: Axes of XPath Date: Aug-05-2000() (see (W3C-members only)). For the current state of affairs see thread around (W3C-members only). For some use-cases see (W3C-members only). Issue-0053: Global vs. local elements Date: Aug-05-2000 Description: The current type system cannot represent global element-declarations of XML-Schema. All element declarations are local. Issue-0054: Global vs. local complex types Date: Aug-05-2000 Description: The current type system does not distinguish between global and local types as XML-Schema does. All types appear to be fully nested (i.e. local types) Issue-0055: Types with non-wellformed instances Date: Aug-05-2000 Description: The type system and algebra allows for sequences of simple types, which can usually be not represented as a well-formed document. How shall we constrain this? Related to [Issue-0016: Mixed content]. Issue-0056: Operators on Simple Types Date: Jul-15-2000 Description: We intentionally did not define equality or relational operators on element and atomic type. These operators should be defined by consensus. See also first designs for support of arithmetic operators (W3C-members only) and for support of operators for date/time (W3C-members only). Issue-0057: More precise type system; choice in path Date: Aug-07-2000 XML query Description: These issues are taken from the comments on the Requirements Document by I18N ( (W3C-members only)).. Issue-0061: Model for References Date: Aug-16-2000 Description: Raised in: (W3C-members only).]. The following issues have been raised since Sep-25-2000. Issue-0062: Open questions for constructing elements by reference Date: Sep-25-2000 Description: (1) What is the value of parent() when constructing new elements with children refering to original nodes? See also discussion at (W3C-members only). (2) Is an approach to either make copies for all children or provide references to all children, or should we allow for a more flexible combination of copies and references? Issue-0063: Do we need (user defined) higher order functions? Date: Oct-16-2000: As agreed in (W3C-members only) the XML Query Algebra will not support user defined higher order functions. It does support a number of built-in higher order functions. Issue-0064: Error code handling in Query Algebra Date: Oct-04-2000. See also thread starting with (W3C-members only). Description: As discussed in (W3C-members only),: In (W3C-members only) Description: What is the meaning of "=" and "distinct"? Equality of references to nodes or deep equality of data? Issue-0067: Runtime Casts Date: Sep-21-2000 Description: In some contexts it may be desirable to cast values at runtime. Such runtime casts lead to an error if a value cannot be cast to a given type. See also (W3C-members only), where the Algebra team has been put in charge of introducing run-time casts into the Algebra. Resolution: cast e : t has been introduced as a reducible operator expressed in terms of match (see [4.2 Reducible Expressions]). Issue-0068: Document Collections Date: Oct-16-2000: At (W3C-members only) the WG decided to dispose of this issue. The current overall organization of the document is quite adequate, but of course editorial decisions will have to made all the time. Issue-0070: Stable vs. Unstable Sort/Distinct Date: Oct-02-2000 Description: Should sort (and distinct) be stable on ordered collections, i.e. lists, and unstable on unordered collections (see [Issue-0049: Unordered Collections])? For more details see thread around (W3C-members only). Issue-0071: Alignment with the XML Query Datamodel Date: Sep-26-2000 Description: Currently, the XML Query Algebra Datamodel does not model PI's and comments. For more details see thread starting with (W3C-members only). Issue-0072: Facet value access in Query Algebra Date: Oct-04-2000 Description: Each of the date-time data types have facet values as defined by the schema data types draft spec. This problem is general enough to be applied to other atomic. See also thread starting at (W3C-members only). Issue-0073: Facets for simple types and their role for typechecking Date: Oct-16-2000 Description: XML-Schema introduces a number of constraining facets for simple types (among them: length, pattern, enumeration, ...). We need to figure out whether and how to use these constraining facets for type-checking. See also thread starting at (W3C-members only). Issue-0074: Operational semantics for expressions Date: Nov-16-2000 Description: It is necessary to add an operational semantics that formally defines each operator in the Algebra. Issue-0075: Overloading user defined functions Date: Nov-17-2000 Description: User defined functions can not be overloaded in the XML Query Algebra, i.e., a function is exclusively identified by its name, and not by its signature. Should this restriction be relaxed and if so - to which extent? [Issue-0015: 3-valued logic to support NULLs] [Issue-0018: Align algebra types with schema] [Issue-0071: Alignment with the XML Query Datamodel] [Issue-0030: Automatic type coercion] [Issue-0052: Axes of XPath] [Issue-0013: Collations] [Issue-0038: Copy by reachability] [Issue-0068: Document Collections] [Issue-0009: Externally defined functions] [Issue-0073: Facets for simple types and their role for typechecking] [Issue-0072: Facet value access in Query Algebra] [Issue-0008: Fixed point operator or recursive functions] [Issue-0032: Full regular path expressions] [Issue-0028: Fusion] [Issue-0003: Global Order] [Issue-0054: Global vs. local complex types] [Issue-0053: Global vs. local elements] [Issue-0060: Internationalization aspects for strings] [Issue-0033: Metadata Queries] [Issue-0016: Mixed content] [Issue-0061: Model for References] [Issue-0062: Open questions for constructing elements by reference] [Issue-0074: Operational semantics for expressions] [Issue-0056: Operators on Simple Types] [Issue-0075: Overloading user defined functions] [Issue-0014: Polymorphic types] [Issue-0007: References: IDREFS, Keyrefs, Joins] [Issue-0066: Shallow or Deep Equality?] [Issue-0070: Stable vs. Unstable Sort/Distinct] [Issue-0020: Structural vs. name equivalence] [Issue-0019: Support derived types] [Issue-0059: Testing Subtyping] [Issue-0055: Types with non-wellformed instances] [Issue-0049: Unordered Collections] [Issue-0029: Views] [Issue-0011: XPath tumbler syntax instead of index?] [Issue-0001: Attributes] [Issue-0047: Attributes] [Issue-0065: Built-In GroupBy?] [Issue-0027: Case syntax] [Issue-0040: Case Syntax] [Issue-0023: Catch exceptions and process in algebra?] [Issue-0010: Construct values by copy] [Issue-0037: Copy vs identity semantics] [Issue-0039: Dereferencing semantics] [Issue-0063: Do we need (user defined) higher order functions?] [Issue-0058: Downward Navigation only?] [Issue-0005: Element identity] [Issue-0064: Error code handling in Query Algebra] [Issue-0035: Exception handling] [Issue-0048: Explicit Type Declarations] [Issue-0046: FOR Syntax] [Issue-0034: Fusion] [Issue-0045: Global Order] [Issue-0036: Global-order based operators] [Issue-0012: GroupBy - needs second order functions?] [Issue-0042: GroupBy] [Issue-0022: Indentation, Whitespaces] [Issue-0044: Keys and IDREF] [Issue-0057: More precise type system; choice in path] [Issue-0002: Namespaces] [Issue-0069: Organization of Document] [Issue-0026: Project - one tag only] [Issue-0051: Project redundant?] [Issue-0043: Recursive Descent for XPath] [Issue-0050: Recursive Descent for XPath] [Issue-0031: Recursive functions] [Issue-0004: References vs containment] [Issue-0067: Runtime Casts] [Issue-0041: Sorting] [Issue-0006: Source and join syntax instead of "for"] [Issue-0021: Syntax] [Issue-0025: Treatment of empty results at type level] [Issue-0017: Unordered content] [Issue-0024: Value for empty forests]
http://www.w3.org/TR/2000/WD-query-algebra-20001204/
crawl-002
refinedweb
12,549
60.24
3D Volume Plots in Python How to make 3D Volume volume plot with go.Volume shows several partially transparent isosurfaces for volume rendering. The API of go.Volume is close to the one of go.Isosurface. However, whereas isosurface plots show all surfaces with the same opacity, tweaking the opacityscale parameter of go.Volume results in a depth effect and better volume rendering. Simple volume plot with go.Volume¶ In the three examples below, note that the default colormap is different whether isomin and isomax have the same sign or not. import plotly.graph_objects as go import numpy as np X, Y, Z = np.mgrid[-8:8:40j, -8:8:40j, -8:8:40j] values = np.sin(X*Y*Z) / (X*Y*Z) fig = go.Figure(data=go.Volume( x=X.flatten(), y=Y.flatten(), z=Z.flatten(), value=values.flatten(), isomin=0.1, isomax=0.8, opacity=0.1, # needs to be small to see through all surfaces surface_count=17, # needs to be a large number for good volume rendering )) fig.show()
https://plotly.com/python/3d-volume-plots/
CC-MAIN-2020-34
refinedweb
173
60.21
Hello readers, in this episode we’re going to talk about languages structures, as a preface to future post where I will show you all this stuff in action, with OOP and concurrency examples and reviewing some toolkits and frameworks. Of course, this is not an exception, on each topic of this post I will show you an example of how it can be used and a comparison with languages to make it easy to understand for those whom come from PHP, C, Java, etc.. Following there’s some examples that shows each variation with its equivalent in PHP: var counter int = 0 for counter < 100 { counter += 1 } <?php while($counter < 100){ $counter++; } import "fmt" for key, value := range list { fmt.Printf("%d => %s\n",key, value) } <?php foreach($list as $key=>$value){ echo "{$key} => {$value}\n"; } for i := 0; i < 10; i++ { fmt.Println("The value of i : ", i) } The if statement in Go, like For statement, does not need to be surrounded by ( ), but the braces { } are required. Like for, the if statement can start with a short statement to execute before the condition. Variables declared by the statement are only in scope until the end of the if. As many other languages, it support the else statement. if value, ok := m[key]; ok { fmt.Println("value is:", value) } if( isset($_POST['id'])) { $id = $_POST['id']; } if _string == "my example" { fmt.Println("this is ",$string) } else { fmt.Println("this is no my string") } <?php if($_string == "my example"){ echo "this is ".$string; } else { echo "this is no my string"; } This is a multiple choice statement that allows us to select between more than two options, and most of the time faster than if-else. The differences against other languages is that each case body breaks automatically, unless it ends with a fallthrough statement, and Switch without a condition is the same as switch true. This construct can be a clean way to write long if-then-else chains. switch i { case 0 : fmt.Println("Zero") case 1 : fmt.Println("One") case 2 : fmt.Println("Two") case 3 : fmt.Println("Three") case 4 : fmt.Println("Four") case 5 : fmt.Println("Five") case 6 : fmt.Println("Six") case 7 : fmt.Println("Seven") case 8 : fmt.Println("Eight") case 9 : fmt.Println("Nine") default : fmt.Println("Unknown Number") } <?php switch $i { case 0 : echo "Zero"; break; case 1 : echo "One"; break; case 2 : echo "Two"; break; case 3 : echo "Three"; break; case 4 : echo "Four"; break; case 5 : echo "Five"; break; case 6 : echo "Six"; break; case 7 : echo "Seven"; break; case 8 : echo "Eight"; break; case 9 : echo "Nine"; break; default : echo "Unknown Number"; } Functions are defined using the keyword func followed by the function name, arguments and the return values. func say_hello() { fmt.Println("Hello From the function") } Functions may have a return value. This value can also be named. func Add(first, second int) (result int){ return first + second } <?php function add($first, $second) { return ($first + $second); } This is one of Go goodies that does not has equivalence in other common languages like PHP or C. In Go we can return multiple values of different types, also naming each returned parameter. Let me show an example: func divide(n,d int) (result float, err error) { if d == 0 { err = errors.New("") } else { result = n / d } return result, err } Functions can take 0 to undefined variables of a particular data type. func sum(args ...int) (total int) { total := 0 for _, i := range args { total = total + i } return total } Go supports anonymous functions, which can form closures. Anonymous functions are useful when you want to define a function inline without having to name it. func Sequence() func() int { i := 0 return func() int { i += 1 return i } } nextValue := Sequence() fmt.Println(nextValue()) // 1 fmt.Println(nextValue()) // 2 fmt.Println(nextValue()) // 3 fmt.Println(nextValue()) // 4 Do not miss the second part of this post where we will use this concepts while discuss OOP and concurrency. Lets talk!
https://www.arroyolabs.com/2016/08/go-basics-control-structures/
CC-MAIN-2019-30
refinedweb
668
74.79
We've seen how inefficient it can be to use a constructor to assign methods to the objects it initializes. When we do this, each and every object created by the constructor has identical copies of the same method properties. There is a much more efficient way to specify methods, constants, and other properties that are shared by all objects in a class. JavaScript objects "inherit" properties from a prototype object.[1] Every object has a prototype; all of the properties of the prototype object appear to be properties of any objects for which it is a prototype. That is, each object inherits properties from its prototype. [1] Prototypes were introduced in JavaScript 1.1; they are not supported in the now obsolete JavaScript 1.0. The prototype of an object is defined by the constructor function that was used to create and initialize the object. All functions in JavaScript have a prototype property that refers to an object. This prototype object is initially empty, but any properties you define in it will be inherited by all objects created by the constructor. A constructor defines a class of objects and initializes properties, such as width and height, that are the state variables for the class. The prototype object is associated with the constructor, so each member of the class inherits exactly the same set of properties from the prototype. This means that the prototype object is an ideal place for methods and other constant properties. Note that inheritance occurs automatically, as part of the process of looking up a property value. Properties are not copied from the prototype object into new objects; they merely appear as if they were properties of those objects. This has two important implications. First, the use of prototype objects can dramatically decrease the amount of memory required by each object, since the object can inherit many of its properties. The second implication is that an object inherits properties even if they are added to its prototype after the object is created. Each class has one prototype object, with one set of properties. But there are potentially many instances of a class, each of which inherits those prototype properties. Because one prototype property can be inherited by many objects, JavaScript must enforce a fundamental asymmetry between reading and writing property values. When you read property p of an object o, JavaScript first checks to see if o has a property named p. If it does not, it next checks to see if the prototype object of o has a property named p. This is what makes prototype-based inheritance work. When you write the value of a property, on the other hand, JavaScript does not use the prototype object. To see why, consider what would happen if it did: suppose you try to set the value of the property o.p when the object o does not have a property named p. Further suppose that JavaScript goes ahead and looks up the property p in the prototype object of o and allows you to set the property of the prototype. Now you have changed the value of p for a whole class of objects -- not at all what you intended. Therefore, property inheritance occurs only when you read property values, not when you write them. If you set the property p in an object o that inherits that property from its prototype, what happens is that you create a new property p directly in o. Now that o has its own property named p, it no longer inherits the value of p from its prototype. When you read the value of p, JavaScript first looks at the properties of o. Since it finds p defined in o, it doesn't need to search the prototype object and never finds the value of p defined there. We sometimes say that the property p in o "shadows" or "hides" the property p in the prototype object. Prototype inheritance can be a confusing topic. Figure 8-1 illustrates the concepts we've discussed here. Because prototype properties are shared by all objects of a class, it generally makes sense to use them only to define properties that are the same for all objects within the class. This makes prototypes ideal for defining methods. Other properties with constant values (such as mathematical constants) are also suitable for definition with prototype properties. If your class defines a property with a very commonly used default value, you might define this property and its default value in a prototype object. Then, the few objects that want to deviate from the default value can create their own private, unshared copies of the property and define their own nondefault values. Let's move from an abstract discussion of prototype inheritance to a concrete example. Suppose we define a Circle( ) constructor function to create objects that represent circles. The prototype object for this class is Circle.prototype,[2] so we can define a constant available to all Circle objects like this: [2] The prototype object of a constructor is created automatically by JavaScript. In most versions of JavaScript, every function is automatically given an empty prototype object, just in case it is used as a constructor. In JavaScript 1.1, however, the prototype object is not created until the function is used as a constructor for the first time. This means that if you require compatibility with JavaScript 1.1, you should create at least one object of a class before you use the prototype object to assign methods and constants to objects of that class. So, if we have defined a Circle( ) constructor but have not yet used it to create any Circle objects, we'd define the constant property pi like this: //First create and discard a dummy object; forces prototype object creation. new Circle ( ); //Now we can set properties in the prototype. Circle.prototype.pi = 3.14159' Circle.prototype.pi = 3.14159; Example 8-4 shows our Circle example fully fleshed out. The code defines a Circle class by first defining a Circle( ) constructor to initialize each individual object and then setting properties of Circle.prototype to define methods and constants. // This forces the prototype object to be created in JavaScript 1.1. new Circle(0,0,0); // Define a constant: a property that will be shared by // all circle objects. Actually, we could just use Math.PI, // but we do it this way for the sake of instruction. Circle.prototype.pi = 3.14159; // Define a method to compute the circumference of the circle. // First declare a function, then assign it to a prototype property. // Note the use of the constant defined above. function Circle_circumference( ) { return 2 * this.pi * this.r; } Circle.prototype.circumference = Circle_circumference; // Define another method. This time we use a function literal to define // the function and assign it to a prototype property all in one step. Circle.prototype.area = function( ) { return this.pi * this.r * this.r; } // The Circle class is defined. // Now we can create an instance and invoke its methods. var c = new Circle(0.0, 0.0, 1.0); var a = c.area( ); var p = c.circumference( ); It is not only user-defined classes that have prototype objects. Built-in classes, such as String and Date, have prototype objects too, and you can assign values to them.[3] For example, the following code defines a new method that is available for all String objects: [3] In JavaScript 1.1 and later. // Returns true if the last character is c String.prototype.endsWith = function(c) { return (c == this.charAt(this.length-1)) } Having defined the new endsWith( ) method in the String prototype object, we can use it like this: var message = "hello world"; message.endsWith('h') // Returns false message.endsWith('d') // Returns true
http://books.gigatux.nl/mirror/javascript/jscript4-CHP-8-SECT-4.html
CC-MAIN-2019-13
refinedweb
1,296
56.15
Scenario: I want to move a users mailbox using a cross Site / Administrative Group move in Exchange 2003. This user also has Enterprise Vault and data archived in a Vault Store. The new site has it's own Vault Store and therefore I need to move the users archived data using the EV Export to PST process then import into the new store. So far so good.... in theory. My problem is that if I choose to restore shortcuts during the import stage I get duplicates for each shortcut which will confuse the user .... or I choose not to create new short cuts and the old ones are pointing to the old store (to which we now have no access) and therefore don't work. ExMerge doesn't have an option to use the Message Class field, EVPM cannot do this for me (I don't believe), and We have no access to users data to do this from within the mailbox after the export process has taken place. Help .... How on earth do I remove the shortcuts ( shown as a Message Class field in the Mailbox). If I can do this it means that I can choose to the option to create new shortcuts during the import and they will work and I will have no legacy shortcuts remaining. Has anyone else had this problem and found an asnwer to it ! Many thanks L.
http://fixunix.com/veritas/479625-moving-vault-stores-shortcuts-print.html
CC-MAIN-2014-15
refinedweb
235
75.54
When I was creating web applications I was loving using JSON-RPC. When I started learning and using Next.js I wanted to find JSON-RPC library for next. But I've found something even better. What is RPC RPC stands for Remote Procedure Call. Basically it's abstracting the boundary of client server architecture of Web applications. You have a function on the server like echo and you call it from the client (like a browser). The library for RPC just do all the packing and unpacking of the requests and you can think like you just have no server and HTTP protocol between at all. So it simplify a way of thinking about application. Because the best way of simplifying a complex application is to not have to thinking about stuff that are not important at a given moment. This is the whole purpose of abstraction, you name a thing and you can forget what it's inside and have your mind think about order things. What is JSON-RPC JSON-RPC is RPC protocol that just sends JSON payload to the server and server unpack the JSON call the method, pack the response in JSON and send it back to the client where client unpack it and get results. Example: - You call function echo("hello, world!") - method call is saved as {"method": "echo", "params": ["hello, world!"} - JSON is send to the server - server call method echo("hello, world!") - The result is saved as {"result": "hello, world!"} - JSON is send back to the client - client return Promise of "hello, world!" NOTE: some properties of JSON-RPC was left out for simplification, you can read how exactly JSON-RPC works in its specification or on Wikipedia. So basically you can just think about this like you call server function, call it from browser and get result as promise. You can forget that you even have a server. JSON-RPC is even even simpler after introducing Promises and async..await into JavaScript, because the JS function on the Front-End can just be async. With Node.js and JavaScript in browser you can have: // client await echo("hello, world!"); // server async function echo(str) { return str; } The rest is magically converted to JSON and sent between browser and server but when you write code you can think about browser and server as one entity. Here is simple example but the function can be more complex like reading or writing data into a database. For me RPC architecture is way superior than REST or GraphQL and it's way underrated. RCP with Next.js When I was searching for JSON-RPC implementation for Node and Next. I've found this little gem, library next-rpc. Using next-rpc is very simple: First you install the library: npm install -S next-rpc Then you need to configure next to use RPC: // ./next.config.js const withRpc = require('next-rpc')(); module.exports = withRpc({ // your next.js config goes here }); Then you define your remote functions/procedures: // /pages/rpc/index.js // this enable RPC mechanism // if this is not included the route will work normally export const config = { rpc: true }; // this is remote procedure that you can import and call export async function getUsers() { return db.query(`SELECT users FROM users`); } Then you can use this method in any component: // /components/users.jsx import { useState, useEffect } from 'react'; import rpc from '../pages/rpc/index.js' const Users = () => { const [users, setUsers] = useState([]); useEffect(() => { getUsers().then(setUsers); }, []); return ( <ul>{ users.map(user => { return <li>{ user.name }</li>; }) }</ul> ); }; And that's it, you can also use next-rpc with reactQuery or swr. Even that this RPC mechanism abstract the usage of the server and HTTP, this library still give you an access to request object, so you for instance can create login and get HTTP headers if you want. But you probably will not do that a lot of times and need it only for special cases. Conclusion IMHO any RPC mechanism is way better, than any other server/client approach, when you're developer that work on both Back and Front of the application, the boundary of server/client is blurred completely. And this is how you typically work with Next.js. You can think about the application as one entity (even more than with pure Next.js) and you can forget about not important things like HTTP requests. But still you can think about it when needed, just like with any abstraction, like a function. Most of the time you can use just the name of the function, but sometimes you need to look inside, and this is what next-rpc library gives you and your Next.js application. If you like this post, you can follow me on twitter at @jcubic and check my home page. Here you can find some NextJS jobs. Top comments (0)
https://dev.to/jcubic/rpc-in-next-js-5bd7
CC-MAIN-2022-40
refinedweb
813
64.91
A recently announced free course on Code School is about making web sites with the MVC pattern and C# ASP.NET. Given the current trend for MVC these days, this course presents a good opportunity for experiencing it from a .NET perspective. Despite being a lightweight introduction, just three levels deep, and with just two goals to complete, Try .NET MVC manages to meet its goal of providing a quick and easy to follow guide to the Microsoft way of doing MVC. These three levels comprise of a mix of videos that feature instructor Eric Fisher, who talks you through the concepts, and assisted exercises to be carried out inside Code School's browser based IDE. There are just two goals to complete: add Names to a list and then display those Names. As with all Code School's courses there absolutely has to be a theme that surrounds the presentation. In this case it is a medieval story, complete with Knights, Dragons and Castles, that somehow manages to blend in MVC and C# in the theme's song context! Crazy stuff that you either love or hate, me belonging to the latter category because it gives me a sense of not being serious enough. But, as always, the professionalism exhibited by Code School's instructors, as well as the level of detail that is put into the production, prove me wrong every time. So don't let the goofy themeology fool you too, but just focus on the material instead. The three levels are organized as: Level 1 Model View Controller Introduction to MVC - Creating a View - Creating a Controller Routing - Default Route - Standard Route - Route Less Travelled Models - Creating a Model Level 2 Getting User Input Input - Create Our Create Action - Set Up Our Input Form Level 3 Retaining Data - Set Our View To Use lists - Create Our Global Variable - Set Up Our Model - Wiring Up Our Controller Knowledge of C# is not presumed, since the reader is presented with parts of the language, like importing namespaces with the "using" directive, that an experienced C# programmer ought to be familiar with, therefore making it clear that the course targets inexperienced developers in either C# or ASP.NET. The exercises or Challenges, are assisted in that you're given precise, coupled with hints, directions on what you should do, such as: "Create a public Create action that returns an IActionResult and accepts a string EquipmentName. Then, inside of that new action, return an empty View()" The code is partially pre-written, and just requires filling the blanks in order for the exercise to become completed. Following the instructions to the letter should not pose any difficulties, but there are two issues that I've encountered when trying out the challenges. First the IDE had no auto-completion, a no-no when having to write code in a statically typed language like C# and secondly, I've encountered a subtle bug in Level 3's Challenge no 2 which requires to "Set Our View To Use lists" In that challenge you have to tweak the code from : @model CharacterSheetApp.Models.Equipment <h2>Equipment:</h2> <form asp- <div> <input name="EquipmentName" /> <input type="submit" value="Add Equipment" /> </div> </form> <h4>Equipment:</h4> <div> <ul> <li> <label>@Model.Name</label> </li> </ul> </div> to accommodate a List and then iterate through it printing its contents: @model List<CharacterSheetApp.Models.Equipment> <h2>Equipment:</h2> <form asp- <div class="form-group"> <input name="EquipmentName" class="form-control" /> <input class="btn" type="submit" value="Add Equipment" /> </div> </form> <h4>Equipment:</h4> <div> <ul> @foreach (var x in Model) { <li> <label>@x.Name</label> </li> } </ul> </div> The problem is that despite the code being correct, it wouldn't compile emitting the same "So close. We have our foreach loop but the item in our list is not correct" error every time. I submitted the issue to the class's forum to get further guidance. Within a couple of hours, the instructor himself, Eric, replied that it was definitely a bug and that the Code School devs were made aware of it. Only a little while later, the issue was fixed so I could continue with the rest of the exercises (although the platform is giving you the option to skip problematic challenges and continue anyway). So hats off to Code School for its almost real time support, an aspect all too important especially when undertaking paid classes. As far as the content itself goes, it is structured around the typical MVC workflow. Thus, Level 1 is shows how the MVC components are organized into files and folders as well as how they're associated and resolved at runtime. Then it goes through creating Views, the Controller and its links to the Model. Level 1 used hardcoded values to keep matters simple, but what we are really after is a form which allows users to enter their own data. That's a matter for Level 2. Level 3 completes the class by showing how to feed the user supplied data to the Controller which subsequently will persist it (no database) to a global singleton generic List. After that it's just a matter of displaying that data back to the users through an outputting HTML View. There you have it, a nice, simple and free introduction to MVC from .NET's perspective.
http://126kr.com/article/9c27c1tjptd
CC-MAIN-2017-22
refinedweb
896
53.95
Avoiding uses the ‘$’ for its wrapper function. To avoid this conflict I used a popular design pattern, that passes a self executing anonymous function to the jQuery namespace with the jQuery object. This fixed the errors. Definitely goning to add this to all my jQuery code from now on :). I recommend checking out How Good C# Habits can Encourage Bad JavaScript Habits: Part 1, the whole series is fantastic and teached me quite a few things that I’ll take with me. Björn Olsson says:Post Author October 26, 2010 at 11:32 I prefer using jQuery.noConflict() myself, it also allows you to use multiple versions of jQuery on the same page. Elijah Manor says:Post Author October 27, 2010 at 05:56 Glad you enjoyed the C#/JavaScript series on Enterprise jQuery Thanks!
http://www.frederikvig.com/2010/10/avoiding-conflicts-when-using-jquery-and-episerver-composer/
CC-MAIN-2017-30
refinedweb
135
72.16
import the step file(assembly) and display Submitted by WuXuan on 4 September, 2012 - 06:29 Forums: i want to import the step file(assembly) to opencascade and display all parts of the assembly. i use the samples(import export) of the occ,but when i import an assembly,it become a part. can anyone help me? Dear WuXuan, Can u share the test Step file .. I do not have a STEP file of an assembly. - PG sure,can you give me your mailbox,i will send to you pgocct@gmail.com i have post the email to you, have you received? yes recvd , but the dimensions are small. What units have u used? yeah,because the that are electronic components,so the dimensions are small Able to load the STEP file using instructions of Alexander. can you give me the source code? try Draw and the DATA EXCHANGE COMMANDS ("Test Harness User's Guide", thug.pdf) pload ALL [int deep {0|1}] [ … ] ReadStep Xdump XShow i am sorry , i cant understand. can you give me an example? i think it is more useful to me Draw commands: ------------ pload ALL # pload ALL load all plugins ReadStep D thefile.stp # ReadStep read the STEP-File in the document D XGetOneShape aShape D # XGetOneShape make one Shape of the whole document vinit #init the viewer vdisplay aShape # display the shape vfit ------------ Select the view window and press 5 (to select shells, enter "vhelp" to see help and filter options). If you move the cursor over a shell (normaly an assembly) it will be highlighted. If you want to display only one assembly you can use the following Draw commands: ------------ Xdump D # Xdump display the assembly structure on the Command line window # use one of the labels for XGetShape XGetShape aShape2 D 0:1:1:3 vdisplay aShape2 ------------ for more commands look at "8.7 XDE general commands" of the thug.pdf Or try if you only want to view the STEP-File. thnx,but how can i see the source code? i want to use this function in MFC
https://www.opencascade.com/content/import-step-file%EF%BC%88assembly-and-display
CC-MAIN-2017-09
refinedweb
347
73.47
UnPoetia talk:Shall I Compare Thee From Uncyclopedia, the content-free encyclopedia Perhaps we should have a separte poetry namespace...In addition, I believe this acticle should have a different title, perhaps. No one is going to search for "Shall I Compare Thee" or even link to it. Rad 13:32, 6 December 2006 (UTC) - It could probably be moved to sonnet, or have sonnet redirect here instead of poetry. • Spang • ☃ • talk • 15:59, 6 Dec 2006 This one's good too! --Anyone 17:16, 8 December 2006 (UTC) Thank you, all. Move or retitle them in whatever way makes the most sense. I started these with a Poetry bookshelf at UnBooks because it seemed a good place to start. A fake namespace is also a possibility if most are agreeable to it. --User:The Bard/sig 18:19, 8 December 2006 (UTC)
http://uncyclopedia.wikia.com/wiki/UnPoetia_talk:Shall_I_Compare_Thee
CC-MAIN-2016-50
refinedweb
143
66.44
- NAME - SYNOPSIS - DESCRIPTION - RESOURCES & LINKS - SEE ALSO - CAVEATS - AUTHORS NAME CPAN::Testers - QA of CPAN distributions via cross-platform testing SYNOPSIS With the explosive growth and increased interest in the CPAN Testers over the first 5 years, it was felt useful to create this namespace placeholder to house the re-architected next-generation CPAN Testers stack. This namespace also provides for the consolidation of related work under one unified and easily identifiable umbrella. Co-maintainer permissions in this namespace are freely granted to anyone working on any area of the CPAN Testers infrastructure. DESCRIPTION] | | [] [] This a rather simplistic view, but covers the basic flow of test reports into the system, and how the 'cpanstats' database and the core websites are derived. Smoke Clients There are additional smokebot applications that sit beyond the CPAN-Reporter, CPANPLUS-YACSmoke and cpanm-report smoker clients, though all use the APIs provided by these hooks into the three primary distribution installers, CPAN, CPANPLUS and cpanminus. Previously there were standalone scripts, such as 'cpantest' included with CPANPLUS prior to v0.50, which used dedicated test capture code, specifically for the purpose of CPAN Testers. As of CPANPLUS-0.50, this code was removed. In its place a new distribution, CPAN-YACSmoke, was released incorporating new test capture code utilising the new CPANPLUS API. In 2006 CPAN::Reporter was released, providing smoke testing support for CPAN.pm. In 2008, with little work being done to bring CPAN-YACSmoke up to date with the current CPANPLUS API, CPANPLUS-YACSmoke was released, building on the work of CPAN-YACSmoke. In 2010 a new minmal installer was released. In 2013 a parser, cpanm-reporter, was released that took the output logs from cpanminus and adapted them into test reports that could be submitted to the Metabase. All three installers had their own dedicated smoker clients. The primary client interfaces for CPAN Testers smoke testing are CPAN-Reporter and CPANPLUS-YACSmoke, though cpanminus-reporter is still young. In order to submit reports, the clients need to supply test results in a consistent form, so that the data store can parse them and store the relevant parts as necessary. The means to provide a consistent API and transport are provided by Test-Reporter, which includes the transport methods to submit to the appropriate data stores. CPAN Testers 1.0 CPAN Testers report submissions began on a mailing list. In the early days reports were crafted by hand and sent via a mail client. With the design of CPANPLUS, an automated tool was written to provide test reports that could then be edited before sending. The transport mechanism was SMTP, as provided by Test-Reporter. For many years this was adequate, with the SMTP transport layer sending reports to the cpan-testers mailing list. The perl.org server which received the mails, then provided a read only NNTP service to view the test reports. In 2008 the number of testers was increasing, and the submission of reports were increasing beyond initial expectations, with over 450,000 reports submitted in November 2009. The storage mechanism provided by NNTP on the perl.org servers, had long reached its limit and was no longer scaling with the level of reports being submitted. It was time for a change. CPAN Testers 2.0 In 2008 the idea for an alternative storage mechanism for CPAN Testers reports was mooted at the Olso QA Hackathon. Out of that came an idea now known as the Metabase. It was the germ of the plan to move CPAN Testers to a HTTP report submission system. At the Birmingham QA Hackathon in 2009, work on the Metabase and a HTTP gateway continued. In December 2009, the perl.org admins gave a deadline of 1st March 2010 to switch off SMTP submissions. Test-Reporter, now provides a delivery mechanism for sending the test report data via a HTTP request, using Test::Reporter::Transport::Metabase, into the Metabase. The Metabase is now the CPAN Testers 2.0 centralised data store. The Metabase currently sits on an Amazon S3 server, and can cope with many more times the level of throughput than was previously seen with the SMTP delivery mechanism. As over 1st September 2010, the old SMTP gateway to the old cpan-testers mailing list was closed. The 'cpanstats' Database The original 'cpantest' Database began life with a parser reading the NNTP feed once a day and storing metadata in an SQLite database, freely available for all to use. In 2007 the CPAN Testers Statistics websites extended the parser and created the 'cpanstats' database, which contain more information necessary to drive the statistical analysis. Also initially a SQLite database. With the overhaul of the CPAN Testers websites in 2008, the 'cpanstats' database became the master database. While the SQLite database was still updated and provided for use by all, the master database was ported into a MySQL database, with tables for uploads and further statistical analysis being added. The MySQL 'cpanstats' database now provides the following SQLite databases: uploads.db release.db The old cpanstats.db SQLite database has now been retired, due to errors creating the data with SQLite. The Websites Prior to 2002 the CPAN Testers reports were available in their raw form via the NNTP server. In 2002 a new site grouped together the list of reports for each distribution uploaded to CPAN and each CPAN author. In 2007 the CPAN Testers Statistics site was launched to provide analysis of data regarding reports and to highlight trends in testing. In 2008, the CPAN Testers websites started receiving an overhaul, with a complete facelift being unveiled in May 2009. The two primary websites, the Reports and Statistics websites are now complimented by the Wiki, Blog, Development, Metabase, Dependencies, Matrix and Analysis websites, with the 'cpanstats' database being used by many other sites for their own data analysis. In 2010 with the launch of CT2.0 the NNTP feed was deprecated. All reports are now held on the cpantesters server, and can be viewed using their id or guid in styled or raw formats. Since 2010, various APIs have been released to enable anyone to get at the underlying data and reports to present, analyse and store reports as they wish. In 2014 the CPAN Testers Admin site was released, to provide authors and testers with a means to 'cancel' reports, where the smoker was submitting incorrect reports, and also for testers to claim the email addresses they have and are using. The latter then feeds into the Leaderboard. Improvements to the CPAN Testers architecture are always in progress. For more information on the CPAN Testers please visit the links below: RESOURCES & LINKS Websites CPAN Testers Reports CPAN Testers Statistics The CPAN Testers Wiki The CPAN Testers Analysis Site The CPAN Testers Matrix The CPAN Testers Dependencies Site The CPAN Testers Blog The CPAN Testers Development Site The CPAN Testers Metabase Site The CPAN Testers Admin Site Mailing Lists The cpan-testers-discuss mailing list. The cpan-uploads mailing list (read only). Presentations The Future of CPAN Testers. A short talk about some of planned projects for CPAN Testers. Presented at LPW 2013. The Eco-System of CPAN Testers by Barbie. An explanation of the software components, databases and process that keep CPAN Testers working. Presented at YAPC::Europe 2012. Smoking The Onion - Tales of CPAN Testers by Barbie. Hints and tips for CPAN authors and users alike. Presented at YAPC::Europe 2011. An introduction to CPAN Testers 2.0 & The Metabase by Barbie. Presented at YAPC::Europe 2010. =item * Full & Lightning Talk for the Statistics of CPAN talks by Barbie. Presented at technical events throughout 2009, including YAPC::NA 2009 and YAPC::Europe 2009. A presentation entitled "How to be a CPAN Tester" by Barbie. An update on the talk by Barbie and David Golden in 2008. Presented at YAPC::NA 2008 A presentation entitled "How to be a CPAN Tester" created by Barbie and David Golden. Presented at YAPC::NA 2007 Articles A short tutorial entitled "Become a CPAN Tester with CPAN::Reporter" created by David Golden An article entitled "Becoming a CPAN Tester with CPANPLUS" created by Audrey Tang SEE ALSO CAVEATS This is the fifth draft of this document. Undoubtedly, there may be various bits that need some adjustments. Feedback is most welcome. AUTHORS Adam J. Foxson <afoxson@pobox.com>, having been involved with the CPAN Testers for over half a decade, is the principal author of Test::Reporter. Barbie, <barbie@cpan.org> for Miss Barbell Productions <>. David Golden Copyright (C) 2007-2010 Adam J. Foxson and the CPAN Testers Copyright (C) 2010-2015 CPAN Testers This distribution is free software; you can redistribute it and/or modify it under the Artistic License v2.
https://metacpan.org/pod/CPAN::Testers
CC-MAIN-2019-47
refinedweb
1,455
63.9
Introduction to NumPy nonzero A non-zero Function from the numpy module in python is used to find the indices of non-zero elements in a numpy array. The numpy.nonzero() function returns a tuple of arrays with indices of all the non-zero elements in the array. For the uninitiated, a numpy array is like a matrix of elements. In this article, we will look at the syntax of numpy.nonzero() function and then discuss a few examples based on it. To begin with, let’s first try to understand some of the possible uses of this function. Uses of numpy.nonzero() function - The popular usage of the numpy nonzero function is to find the indices of elements of the array that satisfy a certain logical condition. For example, finding the indices of elements in the array which is greater or less than 1, even, etc. - Another popular usage of this function is to find non-zero submatrices within a numpy matrix. For example, you have a large matrix with zeros and a few non-zero elements, and you wish to extract the non-zero sections of the matrix. Don’t worry, even if you don’t understand much now. We will discuss this further in the examples section. But before we begin with examples, let’s discuss the syntax and arguments of this function. Syntax and Parameters The basic syntax for numpy.nonzero() function is as follows : numpy.nonzero(a) Argument: The function takes an array-like instance as an input Return: It returns a tuple with indices of non-zero elements in the input array Having discussed the syntax, let’s discuss a few examples based on it. Examples of NumPy nonzero Given below are the examples of NumPy nonzero: Example #1 Find the indices of nonzero elements in the given input array. Code: #import numpy module import numpy as np #input a = np.array([[0,1],[5,3]]) print('input array :\n',a) #indices of non-zero elements np.nonzero(a) Output: In the above output, you will observe that the np.nonzero function returns a tuple that contains indices for each nonzero element in the array. In this particular example, indices [0,1], [1,0], [1,1]. The first value of the tuple corresponds to the first index of the nonzero elements, i.e. (0,1,1), and the second value in the tuple corresponds to the second index of each non-zero element, i.e. (1,0,1). You may consider it as a transpose of the indices. Example #2 Find the elements that are less than 5 from the given input array. Code: #input a = np.array([[2,8,0],[3,9,1],[1,2,3]]) print("input :\n",a) #nonzero function with condition print('indices of non-zero elements:\n',np.nonzero(a #returning elements less than 5 print('elements less than 5:\n', a[np.nonzero(a Output: In this example, we have used a condition along with the np.nonzero function. The function returns the indices of all the elements in the array that meet the specified condition. Here, 1 is considered as True and 0 as False. For example, elements (2,0,3,1,1,2,3) satisfy the condition. Their respective indices are [0,0], [0,2], [1,0], [1,2], [2,0], [2,1] and [2,2]. Example #3 Find the elements that are more than 5 but less than 15 from the given input array. Code: #input a = np.array([[10, 20], [13, 11], [4, 15]]) print('input array :\n',a) #nonzero function with combinatorial logic print('elements in between 5 and 15:\n',a[np.nonzero((a > 5) & (a Output: This example is similar to the previous one, with just the exception that here we have used a combination of conditions. So, for example, you can use complex conditions joined together by logical operators like ‘&’(and) and ‘|’(or). Example #4 Spot and extract the smallest submatrix with nonzero values from the given input matrix. Code: #function using np.nonzero() def nonzero_submat(a): #non-zero indices x, y= np.nonzero(a) #the lower and upper bound of the non-zero indices in the array x_low_ind = x.min() x_high_ind = x.max() y_low_ind = y.min() y_high_ind = y.max() return a[x_low_ind:x_high_ind+1,y_low_ind:y_high_ind+1] #input a = np.array([[0, 0, 0], [1, 1, 0], [1, 1, 0]]) print('input array :\n',a) #calling function on input print("Non-zero submatrix is :\n", nonzero_submat(a)) Output: You can get as creative as you want with a nonzero function. You can use it as a feeder function for your custom functions, as shown in this example. In this example, we tried to extract the smallest submatrix from the matrix. First, we have found indices of non-zero and then used those elements as upper and lower bound of the smallest possible submatrix. Conclusion The nonzero function from numpy is a very popular function that is used to find the indices of nonzero elements or satisfy a specified condition in an array. Recommended Articles This is a guide to NumPy nonzero. Here we discuss the Uses of numpy.nonzero() function along with the Examples, Syntax, and parameters. You may also have a look at the following articles to learn more – - numpy.pad() - Numpy.argsort() - NumPy Arrays - NumPy Linear Algebra The post NumPy nonzero appeared first on EDUCBA. This post first appeared on Best Online Training & Video Courses | EduCBA, please read the originial post: here
https://www.blogarama.com/education-blogs/295303-best-online-training-video-courses-educba-blog/42203272-numpy-nonzero
CC-MAIN-2022-21
refinedweb
915
57.67
Personal Behavior-Driven Development This year I was fortunate enough to attend the KCDC conference here in lovely Kansas City. One of the sessions I attended was on Behavior-Driven Development. I have attended several BDD sessions before and have enjoyed each one of them, but there was one stated question that set this one apart from the others. After learning of all the benefits of using BDD in one’s practice and becoming excited to start such a wonderful discovery, what happens if you won’t have any frameworks or management buy-in to support your mission? As the BDD sessions indicate, frameworks such as Cucumber and JBehave gives the Agile team a way to create testing scenarios in a plain text format. So how do you set out on your own and what BDD principals can you implement on a personal development level? Since BDD is an extension of Test-Driven Development, is it easy enough to use the principles and keywords of BDD down to the unit test level. Bringing BDD down to this level starts with following the naming template Dan North recommends for unit test method names. At some point or another, we have all used the test class generator in Eclipse to save some time. It does give you a pre-populated class that prepends the word test in front of all visible method names, but is that time-saving or helpful in the long term? Is it easy to tell what testCalculateCost() tests for? You will eventually add more test cases for that particular method. How will you differentiate the method names for each additional test case? Dan North recommends using sentences based on behaviors to describe the test. The test method testCalculateCost() would become testShouldFailForMissingBillingDate(). Dan also recommends using the word “behaviour” in favor of the notorious keyword “test” when describing what to test next. It is more natural to determine the behaviours of calculateCost() and to compare the next behavior to the existing behaviors to eliminate the gaps. The next natural behavior to test for may be the behavior of a missing due date with testShouldFailForMissingBillingDueDate(). Along with using the naming conventions suggested by Dan North, the session demonstrated how to organize the behavioral test class to mimic a BDD test scenario. As with BDD scenarios written for JBehave to parse, given/when/then BDD keywords are used to help construct and organize what is needed in the test class. These BDD keywords replace the arrange/act/assert keywords commonly used in plain unit tests. Unit to BDD test keyword translation: Unit Test Keyword → BDD Keyword Arrange/Assemble → Given Act → When Assert → Then While developers who are not on an Agile team can still use this style of writing behavioral tests, not starting with a user story can add to the learning curve. It is easier to translate a user story that contains the same structure as the finished personal BDD tests than a bullet point list of requirements. We will use a very basic user story along with a couple BDD test scenarios to show how similar the user story, BDD test case, and personal BDD test class are. Example We are working on a user story to add functionality to a Sudoku game to allow the user to verify if the numbers picked are correct during an in-progress game. Following BDD practices, the game functionality has not yet been implemented. Story: Verify the board. In order to verify the picked numbers As a game player I want the game to verify my picked numbers. A BDD framework would accept something like this: Scenario 1: A player who wants to know if they have incorrect numbers Given a player who has a game in-progress When the board has all correct numbers the player verifies the board Then the board should be returned verified as correct Scenario 2: A player who wants to know if they have incorrect numbers Given a player who has a game in-progress and the board has all correct numbers When the player picks an incorrect number Then the board should be returned verified as incorrect and the incorrect number will be flagged as incorrect Since we are back from the conference and in our BDD-less world, we will have to use our own creative process to fill in the guts of our personal BDD test class. At first, testing with a behavioral approach and not producing tests based on method names of the test fixture will be a little more difficult and time consuming, until this way of thinking is learned. It wasn’t an easy tread transitioning to a TDD world, but at least this will be an evolutionary step. With this, we can start building our new personal BDD test class to test the behaviors of the verify method using JUnit 4. Following what Dan North recommends, we can use the name SudokuBoardServiceSolveBehavior as our test class. public class SudokuBoardServiceVerifyBehavior { ... } As we fill out our test class using personal BDD, we will use the structure and the keywords of given/when/then similar to what is in Scenario 1 and 2. While we won’t have the scenarios, they do help conceptualize the structure and organization of the test class. The keyword given will be used for the test fixture generation methods. The method name will help define the test fixture and the scope of the acceptance tests. The given method will be annotated with JUnit’s @Before annotation and will be in the shared data. In our scenario, we want to start with a board partially filled with correct numbers. public class SudokuBoardServiceVerifyBehavior { @Before public void givenCorrectBoardNumbers() throws Exception { //stub the board board = TestBoardFactory.createPartialBoardWithCorrectNumberes(); //setup the service service = new SudokuBoardService(); } } Next, the when methods contain the executable steps to take on the test fixture. Depending on the number of different behaviors to test, you may have several when methods for the single given method. Each when can cover a BDD test scenario. The when methods will be annotated with JUnit’s @Test. public class SudokuBoardServiceVerifyBehavior { …. @Test public void whenUserPicksCorrectNumber() { //pick correct number board.setNumber(POS_X,POS_Y,5); } @Test public void whenUserSelectsInCorrectNumber() { //pick incorrect number board.setNumber(POS_X,POS_Y,4); } } Now we have the behaviors being performed on the test fixture. The last step is to find out what happened. Did we implement the requirements as expected? We will soon find out with the then methods. The more complicated the system, the more thens you will have as there will be more assertions to make about a behavior. For clarity and descriptiveness, you will have one assert per then. When you find that a unit test fails, you will know immediately and understand why the test failed. The method name will describe what we are asserting for. The when methods will be the ones responsible for passing control their respective then outcomes. public class SudokuBoardServiceVerifyBehavior { private SudokuBoard board = null; private SudokuBoardService service = null; private static int POS_X = 0; private static int POS_Y = 0; @Before public void givenCorrectBoardAndCorrectNumbers() throws Exception { //stub the board board = TestBoardFactory.createPartialBoard(); //setup the service service = new SudokuBoardService(); } @Test public void whenUserSelectsCorrectNumber() { //pick correct number board.setNumber(POS_X,POS_Y,5); thenTheBoardIsVerifiedAsCorrect(); } @Test public void whenUserSelectsInCorrectNumber() { //pick incorrect number board.setNumber(POS_X,POS_Y,4); thenTheBoardIsVerifiedAsInCorrect(); theTheIncorrectNumberIsFlaggedAsIncorrect(); } private void thenTheBoardIsVerifiedAsCorrect() { service.verify(board); assertTrue(board.isCorrect()); } private void thenTheBoardIsVerifiedAsInCorrect() { service.verify(board); assertFalse(board.isCorrect()); } private void thenTheIncorrectNumberIsFlaggedAsIncorrect() { assertTrue(board.getNumber(POS_X,POS_Y).isCorrect()); } } So what just happened here in order to bring BDD to the personal level? You just became the framework replacement. You just translated the set of business requirements into unit tests. The only difference is that you used JUnit annotations instead of the set of annotations from Cucumber or JBehave. While these behavioral tests in no way compare to the value of what a full BDD infrastructure provides, we were able to introduce BDD principles and structure to a personal level. Personal BDD still provides the benefits of using BDD principles to focus on behaviors that directly contribute to business outcomes. Personal BDD will aid in writing unit tests that produce communicable evidence to the developers that the behavioral aspects of the system are working. Testing becomes more descriptive with better test class and method naming conventions. To stay inline with BDD principles, the tests are still nicely automatable. Once all the tests pass, there will be a fully implemented business function protected with functional tests. — John Hoestje, asktheteam@keyholesoftware.com I like this translation. It reinforces the fact that development strategies can almost always be implemented without specialized frameworks. Just have to be creative! Absolutely! Sometimes we get too hung up on the frameworks and forget that it is the principles that really matter. Thanks for the comment! […] Testing: Defining the right “Unit”Blog: A Dungeon Master’s Guide to SCRUMBlog: Personal Behavior-Driven DevelopmentBlog: Our checklist for improving mobile […]
http://keyholesoftware.com/2013/08/19/personal-behavior-driven-development/
CC-MAIN-2014-42
refinedweb
1,487
53.31
You need to read the previous article to understand the basics First Article of Share Point In the previous session of SharePoint article we had discussed about the basics of SharePoint. In this session we will:- How can I create my first site in SharePoint?. What is Quick Launch menu? Below figure shows what is the quick launch menu. In this question we just wanted to make sure you know the terminology and where it maps to. In the further section we will be using this terminology for the left hand menu shown in the figure below. We 'Look and feel' settings. But this will be the landing page when we want to implement customization in SharePoint. We have heard it has ready made functional modules for collaboration? Oh, yes you have heard it loud, right and clear. The best part about SharePoint is collaboration. Collaboration has four major entities people, task, data and communication. So below are some key points of enterprise:-:- Ok, what we will do is that to build confidence let's make a simple page called as 'SimplePage.aspx'. We are not doing anything great in this we will just write this simple sentence inside the page. Note: - For the next question you need to understand the concept of master pages. If you have not please read it once. Consistent look and feel is one of the most important factor in enterprise portal and SharePoint achieves the same'. We have now tailored the 'simplepage.aspx' source code as shown below. We need to do the following:- LOL !...Your SharePoint page now looks like a page. You can get the source of the simple inline ASPX file attached at the end of the article. Some couple of points we need to take care regarding implementing behind code in ASP.NET are the following:-. 'Layout. <! the Assembly and set the Page attributes. Its> <td>Answer</td> <td><asp:Label</td> </table> </asp:Content> <asp:Content SharePoint Behind code implementation <asp:Content When we want to implement behind code we need to register the same in GAC. Note: - Do not try to compile the project in VS.NET IDE. You can only compile the class assembly. The ASPX file you need to later paste it to the '_layout' directory i.e. 'C:. using System.Collections.Generic; using System.Text; // Refer the SharePoint namespace We need to implement the 'SPFeatureReceiver' class and implement all the events. the title and description. public override void FeatureDeactivating(SPFeatureReceiverProperties properties) // Get hold of the SharePoint web object and reset back the values site.Description = "Custom Page display is disabled"; site.Title = site.Properties["OriginalTitle"]; --> and go to 'C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN' directory. Now you can see your feature enabled in the site actions menu. If you click on the feature i.e 'Display If you want only administrators to view the features set RequireSiteAdministrator="True" as shown in the below 'ElementManifest.XML' file. RequireSiteAdministrator="True" The source code has the following things:- View All
http://www.c-sharpcorner.com/uploadfile/shivprasadk/sharepoint-quick-start-faq-part-ii/
CC-MAIN-2018-09
refinedweb
508
67.55
Using. A quick introduction to typed DataSets Typed DataSets are classes that you create declaratively through the Visual Studio designer. Typed DataSet classes derive from the ADO.NET DataSet, DataTable, and DataRow classes and expose a type-safe API for accessing data contained within a DataSet that has a particular schema. You create typed DataSets in Visual Studio 2005 through some simple drag-and-drop operations and by setting properties in the Properties window of the designer. What you are actually creating when you design a typed DataSet is an XML Schema Definition (XSD) file that contains the schema of the data that will be contained by the DataSet. The XSD file also contains annotations that associate it with the data source it was generated from. Visual Studio then uses that XSD to generate a code file that contains the typed DataSet class definitions. When you work with data in an application, the data is usually partitioned into different types of logical business entities, such as Customers, Products, Employees, and so on. To work with that data, you need to encapsulate those logical entities into objects that you can deal with in your code. You could write a custom class for each entity type. Those entity types would expose properties for each of the data values that the entity includes. You would then also want to create a custom collection type for each entity type so that you could have strongly typed collections to contain those entities. Typed DataSets represent an easy alternative to creating and maintaining all those custom types yourself. Essentially what you are doing when you create a typed DataSet is that you are creating a set of custom type definitions to contain logical business entities and collections of those entities, similar to writing those types by hand. The difference is that you are doing it in a declarative way through the designer that is easy to visualize, edit, and keep synchronized with the database schema that populates those business entities. The code generation of Visual Studio takes care of writing all the underlying properties and methods that give you a strongly typed API for dealing with those business entities in your consuming code. Additionally, because these types are inheriting from the ADO.NET types, you inherit the rich relational data manipulation functionality from those types. These types are also aligned well with the data binding capabilities in WinForms and ASP.NET, so if you will be setting up data binding using the objects, then you have less work to do on that front as well. Finally, and perhaps most importantly, when you create typed DataSets in Visual Studio 2005 from a database, you also get a table adapter type created for each table that you add to the data set. A table adapter is a full fledged data access component that lets you retrieve and update data from the database. It encapsulates a connection, a data adapter, and a set of command objects that allow you to execute queries to the database. I'll get into more detail on table adapters in a little bit. DataSets vs. Business Objects: An open debate Almost as common as the debate over which .NET language to choose is the argument about whether to use DataSets or not. As described above, typed DataSets are easy to generate through the designer, provide a type safe API for containing business entity data, and already support advanced features such as change tracking, sorting, filtering and searching. Some of the resistance to DataSets resulted from several performance shortcomings in the .NET 1.1 implementations. These problems included poor performance when working with large DataSets and the fact that DataSets always serialized themselves as XML, which had bandwidth and performance implications when passing DataSets across remoting boundaries. These problems have been fixed in .NET 2.0 and there have been a large number of other improvements. If you dismissed DataSets in .NET 1.1, they deserve another look. The alternative to using DataSets is to create custom object types that represent your business entities, and custom collection types to contain them. When you go this route, you end up needing to write a lot more code yourself. This has gotten a lot better in Visual Studio 2005 and the .NET Framework 2.0 with the additions of code snippets and generic collection classes. But to support the full range of features that a DataSet provides, there is still a fair amount of custom code that you will need to write by hand. Custom objects have the advantage of giving you explicit and complete control over the way the type is designed, what its internal capabilities are, and what the API is that is exposed from the object. If you prefer a pure object-oriented design approach, then custom business entities will feel a little more comfortable to you. You can accomplish almost anything with a typed DataSet that you can with a custom business entity, but some things may be a little less clean with a typed DataSet if the things you are trying to do don't map well to the relational nature of a typed DataSet. But if you are primarily getting business data for the purposes of presenting the data, allowing the user to work with the data, and then will persist the data back to the database, you will be able to get things done quicker with typed DataSets if you harness the features of the DataSet designer. When you go with typed DataSets in Visual Studio 2005, you can actually support most of the same design styles that you could with custom business entity types. The data access code will always be separated into the table adapter types generated by the designer, or into data access components that you write. But you can add custom validation and other logic into your business entity types (the typed data row or data table classes) through partial class extensions. Each of the types created as part of a typed DataSet definition (data set, data table, data row, and table adapter) are defined in the generated code as partial classes. This feature in .NET 2.0 allows you to supplement the designer generated code with custom code that becomes part of the compiled type, but you do so through a separate code file. This prevents your code from being destroyed if you choose to regenerate the designer generated code. For more information on partial types, see the MSDN library documentation for .NET 2.0. Another argument that comes up a lot against using DataSets is the assertion that if you are using DataSets in your presentation or business layer, then you are tightly coupling your application to the data tier. This does not have to be the case. First off, you should consider using stored procedures as a layer of decoupling between your actual data tier schema and your application. Your stored procedures can then return and work with result sets that map well to the business entities that you will be manipulating in your application. Additionally, if you need to provide additional decoupling beyond what the stored procedures provide, you can transform data that has been placed into a DataSet into either a different (decoupled) typed DataSet definition or a custom business entity type in your business or data access layer. One final thing to point out has to do with returning DataSetsfrom Web services. There is a strong argument that you should never return a DataSet from a Web service method. Never is a strong word in design, but if you want to support a true service-oriented architecture with your Web services, I would have to agree with this guidance. Typed DataSetsdo introduce both a type coupling and a .NET technology coupling for any clients of that service, which is something you should avoid in a service-oriented world. If your client is a .NET client, it is fairly simple to consume the proxy generated version of the typed DataSeton the client side, and there is little harm if you are willing to lock yourself into only .NET clients. But in general you should think twice before exposing a DataSet as a type on a web service contract, and favor not doing so. If you want to achieve maximum productivity in building a .NET application, and can live with the limitations described in this section, then typed DataSets are a great capability that you should consider exploiting in your .NET applications where it makes sense. One of the biggest wins in using typed DataSets in Visual Studio 2005 is the fact that it also generates a table adapter class, which is like a typed data adapter, for each table in the DataSet. The designer allows you to very quickly create customized query methods in the table adapter that makes it so you will rarely have to write any ADO.NET code yourself if you are working with typed DataSets. A working example To make things more concrete, let's step through a simple example of creating a typed DataSet and using table adapters. To emphasize that nothing that I am showing in this article is particular to SQL Server 2005, I will use the tried-and-true Northwind database with SQL Server 2000 as a data source. If you are working with a machine that does not have SQL Server 2000 on it, you can also get an instance of Northwind installed on SQL Server 2005, including the Express version. You will need to get a data connection configured for the Northwind database in Server Explorer. To do so, right click on the Data Connections node in Server Explorer, select Add Connection, and step through the Add Connection dialog to configure a connection to Northwind. Unfortunately the Northwind database does not have a good stored procedure layer set up for CRUD (Create, Retrieve, Update, Delete) operations. It also does not have any columns in the tables to help enforce optimistic concurrency efficiently. To do this, you should have a datetime, rowguid, or timestamp column that gets updated on every INSERT or UPDATE, and that can be used to check for concurrency violations when updating or deleting rows. The download code for this article includes a script that you can run against the Northwind database through SQL Query Analyzer or SQL Server Management Studio that will add a Modified datetime column to the Employees table and CRUD stored procedures to work with that table. The sample developed below works against those modifications to implement the table adapter using a good technique for real applications. The stored procedures include SelectEmployees, UpdateEmployees, InsertEmployees, and DeleteEmployees standardized CRUD procedures that I have implemented in a CodeSmith template so that I can generate them for any table I am working with that uses an optimistic concurrency checking column. The CodeSmith template is also included in the download code in case you use that tool for code generation, but for the sample you can just run the included SQL script. After running the SQL script to modify Northwind as described above, open up Visual Studio 2005 and create a new class library project named NorthwindDataAccess (see Figure 1). You can delete the Class1.cs file that is added to the project by default. Next, right click on the project in Solution Explorer and select Add > New Item... from the context menu. Select the DataSet template type, and name it EmployeesDataSet.xsd as shown in Figure 2. When you do this, you are adding a typed DataSetdefinition to your project. Figure 1: Create a Data Access Class Library Project Figure 2: Add a Typed DataSetDefinition to the Project Next we will add some table definitions to the DataSet through the Server Explorer window. Bring up Server Explorer (View > Server Explorer) and expand the Northwind data connection down to the Stored Procedures level. Drag the SelectEmployees stored procedure onto the design surface. When you do this, you will see a table definition added that has all the same columns as the Employees table from the database. These are defined based on the columns that the SELECT statement in the stored procedure returns. Rename the table from SelectEmployees to just Employees by single clicking on the name in the title bar of the table definition in the designer. Alternatively, you can select the table in the designer and use the Properties window to rename it. You will also see that at the bottom of the Employees table, something else has been added called EmployeesTableAdapter (see Figure 3). This is the table adapter that I introduced earlier. When you save the data set, Visual Studio will kick in and do some code generation behind the scenes. Figure 3: Employees Table Definition and Table Adapter For the simple drag and drop that we just did, Visual Studio created a number of new type definitions. The EmployeesDataSet type is the top level container class for the other data container types we are working with. An EmployeesDataTable was generated that provides a strongly typed collection class for Employee entities. An EmployeesRow class was generated that is a strongly typed entity class with properties exposed for each of the columns in the table. And finally, the EmployeesTableAdapter is generated to allow you to retrieve data into the Employees table using the SelectEmployees stored procedure. In one single drag and drop operation, over 1000 lines of highly functional best-practice ADO.NET code was written for you. All these types are defined as partial classes in a designer code file (EmployeesDataSet.Designer.cs in this case) when you save the XSD file. This allows you to add code to any of the classes in a separate partial class definition file that will not be affected if you need to regenerate your code in the future. Regenerating the DataSetmight be necessary if you are iteratively developing the database schema, or if you just goon something up in the designer. Hooking up the other stored procedures When you drag a SELECT stored procedure onto the designer, the table adapter only implements the code to fill the generated table. Specifically, it adds a Fill method that takes the specific table type (EmployeesDataTable in this case) as a parameter and fills that instance with the rows returned from the SELECT stored procedure. It also generates a GetData method that will create an instance of the table type, populate it with the rows, and return it from the method as the return value so that you do not have to construct one yourself first. To hook up the corresponding UPDATE, INSERT, and DELETE stored procedures, there is a simple wizard available through the designer. This wizard is the same one you can use to later modify the table adapter if you want to target different or modified stored procedures. To bring up the wizard, click on the title bar of the table adapter in the designer to select it, then right click on it and select Configure... from the context menu. This will bring up the Table Adapter Configuration Wizard, which allows you to change the stored procedures that are called by the table adapter. Since the table adapter is already hooked up to the existing SelectEmployees stored procedure, it will start at the step labeled Bind Commands to Existing Stored Procedures (see Figure 4). Figure 4: Table Adapter Configuration Wizard To hook up the InsertEmployees, UpdateEmployees, and DeleteEmployees stored procedures, just select them from the drop down lists on the left side of the wizard. The right side of the wizard will show the mapping of stored procedure parameters to columns in the associated table. If your stored procedure parameter names match existing columns in the table, the mappings will all be set up automatically for you, which should always be the case when the table is generated from the stored procedure. Unfortunately, at least in Visual Studio 2005 Beta 2, the wizard is not perfect and may not match all the parameters correctly. For example, in this sample, the PhotoPath parameter on the UPDATE and INSERT stored procedures gets mapped to the Photo column by mistake. To fix that, you just need to select the correct column in the column mappings as shown in Figure 5. Make sure you do this for both the insert and update stored procs. Hopefully this behavior will be fixed by release. Figure 5: Correcting the column mappings Once you have selected the stored procedures, you can simply press the Finish button. The other steps in the wizard are used for configuring other scenarios that I don't have room to cover here. For more comprehensive coverage of configuring table adapters, see Chapter 2 in my book Data Binding in Windows Forms 2.0. At this point Visual Studio adds Insert, Update, and Delete methods that allow you to perform modifications at the table or row level, as well as overloads that allow you to pass the parameters to the stored procedures explicitly. With those simple steps, we are all hooked up to retrieve employee data into instances of the EmployeesDataTable collection type and work with them in the middle tier or client layer. You can then pass modified tables, rows, or individual values back down through the table adapter to persist those changes to the database. If you work directly against the tables in a database by dragging them out instead of dragging out a stored procedure, SELECT, UPDATE, INSERT, and DELETE SQL statements will be written and added to the table adapter for you. Those default queries use optimistic concurrency checking that compares the values of every column in the table to their original values. If you wanted to modify these queries, you could just step into the Table Adapter Configuration Wizard and edit the queries. Adding additional queries to a table adapter You are not stuck with the basic CRUD queries that are generated for you by default for a table adapter. Using the designer, it is easy to add additional ad-hoc queries that can be used for things like retrieving Employees by country. To do so, right click on the table adapter in the designer and select Add Query... from the context menu. This brings up the TableAdapter Query Configuration Wizard. The first step, shown in Figure 6, allows you to specify whether you will base the new query method on a SQL statement, a new stored procedure, or an existing stored procedure. For the first two choices, you are then led through additional steps that allow you to specify the supporting SQL that will be called by the table adapter. The option to Use existing stored procedures allows you to point to another stored procedure that is already in the target database and hook it up to either return rows, return a single value, or perform update, insert, or delete forms of operations. Figure 6: Selecting the query command type We need to create a stored procedure to support retrieving employees by country, so we might as well do it through the wizard. Select the option to Create new stored procedure and press Next. The next step allows you to specify what the query type will be as shown in Figure 7. Figure 7: Selecting the query type We are designing a stored procedure that returns rows of employees for a specified country, so the first option is the one we want for this case. Press Next and you are presented with the step that allows you to specify the SQL that the stored procedure will wrap (see Figure 8). You can press the Query Builder button to get a dialog that helps you select the appropriate column names and table names based on the database schema, or you can just type in the query. Type in the SQL code shown in Figure 8. Figure 8: Specifying the body of the stored procedure The wizard will infer the parameters for the stored procedure based on the parameters present in the query and the underlying types of the columns. It will also automatically try to map the columns to the corresponding columns in table as was done when configuring the original stored procedure. Any problems will be reported by the wizard at the end and will prevent the creation of the query method in the table adapter. Press Next to move to the step that allows you to specify the name of the stored procedure that will be added to the database to contain the specified SQL (see Figure 9). There is a button in this step that will allow you to preview the full SQL script that is generated to create the stored procedure if you want. Figure 9: Naming the stored procedure Press Next to move to the next step, which allows you to specify the name(s) of the corresponding methods that will be added to the table adapter. For a procedure that will return rows, two methods will be created. One takes the table type (EmployeesDataTable in this case) as a parameter, as well as any parameters required by the stored procedure (country in this case). The second method just takes the parameters that are passed to the stored procedure, if any, and returns a populated instance of the table type. The naming convention for these methods is FillByXXX and GetDataByXXX, where XXX is something indicating the criteria that is specified in the parameters (see Figure 10). Figure 10: Naming the table adapter query methods Pressing Next just takes you to the final step where the code generation is executed. If you got everything correct, you will just see confirmation of what was performed by the wizard (see Figure 11). If you had a syntax error on your query or other problems occurred in the code generation process, they will be indicated here. Figure 11: Finishing the wizard Make sure to save the DataSetat this point. The wizard is actually adding code (annotations) to the XSD that is the true DataSetdefinition. The code generation of the corresponding C# or VB code is not run until you save the DataSetXSD file. In addition to adding queries to an existing table adapter, you can add ad-hoc queries to a typed DataSetdefinition, not associated with any of its tables. To do so, just right click in an empty area in the designer and you can add a query as described above. Doing so will define methods on a table adapter type that gets named QueriesTableAdapter and simply resides in the DataSetcode generated file. Going beyond the designer What if you want to use a data reader to populate a custom business entity instead of populating a data table? What if you want to execute some custom validation of a column value when it is changed by client code? Do these requirements mean you need to abandon the typed DataSet designer? Not necessarily. These things cannot be set up directly in the designer, but are fairly straightforward to add through partial class extensions. If you add a class to your data access layer project, and put the following code in it: using System; using System.ComponentModel; using System.Data.SqlClient; using System.Data; namespace NorthwindDataAccess.EmployeesDataSetTableAdapters { public partial class EmployeesTableAdapter : Component { public SqlDataReader GetReader() { return Adapter.SelectCommand.ExecuteReader( CommandBehavior.CloseConnection); } } } You will now have added a method to the table adapter that can execute the SelectCommand on the encapsulated data adapter directly, instead of going through the Fill or GetData methods. You can then do whatever you need to with the internal Connection, Adapter, or Commands properties on the table adapter to access its encapsulated objects. Likewise, if you wanted to add custom validation of columns, you can just add that validation logic through a partial class extension of the table type itself: namespace NorthwindDataAccess { public partial class EmployeesDataSet : DataSet { public partial class EmployeesDataTable : DataTable { public override void BeginInit() { this.ColumnChanging += ValidateColumn; } void ValidateColumn(object sender,DataColumnChangeEventArgs e) { if(e.Column.ColumnName == "BirthDate") { if((DateTime)e.ProposedValue < DateTime.Parse("1/1/1900")) { throw new ArgumentException( "Employee's productivity is likely to be very low"); } } } } } } In this code we are actually extending both the typed DataSetclass and the typed data table class, which we have to do since the table type is a nested type inside the typed DataSet type. Admittedly, this is not as clean as just calling a validation method in the set block of a property definition in a custom entity type, but the net result is the same. Consuming the table adapter methods Once you have defined your data access layer through your table adapters, you can consume them with nice clean code, the same as you would if you were writing all the methods yourself: // Get a collection of business entities EmployeesTableAdapter adapter = new EmployeesTableAdapter(); EmployeesDataSet.EmployeesDataTable employees = adapter.GetDataByCountry("USA"); // Modify one of the items employees[0].BirthDate = DateTime.Parse("1/1/1965"); // Save the changes to the database adapter.Update(employees); To use the table adapter, you just create an instance of it and call its methods, passing the appropriate parameters, just like you would with a custom data access component. The big difference is that you did not have to write a line of ADO.NET code yourself, and new queries can be added in seconds instead of minutes. Wrap up There is one downside to the way the code is generated for table adapters. The code is injected into the same file as the typed DataSetdefinition. This means that the business entity type definitions (the data set, data table, and data row types) are physically coupled to the data access component type definition (the table adapter). This prevents you from being able to factor your business entity definitions into separate class library that is referenced from any consuming layer, while keeping the data access components in their own class library that is only referenced from the business layer. You can work around this by taking the code generated code and moving it into another project, but then you lose the designer support for modifying and maintaining that code. Perhaps this limitation will be addressed in a future version of Visual Studio. But for now, that is not a significant enough limitation to offset the huge productivity boon that the DataSetdesigner represents. DataSets, and the DataSet designer in Visual Studio in particular, include some significant new capabilities in Visual Studio 2005. Typed DataSetsare quick and easy to create, and provide fully functional, strongly-typed containers for collections of business entity data. In addition to the type definitions for strongly typed tables and rows within the data set, you get a table adapter per table that acts as a data access component encapsulating all the ADO.NET code to work with a particular table in a strongly typed way. You can add custom query methods to the table adapter to support multiple use cases for a particular entity type, or you can add ad-hoc query methods not associated with a particular table. DataSets are not appropriate for every application, and custom business entities certainly have advantages in many scenarios. But for knocking out data access use cases quickly and effectively, DataSets and table adapters work great for a large number of situations as well. Download code samples
https://searchwindevelopment.techtarget.com/tip/Using-the-Visual-Studio-2005-DataSet-Designer-to-build-a-data-access-layer
CC-MAIN-2020-16
refinedweb
4,556
58.11
progress 5.0.2 Easy progress reporting for D. There are Progress bar, Spinner, Counter and D-man. To use this package, run the following command in your project's root directory: Manual usage Put the following dependency into your project's dependences section: progress Easy progress reporting for D inspired by Python's one with the same name. There are 6 progress bar, 4 spinner, 4 counter, and... Dman. Progress bar - Bar - ChargingBar - FillingSquaresBar - FillingCirclesBar - IncrementalBat - ShadyBar Spinner - Spinner - PieSpinner - MoonSpinner - LineSpinner Counter - Counter - Countdown - Stack - Pie Dman - DmanSpinner Usage progress bars Call next to advance and finish to finish. Bar b = new Bar(); b.message = {return "Processing";}; b.max = 20; foreach(i; 0 .. 20) { //Do some work b.next(); } b.finish(); Processing |################## | 12/20 In the general case, you can use the iter method to write simply import std.range : iter; Bar b = new Bar(); foreach(i; b.iter(iota(20)) ) { //Do something } Progress bars are very customizable, you can change their width, their fill character, their suffix and more. import std.conv : to; b.message = {return "Loading";}; b.fill = '@'; b.suffix = {return b.percent.to!string ~ "%";}; This will produce a bar like the following: There are various properties that can be used in message and suffix. Instead of passing all configuration options on instatiation, you can create your custom subclass: class CustomBar : Bar { this() { super(); bar_prefix = "/"; bar_suffix = "/"; empty_fill = " "; fill = "/"; suffix = {return "Custom";}; } You can also override any of the arguments or create your own: class SlowBar : Bar { this() { super(); suffix = {return this.remaining_hours.to!string ~ "hours remaining";}; } @property long remaining_hours() { return this.eta.total!"hours"; } } Spinners For actions with an unknown number of steps you can use a spinner: import progress.spinner; auto s = new Spinner(); s.message = {return "Loading";}; while (finished != true) { //Do something s.next(); } Counters Counters can be used like progress bar. However, Counter is the same as spinners, and has no properties that require maximum value. Dman Same as spinners. it's very big. Please see example projects and source if you want to learn more. - Registered by Kotet - 5.0.2 released a month ago - kotet/progress - ISC - Authors: - - Dependencies: - none - Versions: - Show all 25 versions - Download Stats: 0 downloads today 1 downloads this week 2 downloads this month 192 downloads total - Score: - 1.2 - Short URL: - progress.dub.pm
https://code.dlang.org/packages/progress
CC-MAIN-2022-27
refinedweb
388
68.16
). The current mouse. a dictionary containing the status of each mouse event. . A list of channel names that may be used with setChannel and getChannel.. Alternative to the 2 arguments, 4 arguments (channel, matrix, loc, size, quat) are also supported. Note These values are relative to the bones rest position, currently the api has no way to get this info (which is annoying), but can be worked around by using bones with a rest pose that has no translation.. KX_BlenderMaterial Returns the material’s shader. Set the pixel color arithmetic functions. Returns the material’s index. Applies changes to a camera. strength of of the camera following movement. minimum distance to the target object maintained by the actuator. maximum distance to stay from the target object. height to stay above the target object. axis this actuator is tracking, True=X, False=Y.. Read-only. [sx, sy, sz] The object’s local position. [x, y, z] The object’s world position. [x, y, z].colour = colour of this light. Black = [0.0, 0.0, 0.0], White = [1.0, 1.0, 1.0]. Synonym for colour. import GameLogic co = GameLogic.getCurrentController() obj = co.owner. Mouse Sensor logic brick. current [x, y] coordinates of the mouse, in frame coordinates (pixels). sensor mode. Get the mouse button status.).. KX_PhysicsObjectWrapper Set the object to be active. Set the angular velocity of the object. Set the linear velocity of the object. This is the interface to materials in the game engine. Materials define the render state to be applied to mesh objects. Warning Some of the methods/variables are CObjects. If you mix these up, you will crash blender. This example requires PyOpenGL and GLEWPy import GameLogic import OpenGL from OpenGL.GL import * from OpenGL.GLU import * import glew from glew import * glewInit() vertex_shader = """ void main(void) { gl_Position = ftransform(); } """ fragment_shader =""" void main(void) { gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); } """ class MyMaterial: def __init__(self): self.pass_no = 0 # Create a shader self.m_program = glCreateProgramObjectARB() # Compile the vertex shader self.shader(GL_VERTEX_SHADER_ARB, (vertex_shader)) # Compile the fragment shader self.shader(GL_FRAGMENT_SHADER_ARB, (fragment_shader)) # Link the shaders together self.link() def PrintInfoLog(self, tag, object): """ PrintInfoLog prints the GLSL compiler log """ print "Tag: def PrintGLError(self, tag = ""): def PrintGLError(self, tag = ""): """ Prints the current GL error status """ if len(tag): print tag err = glGetError() if err != GL_NO_ERROR: print "GL Error: %s\\n"%(gluErrorString(err)) def shader(self, type, shaders): """ shader compiles a GLSL shader and attaches it to the current program. type should be either GL_VERTEX_SHADER_ARB or GL_FRAGMENT_SHADER_ARB shaders should be a sequence of shader source to compile. """ # Create a shader object shader_object = glCreateShaderObjectARB(type) # Add the source code glShaderSourceARB(shader_object, len(shaders), shaders) # Compile the shader glCompileShaderARB(shader_object) # Print the compiler log self.PrintInfoLog("vertex shader", shader_object) # Check if compiled, and attach if it did compiled = glGetObjectParameterivARB(shader_object, GL_OBJECT_COMPILE_STATUS_ARB) if compiled: glAttachObjectARB(self.m_program, shader_object) # Delete the object (glAttachObjectARB makes a copy) glDeleteObjectARB(shader_object) # print the gl error log self.PrintGLError() def link(self): """ Links the shaders together. """ # clear error indicator glGetError() glLinkProgramARB(self.m_program) self.PrintInfoLog("link", self.m_program) linked = glGetObjectParameterivARB(self.m_program, GL_OBJECT_LINK_STATUS_ARB) if not linked: print "Shader failed to link" return glValidateProgramARB(self.m_program) valid = glGetObjectParameterivARB(self.m_program, GL_OBJECT_VALIDATE_STATUS_ARB) if not valid: print "Shader failed to validate" return def activate(self, rasty, cachingInfo, mat): self.pass_no+=1 if (self.pass_no == 1): glDisable(GL_COLOR_MATERIAL) glUseProgramObjectARB(self.m_program) return True glEnable(GL_COLOR_MATERIAL) glUseProgramObjectARB(0) self.pass_no = 0 return False obj = GameLogic.getCurrentController().owner mesh = obj.meshes[0] for mat in mesh.materials: mat.setCustomMaterial(MyMaterial()) print mat.texture Texture name. OpenGL texture handle (eg for glBindTexture(GL_TEXTURE_2D, gl_texture). Material name. Texture face properties. Texture is tiling. Number of tile repetitions in x direction. Number of tile repetitions in y direction. Drawing mode for the material. - 2 (drawingmode & 4) Textured - 4 (drawingmode & 16) Light - 14 (drawingmode & 16384) 3d Polygon Text. This material is transparent. All meshes with this material will be rendered after non transparent meshes from back to front. Transparent polygons in meshes with this material will be sorted back to front before rendering. Non-Transparent polygons will be sorted front to back before rendering. Light layers this material affects. Mesh data with this material is triangles. It’s probably not safe to change this. The diffuse colour of the material. black = [0.0, 0.0, 0.0] white = [1.0, 1.0, 1.0]. The specular colour of the material. black = [0.0, 0.0, 0.0] white = [1.0, 1.0, 1.0]. The shininess (specular exponent) of the material. 0.0 <= shininess <= 128.0. The amount of specular of the material. 0.0 <= specularity <= 1.0. Updates a realtime animation. Sets texture render state. mat.setTexture(mat.tface) Sets material parameters for this object for rendering. Material Parameters set: Sets the material state setup object. Using this method, you can extend or completely replace the gameengine material to do your own advanced multipass effects. Use this method to register your material class. Instead of the normal material, your class’s activate method will be called just before rendering the mesh. This should setup the texture, material, and any other state you would like. It should return True to render the mesh, or False if you are finished. You should clean up any state Blender does not set before returning False. Activate Method Definition: def activate(self, rasty, cachingInfo, material): class PyMaterial: def __init__(self): self.pass_no = -1 def activate(self, rasty, cachingInfo, material): # Activate the material here. # # The activate method will be called until it returns False. # Every time the activate method returns True the mesh will # be rendered. # # rasty is a CObject for passing to material.updateTexture() # and material.activate() # cachingInfo is a CObject for passing to material.activate() # material is the KX_PolygonMaterial instance this material # was added to # default material properties: self.pass_no += 1 if self.pass_no == 0: material.activate(rasty, cachingInfo) # Return True to do this pass return True # clean up and return False to finish. self.pass_no = -1 return False # Create a new Python Material and pass it to the renderer. mat.setCustomMaterial(PyMaterial()) | # +----------+ +-----------+ +-------------------------------------+ import GameLogic # List detail meshes here # Mesh (name, near, far) # Meshes overlap so that they don't 'pop' when on the edge of the distance. meshes = ((".Hi", 0.0, -20.0), (".Med", -15.0, -50.0), (".Lo", -40.0, -100.0) ) co = GameLogic.getCurrentController() obj = co.owner act = co.actuators["LOD." + obj.name] cam = GameLogic.getCurrentScene().active_camera def Depth(pos, plane): return pos[0]*plane[0] + pos[1]*plane[1] + pos[2]*plane[2] + plane[3] # Depth is negative and decreasing further from the camera depth = Depth(obj.position, cam.world_to_camera[2]) newmesh = None curmesh = None # Find the lowest detail mesh for depth for mesh in meshes: if depth < mesh[1] and depth > mesh[2]: newmesh = mesh if "ME" + obj.name + mesh[0] == act.getMesh(): curmesh = mesh if newmesh != None and "ME" + obj.name + newmesh[0] != act.getMesh(): # The mesh is a different mesh - switch it. # Check the current mesh is not a better fit. if curmesh == None or curmesh[1] < depth or curmesh[2] > depth: act.mesh = obj.getName() + newmesh[0] GameLogic.addActiveActuator(act, True) MeshProxy or the name of the mesh that will replace the current one. Set to None to disable actuator. when true the displayed mesh is replaced. when true the physics mesh is replaced. Immediately replace mesh without delay.! import GameLogic # get the scene scene = GameLogic.getCurrentScene() # print all the objects in the scene for obj in scene.objects: print obj.name # get an object named 'Cube' obj = scene.objects["Cube"] # get the first object in the scene. obj = scene.objects[0] #.the actuator to be activated - they act instantly provided that the actuator has been activated once at least. The filename of the sound this actuator plays. The volume (gain) of the sound. The pitch of the sound. The roll off factor. Rolloff defines the rate of attenuation as the sound gets further away. The loop mode of the actuator. The position of the sound as a list: [x, y, z]. The velocity of the emitter as a list: [x, y, z]. The relative velocity to the observer determines the pitch. List of 3 floats: [x, y, z]. The orientation of the sound. When setting the orientation you can also use quaternion [float, float, float, float] or euler angles [float, float, float]. The operation mode of the actuator. Can be one of these constants vertex holds position, UV, colour and normal information. Note: The physics simulation is NOT currently updated - physics will not respond to changes in the vertex position. The position of the vertex. The texture coordinates of the vertex. The normal of the vertex. The colour of the vertex. Black = [0.0, 0.0, 0.0, 1.0], White = [1.0, 1.0, 1.0, 1.0] Synonym for colour. colour. 0.0 <= r <= 1.0. The green component of the vertex colour. 0.0 <= g <= 1.0. The blue component of the vertex colour. 0.0 <= b <= 1.0. The alpha component of the vertex colour. colour of this vertex. The colour is represented as four bytes packed into an integer value. The colour is packed as RGBA. Since Python offers no way to get each byte without shifting, you must use the struct module to access colour in an machine independent way. Because of this, it is suggested you use the r, g, b and a attributes or the colour attribute instead. import struct; col = struct.unpack('4B', struct.pack('I', v.getRGBA())) # col = (r, g, b, a) # black = ( 0, 0, 0, 255) # white = (255, 255, 255, 255) Sets the colour of this vertex. See getRGBA() for the format of col, and its relevant problems. Use the r, g, b and a attributes or the colour attribute instead. setRGBA() also accepts a four component list as argument col. The list represents the colour spesifying]. Sets the seed of the random number generator. If the seed is 0, the generator will produce the same value on every call.. This camera’s 4x4 model view matrix. (read-only). Note This matrix is regenerated every frame from the camera’s position and orientation.. import GameLogic co = GameLogic.getCurrentController() cam =. import GameLogic co = GameLogic.getCurrentController() cam =. import GameLogic co = GameLogic.getCurrentController() cam =. Constants related to (only for IK constraint).) Armature sensor detect conditions on armatures. Constants related to. Constants related to type Constants related to ik_type constraint is trying to match the position and eventually the rotation of the target. Constraint is maintaining a certain distance to target subject to ik_mode Constants related to. Constants related to ik_mode The constraint tries to keep the bone within ik_dist of target The constraint tries to keep the bone outside ik_dist of the target The constraint tries to keep the bone exactly at ik_dist of the target.. See rotation. Use the following constants (euler mode are named as in Blender UI but the actual axis order is reversed)..
http://www.blender.org/documentation/blender_python_api_2_60_6/bge.types.html
crawl-003
refinedweb
1,828
53.88
I2C (also referred as IIC or TWI) unique address. Communication between devices is master and slave based. Master generates clock signal, initiates and terminates data transfer. From electrical point of view I2C devices use open drain (open collector) pins. In order to operate correctly SDA and SCL lines require pull up resistors. Typically 4.7kΩ resistors are used. Each communication is initiated by START signal and finished by STOP. These are always generated by master. START and STOP signals are generated by pulling SDA line low while SCL line is high. In other cases when data is transferred data line must be stable during clock high and can be changed when clock is low: Bus is considered to be busy between START and STOP signals. So if there are more than one master each of them has to wait until bus is freed by current master with STOP signal. I2C communication packet consists of several parts: START signal; Address packet – seven address bits lead by data direction bit (read or write) + acknowledge bit; Data packet – eight data bits + acknowledge bit; STOP signal. Acknowledge bit is a ninth bit of every byte sent. Receiver always has to confirm successful receive with ACK by pulling SDA low or in case receiver cannot accept data it will leave SDA high (NACK) so master could stop transmitting and do other scenario if needed. I2C devices can work in four different modes: - Master Transmitter – initiates transfer sends data to slave device; - Master Receiver – initiates transfer reads data from slave device; - Slave Transmitter – waits for master request and then sends data; - Slave Receiver – waits for master transmission and accepts data. It is worth mention that I2C interface supports multi-master transmission. It doesn’t mean that all master are able to transmit data at same time. As matter of fact each master must wait for current transmission to be finished and then can initiate transfer. It may be situation when multiple masters tries to initiate transfer. In this case so called arbitration happens where each transmitter check level of bus signal and compares it with expected. If master loses arbitration it must leave bus immediately and/or switch to slave mode. Bursting multiple bytes I2C can send and receive multiple bytes inside single packet. This is handy for instance to write or read memory. For instance we need to read 3 bytes from EEPROM memory address 0x0F. Say that EEPROM slave address is 0x1111000. This is how whole reading process would look: Note that first master has to write in order to select initial memory address. Then send start signal again in order to initiate master read mode and then after reading of all bytes is done free line by sending stop signal. AVR I2C registers AVR microcontroller is using TWI (Two Wire Interface) nomenclature when talking about I2C. So all registers are named as TWI. First important register is bit rate register TWBR. It is used to scale down CPU frequency in to SCL. Additionally there are two bits (TWPS1 and TWPS2) in status register TWSR to prescale SCL frequency with values 1, 4, 16 and 64. You can find formula in datasheet that is used to calculate SCL end frequency: As usually there is control register TWCR which has a set of bits that are used to enable TWI interrupt, TWI enable, Start, Stop. Status register TWSR holds earlier mentioned prescaller bits but its main purpose to sense I2C bus status with TWS[7:3] bits. TWDR is data register which is used to hold next byte to transmit or received byte. TWAR and TWARM register are used when AVR works as I2C slave. Example of using I2C in AVR As example we are going to interface old good 24C16 I2C EEPROM chip to Atmega328P. As you can see connection is simple – only SDA and SCL lines has to be connected. For different EEPROM capacities you may need to connect A0, A1 and A2 pins to GND or pull high in order to set device address. 24C16 doesn’t use these pins for addressing chip. We leave them open. For demonstration I am using Arduino328P board which is used as general AVR test board. You can use any other AVR development board to test this example. If you have Arduino board laying arround I suggest not to clear original bootloader by writing hex with some ISP adapter, but use built in bootloader to upload hex. Download program that communicates to bootloader so as from Arduino IDE: Hardware is really simple lets head to software writing. For debugging purposes USART is used which was discussed in earlier tutorials. So we are gonna set it to 9600 baud and use as library usart.h. In order to have nice control of I2C interface lets split whole process in to multiple functions. First of all we need to initialize TWI (I2C): void any additional prescallers so set TWSR to 0. And finally we simply enable TWI by setting TWEN bit to “1”. Next we take care of TWIStart and TWIStop functions that generate start and stop signals. void TWIStart(void) { TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN); while ((TWCR & (1<<TWINT)) == 0); } //send stop signal void TWIStop(void) { TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN); } For start we need to set TWSTA and for stop TWSTO bits along with TWINT and TWEN bits. After start signal is sent we need to wait for status (until TWINT resets to zero). Another function is TWIWrite: void TWIWrite(uint8_t u8data) { TWDR = u8data; TWCR = (1<<TWINT)|(1<<TWEN); while ((TWCR & (1<<TWINT)) == 0); } it writes data byte to TWDR register which is shifted to SDA line. It is important to wait for transmission complete within while loop. After which status can be read from status register TWSR. Reading is done in similar way. I have wrote two functions where one transmits ACK signal after byte transfer while another doesn’t: uint8_t TWIReadACK(void) { TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA); while ((TWCR & (1<<TWINT)) == 0); return TWDR; } //read byte with NACK uint8_t TWIReadNACK(void) { TWCR = (1<<TWINT)|(1<<TWEN); while ((TWCR & (1<<TWINT)) == 0); return TWDR; } And finally last function we gonna use is reading status: uint8_t TWIGetStatus(void) { uint8_t status; //mask status status = TWSR & 0xF8; return status; } We need to read upper five bits from TWSR register so we simply mask out three lower bits. As we will see reading status messages is essential part in detecting failures in I2C communication. After we set up TWI functions we can use them to communicate with 24C16 EEPROM chip. This chip contains 2048 bytes of EEPROM memory in order to address all bytes 11 byte addressing is used. 24Cxx chips have four high bit fixed ID which his 0b1010 lower three bits are used for addressing chip memory. This way we avoid sending two bytes for memory addressing memory. But instead we need to split 11 bits in to fit three high bits that goes to device ID 1, 2, 3 bit locations while rest byte is sent next as normal address selection. Having this in mind we can implement EEPROM byte write function: uint8_t EEWriteByte(uint16_t u16addr, uint8_t u8data) {; //write byte to eeprom TWIWrite(u8data); if (TWIGetStatus() != 0x28) return ERROR; TWIStop(); return SUCCESS; } As you can see after each TWI command we check status. Status codes can be found on AVR datasheet. In case of communication failure we return ERROR. Using status codes may help to track bugs in program or detect hardware failures. Before writing byte to memory we first start I2C communication then we write device device address combined with three high memory address bits. Lowest device bit is “0” for write. Next byte we send is 8 lower memory address bits and then finally if we get ACK by checking status (0x18) we send data byte. Lastly we end communication by sending Stop signal. Reading requires a bit more code: uint8_t EEReadByte(uint16_t u16addr, uint8_t *u8data) { //uint8_t databyte;; //send start TWIStart(); if (TWIGetStatus() != 0x10) return ERROR; //select devise and send read bit TWIWrite((EEDEVADR)|((uint8_t)((u16addr & 0x0700)>>7))|1); if (TWIGetStatus() != 0x40) return ERROR; *u8data = TWIReadNACK(); if (TWIGetStatus() != 0x58) return ERROR; TWIStop(); return SUCCESS; } Because first we need to select memory address by writing device ID and rest of memory address as write command. Then after this we repeat START signal and then we send device address with read command (last bit set to “1”). If read status is OK we can store received data in to variable. For single byte we don’t need to send ACK signal just STOP. Similarly EEPROM page write and read are implemented. 24C16 is divided in to 128 pages of 16 bytes . Each page start address is located in high 7 bits of address. When writing page be sure to start from first byte of page because if page address reaches its end address rols-over and writing starts from beginning of page. This way you can overwrite existing data. I’m just giving my way of page write and read implementation: uint8_t EEWritePage; //write page to eeprom for (i=0; i<16; i++) { TWIWrite(*u8data++); if (TWIGetStatus() != 0x28) return ERROR; } TWIStop(); return SUCCESS; } uint8_t EEReadPage; //send start TWIStart(); if (TWIGetStatus() != 0x10) return ERROR; //select devise and send read bit TWIWrite(((EEDEVADR)|(u8paddr>>3))|1); if (TWIGetStatus() != 0x40) return ERROR; for (i=0; i<15; i++) { *u8data++ = TWIReadACK(); if (TWIGetStatus() != 0x50) return ERROR; } *u8data = TWIReadNACK(); if (TWIGetStatus() != 0x58) return ERROR; TWIStop(); return SUCCESS; } As you can see when receiving multiple bytes ACK must e generated after each reception. Juster after final byte ACK is not needed. In main program you can see EEPROM testing routines that shows everything is working correctly. Test routine checks single byte write to custom address location and then reading. In terminal screen you can view if written and read results are same. Also a page write test is done. It writes 16 bytes of information to page 5 and then reads them to different buffer. Then write and read buffers are compared and if both are equal – a success message is displayed in terminal screen. Main program: #include <stdio.h> #include <avr/io.h> #include <avr/pgmspace.h> #include "usart.h" #include "ee24c16.h" //set stream pointer FILE usart0_str = FDEV_SETUP_STREAM(USART0SendByte, USART0ReceiveByte, _FDEV_SETUP_RW); int main(void) { uint8_t u8ebyte; uint8_t u8erbyte; uint16_t u16eaddress = 0x07F0; uint8_t page = 5; uint8_t i; uint8_t eereadpage[16]; uint8_t eewritepage[16] = { 10, 44, 255, 46, 80, 87, 43, 130, 210, 23, 1, 58, 46, 150, 12, 46 }; //Initialize USART0 USART0Init(); // TWIInit(); //assign our stream to standard I/O streams stdin=stdout=&usart0_str; printf("\nWrite byte %#04x to eeprom address %#04x", 0x58, u16eaddress); if (EEWriteByte(u16eaddress, 0x58) != ERROR) { printf_P(PSTR("\nRead byte From eeprom")); if (EEReadByte(u16eaddress, &u8ebyte) != ERROR) { printf("\n*%#04x = %#04x", u16eaddress, u8ebyte); } else printf_P(PSTR("\nStatus fail!")); } else printf_P(PSTR("\nStatus fail!")); printf_P(PSTR("\nWriting 16 bytes to page 5 ")); if(EEWritePage(page, eewritepage) != ERROR) { printf_P(PSTR("\nReading 16 bytes from page 5 ")); if (EEReadPage(page, eereadpage) != ERROR) { //compare send and read buffers for (i=0; i<16; i++) { if (eereadpage[i] != eewritepage[i]) { break; } else continue; } if (i==16) printf_P(PSTR("\nPage write and read success!")); else printf_P(PSTR("\nPage write and read fail!")); } else printf_P(PSTR("\nStatus fail!")); }else printf_P(PSTR("\nStatus fail!")); printf_P(PSTR("\nContinue testing EEPROM from terminal!")); while(1) { printf("\nEnter EEPROM address to write (MAX = %u): ", EEMAXADDR); scanf("%u",&u16eaddress); printf("Enter data to write to EEPROM at address %u: ", u16eaddress); scanf("%u",&u8ebyte); printf_P(PSTR("\nWriting...")); EEWriteByte(u16eaddress, u8ebyte); printf_P(PSTR("\nTesting...")); if (EEReadByte(u16eaddress, &u8erbyte) !=ERROR) { if (u8ebyte==u8erbyte) printf_P(PSTR("\nSuccess!")); else printf_P(PSTR("\nFail!")); } else printf_P(PSTR("\nStatus fail!")); //TODO:: Please write your application code } } You can play around by sending data bytes to custom address locations from terminal screen and test various data memory locations. AVR Studio 5 project files for download [I2CEE.zip]. Have fun! AVR studio 5 can’t seem to understand your project? What am I doing wrong I wonder? This project was created with Avr Studio 5.1 so AVR Studio 5.0 won’t understand it. Upgrade studio to latest release or simply create new project and import existing source files. Done deed. Compiled perfectly on 5.1. Hello, I like your code, it is fine, but what is the ERROR function, how does it to implement? and what will happens in the loops while if the response never done? thanks Really simple and easy tutorial on AVR I2C. Thanks! How to select SCL frequency of atmega 8? For interfacing with ds1307? I have a board (with ATMega328) where only MISO/MOSI pins are broken out. Is it possible to configure TWI to use those two pins? Or would i have to do “software”/bitbang TWI on these? The only option is to use software TWI library. You can find few good libraries by googling. For instance the first that pops out: void TWI_stop(void) { TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO); while (TWCR & (1<<TWST! thanks for tutorial. but what’s EEDEVADR? EEDEVADR is EEPROM chip address on I2C line. In this example: #define EEDEVADR 0b10100000 ;Sample_I2C.asm .dseg .DEF uartChar = r1 ; Storage for character received from UART .DEF tempReg = r21 ; for temp purpose ; TSWR response for Acknowledgement from slave .equ I2C_SLA_W = 0×04 .equ I2C_START = 0×08 .equ MT_SLA_ACK = 0×18 .equ MT_DATA_ACK = 0×28 ;********************************************** ; IRQ TABLE ;********************************************** .cseg .org 0×0000 ; irq table rjmp main ; Reset Handler ; IRQ TABLE IS UPTO 0X3C .org 0×40 ;*********************************************** ; Main Function For Program ;*********************************************** main: ldi tempReg, 0×73 ; op port for DMX > 01110011 out DDRC, tempReg ; Set PORTC 0.4 AND 0.5 to 1 To enable DMX in Transmitter Mode out PORTC, tempReg ; 0.0 > SCL and 0.1 SDA ldi tempReg, 0xF0 ; op port for LED out DDRD, tempReg ; USART0 and USART1 in out PORTD, tempReg MainProgram: call i2cInit call i2cStart sbi PORTD, 4 call i2cAddressSlave ldi tempReg, ‘J’ mov uartChar, tempReg call i2CDataTransfer sbi PORTD, 5 ldi tempReg, ‘A’ mov uartChar, tempReg call i2CDataTransfer ldi tempReg, ‘S’ mov uartChar, tempReg call i2CDataTransfer call i2cStop MainProgramEnd: rjmp MainProgram ;*******************************Initialization of I2C************************************* i2cInit: ldi tempReg, 0×00 sts TWSR, tempReg ldi tempReg, 0x0C sts TWBR, tempReg ldi tempReg, (1<<TWEN) sts TWCR, tempReg ret waitForStartSend: lds tempReg,TWCR ; Wait for TWINT Flag set. This indicates sbrc tempReg,TWINT ; that the START condition has been transmitted rjmp waitForStartSend ; if TWINT flag is set lds tempReg,TWSR ; Check value of TWI Status Register. andi tempReg, 0xF8 ; Mask prescaler bits. cpi tempReg, I2C_START ; If status different from START (0×08) go to ERROR brne ERROR ; Set LED on PORTD0.5 as error signal and terminate I2C ret ;******************************************************* i2cAddressSlave: ;CR waitForSlaveAddrSend: lds tempReg,TWCR ; and ACK/NACK has been received. sbrc tempReg,TWINT ; Wait for TWINT Flag set. rjmp waitForSlaveAddrSend waitForDataSend: lds tempReg, TWCR ; This indicates that the DATA has been transmitted, sbrc tempReg, TWINT ; and ACK/NACK has been received. rjmp waitForDataSend lds tempReg,TWSR ; Check value of TWI Status Register. andi tempReg, 0xF8 ; Mask prescaler bits. cpi tempReg, MT_DATA_ACK ; If status different from MT_DATA_ACK = ; 0×28 go to ERROR brne ERROR ret ;******************************************************* i2cStop: ldi tempReg, (1<<TWINT)|(1<<TWEN)|(1<<TWSTO) ;Transmit STOP condition sts TWCR, tempReg ret ;******************************************************* ERROR: call i2cStop clr tempReg out PORTD, tempReg rjmp MainProgramEnd ;******************************************************* Hello! I have been programming MK ATmega16A. Seven-segment LEDs is controlled via I2C chips on FCA8574AT. I am a new in this area, help with this please !!! Thank god i found this.Thank you very much for writing these codes. Very good tutorial.Thank you. how can I know the status from the bits in the TWSR ?? for example if I get 0x08 status what does this mean ?!? caegkkeebabkaeee What is an ERROR() function? It is to be called if required status is not received. But what does it actually do? And it is not available in atmel studio 6.2. Tell me how to use it? Those are constants (status codes returned by fuctions) defined in ee24c16.h e.g. #define ERROR 1 #define SUCCESS (!ERROR) Where is define ERROR ? in AVR Studio 5 project files in ee24c16.h [I2CEE.zip]. Nice article on I2C. Thank you very much for this demo 🙂
https://embedds.com/programming-avr-i2c-interface/
CC-MAIN-2018-09
refinedweb
2,704
66.03
(This articles has already been posted in. Now I post it again in my own blog.) Introduction I am very sure that most of us have been familiar with NewForm.aspx from Sharepoint. That kind of submission form by Sharepoint is a template, which is then populated based on columns definition of a list. So we can have date field, number field etc., depends on columns definition.Surprisingly, that form is made by some JavaScript object. (Figure-1). Typically creating text field is not a problem but not with date field. Usually we need to allocate special effort for date field – either by creating new custom control or create some JavaScript for the date chooser. However if we could re-use date field object from Sharepoint – then the job can be done faster. So let’s start to figure out how! Sharepoint WebControl One of Microsoft.Sharepoint namespaces that rarely been talked about is Microsoft.Sharepoint.WebControl. Most of the controls in this namespace are derived from System.Web.UI.Control class – which is the base class for the controls in a web page. I will not discuss all controls but our interest is the OWS* control. There are 5 OWS* control in this namespace : – OWSForm – OWSControl o OWSDateField o OWSNumberField o OWSSubmitButton Look at the order! The OWSForm is container for OWSControl – a base class for the other OWS*Field and OWSSubmitButton. Basically the OWSForm is responsible to create form and OWS*Fields are the input definition. OWSSubmitButton is then create relevant submit action for specific OWSForm. Reusing OWS Control Let’s the creating webpart task leaves behind – because many examples around the web. We will focus our discussion on how to use the OWSControl. First, remember the order ! If you need to use any of OWS*Field control then the container (OWSForm) must exist. You can create OWSForm object by calling OWSForm owsForm = new OWSForm(); this.Controls.Add(owsForm); and the OWSDateField objectby calling OWSDateField dateFld = new OWSDateField(); Second, always submit the OWSForm When the values need to be submitted – we must make sure that we submit the correct form. The easiest way is using OWSSubmitButton, because it will create relevant submit script for that control. OWSSubmitButton submitBtn = new OWSSubmitButton(); Third, add everything to the containers The next step is to add all child components to the container, owsForm.Controls.Add(dateFld); owsForm.Controls.Add(submitBtn); Although you can directly add OWS*Field to the WebPart control – but it’s not suggested as you disobey the hierarchy. You can also layout the components before adding them to the containers. Last, OWS*Field.Value is not the value you expect OWS*Field has Value property – but believe me that it is not the value you’re expecting. Since OWS Control render javascript, then everything you need to capture is throughout Page.Request.Params. The Value property is the way you maintain viewing aspect of the users (same with EnableViewState = true in common controls). So, you can get the correct value using Page.Request.Params[dateFld.UniqueID]; Since you need to have control’s UniqueID then you MUST PUT THE LAST STATEMENT after all controls has been added to it parent! dateFld.Value = Page.Request.Params[dateFld.UniqueID] will create same effect as EnableViewState = true. Summary To use OWS Control we need OWSForm as containers and follow the hierarchy to build it up in webpart. redirects me to the webparts maintenance page Sridhar Bommana: When you start a new webpart project, its better to create simple “Hello World” text webpart. After successfull insertion in Sharepoint webpart pages, you can continue the project with real logic. You can also use try … catch block, so you won’t missed the error message. hey Sridhar, cannu send me whole code of the above webpart i want to use datefiled. u can send me code [email protected] thanks in advance
https://blog.libinuko.com/2006/07/29/sharepoint-webcontrol-part-i-reusing-ows-controls-in-custom-webpart/
CC-MAIN-2019-13
refinedweb
646
57.27
hurry.jquery 1.4.3.1 fanstatic style resources for jQuery. hurry.jquery Introduction This library packages jQuery for hurry.resource. It is aware of jQuery's structure and different modes (normal, minified). How to use? You can import jQuery from hurry.jquery and .need it where you want these resources to be included on a page: from hurry.jquery import jquery .. in your page or widget rendering code, somewhere .. jquery.need() This requires integration between your web framework and hurry.resource, and making sure that the original resources (shipped in the jquery-build directory in hurry.jquery) before release This section is only relevant to release managers of hurry.jquery..4.3.1 (2010-10-18) - Using jQuery-1.4.3. 1.4.2.3 (2010-07-28) - We needed to do some safety checks in the zest.releaser entry points as otherwise these entry points would be triggered even for the release process of packages that depend on this (such as hurry.jqueryui). 1.4.2.2 (2010-07-28) - Relying on new hurry.resource 0.10, which needs an entry point. - Export jquery_lib as the library. Before this change library was not accessible as it was immediately overwritten by the jquery ResourceInclusion. This means that jquery resources will now be published under jquery_lib in the URL instead of jquery, but since these URLs are automatically generated this should be okay. 1.4.2.1 (2010-03-14) - Using jQuery-1.4.2. - Added zest.releaser and using its prerelease-entrypoint to assure download of the jquery libary before release. No functional changes. 1.3.2.1 (2009-05-27) - Initial public release, using jQuery-1.3.2. Download - Author: Jan-Wijbrand Kolman - License: ZPL 2.1 - Package Index Owner: jw, trollfot, faassen, kagesenshi - DOAP record: hurry.jquery-1.4.3.1.xml
http://pypi.python.org/pypi/hurry.jquery/1.4.3.1
crawl-003
refinedweb
305
61.63
3 Cd Set: The Very Best Of Blue Note Jazz For Sale I am a private seller looking to give these CD's a better home. EXCELLENT (like new) CONDITION. Packed for shipping this set weighsabout1 lbs so when Paypal confirms your payment, I'll ship ASAP via USPS Media Mail. If actual S&H is less than estimated, I'll refund the difference back to your Paypal account. Of course if you're not completely satisfied with your purchase, no explanations necessary, I'll provide a full refund to your postpaid return (within 2 weeks please). Best regards from JANS ATTIC 3-CD SET (1994 CEMA S23-18038) This item has been shown 0 times. 3 Cd Set: The Very Best Of Blue Note Jazz: $10 ><<
http://www.holidays.net/store/3-CD-set-The-Very-Best-of-BLUE-NOTE-JAZZ_291120199848.html
CC-MAIN-2015-35
refinedweb
127
71.14
The previous section discussed embedded and linked files. When you create an assembly, the manifest informs the Common Language Runtime of all dependent files. If you want to make sure that a specific icon, image, text file, or whatever file you need, is considered a necessary part of your application, you can make it a part of your assembly. There are two ways to make a file part of your assembly. You can either embed the file directly into the assembly, or you can make the assembly refer to the file via the manifest. When using Visual Studio .NET, it is actually quite easy to create embedded resources, so that's what will be covered in this next section. Keep in mind that you can store absolutely anything as an embedded resource. Neither Visual Studio .NET nor the Common Language Runtime cares what information you're storing. Whenever you get a resource out of a loaded assembly, you get it as a stream (part of System.IO). This stream can contain any kind of data, including binary data for images, text data for XML, culture-specific string tables, and much more. For this example, assume that you've decided that you want to add some kind of read-only set of data to your assembly. Perhaps you want to store a table of ZIP Code and county lookups, state names, or any other kind of large set of read-only data that you want to distribute with your application but you don't want to expose in some accessible format, such as Access or Excel. Add a new item to the AssemblyIntro project, select XML File, and call it EmbeddedData.xml. Set its contents to the following: <?xml version="1.0" encoding="utf-8" ?> <EmbeddedData> <DataNode > <DataValue>This is a data value</DataValue> </DataNode> <DataNode > <DataValue>This is another data value</DataValue> </DataNode> </EmbeddedData> In that file's properties panel, set the build action to Embedded Resource. This instructs Visual Studio .NET to compile the file directly into the assembly. This is extremely important because if the file is not marked as an embedded resource, it will not be linked and will not appear in the compiled assembly. To get at the embedded data, you need to make use of some more reflection. Listing 12.3 shows the new AssemblyTool class and a new method, GeTDataNodeValue, to retrieve data nodes from the preceding XML. using System; using System.IO; using System.Xml; using System.Reflection; using System.Text; namespace SAMS.CSharpUnleashed.Chapter12.AssemblyIntro { /// <summary> /// This is the AssemblyTool sample class /// </summary> public class AssemblyTool {"; } } } The first new method, LoadEmbeddedDoc, uses GetManifestResourceStream to obtain a stream for the embedded XML document. Remember this method because you'll use it nearly every time you try to grab embedded data from an assembly. The second method, GeTDataNodeValue, first checks to see whether XmlDocument is null. TIP Reflection operations are typically very costly in terms of time and processor consumption. If at all possible, store the results of reflection operations to avoid repetitive and redundant calls. In this case, the XML document is cached so that throughout the lifetime of the application process, the reflection operation is performed only once. If the document is null, the LoadEmbeddedDoc method is invoked. Then some XPath is used to find the appropriate DataNode element and return its value. Add the following few lines of test code to the main class to exercise the new code sections: Console.WriteLine( AssemblyTool.GetDataNodeValue(21) ); Console.WriteLine( AssemblyTool.GetDataNodeValue(35) ); Console.WriteLine( AssemblyTool.GetDataNodeValue(50) ); Build the application again and run it, and you should see the following three new lines of text: This is a data value This is another data value No node found You might be wondering how this might actually be useful for you. If you are thinking about monolithic applications or large installs on DVD-ROMs, it might not seem all that useful. However, the situation changes if you think modular. In a situation in which your application relies on data embedded in an assembly and your application is configured for dynamic updates from the Internet, you can easily imagine a scenario where you could simply make changes to the embedded XML (or text files, or images, or language-specific strings, and so on) and they would propagate to your application (be it web-based or Windows-based) seamlessly. XML resources can also expose to other applications complex data structures to allow for in-depth processing, such as exposing an identity to an application that supports plug-ins (creating plug-ins will be covered at the end of this chapter).
https://flylib.com/books/en/1.238.1.91/1/
CC-MAIN-2022-05
refinedweb
774
53.41
Your Java-coded application can embed the Jython interpreter in order to use Jython for scripting. jython.jar must be in your Java CLASSPATH. Your Java code must import org.python.core.* and org.python.util.* in order to access Jython’s classes. To initialize Jython’s state and instantiate an interpreter, use the Java statements: PySystemState.initialize( ); PythonInterpreter interp = new PythonInterpreter( ); Jython also supplies several advanced overloads of this method and constructor in order to let you determine in detail how PySystemState Java classes in order to access your application’s functionality. Your Java code can set attributes in the interpreter namespace by calling overloads of interp .set, and get attributes from the interpreter namespace by calling overloads of interp .get. The methods’ overloads give you a ... No credit card required
https://www.safaribooksonline.com/library/view/python-in-a/0596001886/ch25s02.html
CC-MAIN-2018-17
refinedweb
132
50.63
The Windows Phone Bing Maps Silverlight control is almost, but not quite, identical to the desktop control. We take a look at using it and some of the ways that it differs. Mapping is a common requirement for a mobile app and now it is easy to add mapping, even custom mapping, to a mobile application using the Bing Silverlight control. It is important to realise that you have two distinct ways to use Bing Maps in your app. The original Javascript/Ajax control is supported and you can use this in a Web application or you can embed a browser control within your app and access it in the same way. However the Silverlight control has a lot going for it and it is much easier to integrate it into the logic of your app rather than having to write Javascript to make it all work. To make use of the Siverlight Bing Maps control you have to download the lasted edition of the Windows Phone Tools. This is a good idea anyway as you can't submit apps to the app store using an older version. To try it out start Visual Studio and create a new Windows Phone Silverlight application. To add the Bing Maps Control to your project simply use the Toolbox and drag-and-drop and resize the map using the designer. Notice that the Windows Phone Map control and the desktop map control are different and they have a different namespace. The designer adds the line: xmlns:my="clr-namespace:Microsoft. Phone.Controls.Maps; assembly=Microsoft.Phone.Controls.Maps" so you can refer to the control with the prefix my. The generated XAML map tag is something like: <my:Map As soon as you add the map tag the designer displays a default map view. You can't interact or use the map facilities in the designer - it just acts as a placeholder. The map in the designer If you now run the program you will discover that a map appears but then a message to say that you have invalid credentials appears. <my:Map where, of course you replace KEY with your real Bing Maps key. If you now run the application you will see the same map but now you should be able to interact with it using the zoom, pan and all of the other default tools. You don't have to use XAML - ever. XAML is just an object instantiation and property initialisation language. Anything you can do in XAML you can do in code and it's often a good idea to see how things are done without XAML. First you need to add: using Microsoft.Phone.Controls.Maps; using Microsoft.Phone.Controls.Maps; to the start of the code file.so that you can refer to map classes using short names. In the button's click handler you first create the map object: private void button1_Click( object sender, RoutedEventArgs e){ Map map = new Map(); Next you set the credentials: map.CredentialsProvider = new ApplicationIdCredentialsProvider( "KEY"); and as before you have to replace KEY with your Bing Maps key. Now we can add the map object to the Grid's Children collection so that it displays: LayoutRoot.Children.Add(map);} This is all that we need and if you run this program you will see the default map as before. <ASIN:0470886595> <ASIN:1449388361> <ASIN:0735643350> <ASIN:1430233060> <ASIN:1430234105>
http://i-programmer.info/programming/mobile/1357-windows-phone-7-the-bing-maps-control.html
CC-MAIN-2014-35
refinedweb
570
70.33
.NET to Ruby: Methods and Variables. First we’ll go through how to create and call methods, then we’ll look at Blocks and some application of blocks, and we’ll finish up by going through the types of variables that exist within Ruby. As always we’ll actually be comparing Ruby to C#, because .NET is a framework not a language. Methods Ruby methods are quite easy – especially since there is no type system to worry about, which allows us to skip defining parameter types, and method return types. Methods in ruby are written using the def keyword to start the method definition, and they are closed using the end keyword, like this: def a_method() # this is a Ruby method end This is very different from a .NET method which would look like this: public void AMethod() { // this is a C# method } When using method parameters you write them inside the brackets and separate them with commas: def a_method(a, b, c) # this method has three parameters a, b, and c end As stated in the previous post on Ruby Classes, since Ruby is duck typed you don’t have to declare the data types of your parameters within your method definitions. Compare that with .NET: private void AMethod(int a, int b, int c) { // this method has three parameters: // an integer a, an integer b, and an integer c } The difference between these two pieces of code is the amount of characters that need to be written. Ruby is known as a terse language, and small method definitions are clearly one of the things that make Ruby so terse. Moving along, let’s look at one of Ruby’s more obscure syntaxes. Something you might see in code are methods defined without brackets – gasp! def a_method a, b, c # this method also has three parameters a, b, and c end This is perfectly valid syntax, and you can use it in your own code. Let’s back track and rewrite our first example using this syntax: def a_method # No brackets here end So you can see Ruby’s methods differ substantially from .NET’s. But before I release some cowboy coders onto the world it’s important that I tell you about accepted community practice, which is: when defining methods omit brackets for methods without parameters, and use the brackets when your methods have parameters. Let’s move on to method calls. They look the same as .NET method calls too, and they can be done without brackets as well: AMethod(1, 2, 3); a_method(1, 2, 3) a_method 1, 2, 3 All of the above lines of code call a_method with the arguments 1, 2, 3. Now that we’re done with creating, and calling methods, lets get into some of the interesting aspects of methods that C# lacks in, and where Ruby shines. Blocks We’ll start with blocks. Blocks are defined using either curly braces or between the do and end keywords: { puts "A Block" } do puts "also a block" end Conceptually blocks are like lambda’s in C#, they can be passed into a method and then executed from within that method’s context. This is done using yield: def a_method puts "begin" yield puts "end" end a_method { puts "block code" } Which outputs: begin block code end And just like methods, blocks can accept variables into them. This is done using the pipe character to delimit the variable name like this: def a_method yield("George") end a_method { |name| puts name } #=> George The equivalent code in C# would look like this: public static void a_method(Action<string> block) { block("George"); } a_method((name) => System.Console.WriteLine(name)); Blocks are used heavily in Ruby, and they allow us to implement some neat features, such as C#’s using statement. For example here’s some code to write to a file in C#: using (StreamWriter file = new StreamWriter(@"Output.txt")) { file.WriteLine("Line 1"); } This code opens the file Output.txt, then writes “Line 1n” to the file, and finally closes the file handle. Ruby is capable of the same thing, but instead uses blocks to do it: File.open("Output.txt", "w") do |file| file.write "Line 1" end Pretty neat isn’t it!? In the above code, file is a variable reference to the IO object created by File.open. I’ll admit that Ruby’s block syntax is a little more cryptic than C#’s syntax, since with C# you need to be explicit about your usage. This is will be a small hurdle for you to overcome when learning Ruby. There are many more powerful applications for blocks. Take for example Sinatra. Sinatra uses blocks to create a DSL (Domain Specific Language) for it’s URL routing. Sinatra’s Hello World! example looks like this: get '/hello' do 'hello world' end In the above example, get is simply a method call with a block attached to the end of it. This makes routes super easy to write in Sinatra, and makes the code very easy to read, while still remaining expressive in it’s functionality. RubySource has a four part series on Sinatra that’s worth a look at too! Ultimately blocks are really just an implementation of the strategy pattern that is built into the Ruby language. And because blocks are so easy to write they get used extensively when Rubyists write their code. Variables Moving on from blocks, let’s focus the rest of this post on the most basic item of a Ruby program, the variable. Local variables are variables that you’d write in your Ruby methods are written like this: a_variable = 2 The equivalent code in C#: var a_variable = 2; Again there is no need to tell Ruby what your variable type is. Ruby figures it out on it’s own, which makes variable syntax just as terse as method syntax. Ruby variables use a naming convention called snake case. So instead of using capital letters like .NET does to distinguish between words in a variable you should use underscores. The variables below are valid variable names: variable a_variable a_really_big_variable_name The variables below are still valid Ruby variables, but they break Ruby’s naming convention, so they shouldn’t be used. Variable A_Variable areallybigvariablename When writing classes, Ruby has some special notation to distinguish between local variables and instance variables. Instance variables are prefixed with the at symbol: @. This is significantly different that .NET so it’s worth comparing the two: public class Example { private int iv; public Example() { iv = 12; } } class Example def initialize @iv = 12 end end In both Example classes above, an instance variable iv is created within every instance of Example. In Ruby there is no explicit declaration of the variable @iv, instead by writing the assignment of 12 to @iv Ruby is smart enough to determine that @iv is your instance variable. On top of instance variables, Ruby also has another type of variables known as class variables. For those of you coming from the .NET world, this is the same as a static variable. To create a class variable you use a double at symbol: @@. The following code examples are equivalent: public class Example { private static int id = 42; public static int GetId() { return id; } } class Example @@id = 12 def self.get_id @@id end end As well, it’s worth mentioning that Ruby also has global variables. They are prefixed with a dollar sign: $. Global variables aren’t something you’re likely to come across as you start to learn Ruby, so I won’t enumerate the variables that exist, however Ruby User’s Guide has a list of global variables. And here is where we’ll draw this post to an end. By the end of this post you should be able to create methods, call methods, use blocks, and know of the 3 types of variables within Ruby. At this point if you’ve been following along in the series you have the basic building blocks to start coding your own Ruby programs. You’ve got an environment to work in, Classes to work with, and now Methods and Variables to build your routines. For the next article we’ll do a bit of Ruby house keeping and go through the tools you can use to keep your Ruby programs readable and maintainable for other Rubyists. We’ll touch on topics like Naming Conventions, Comments, Documention, and Namespacing, so be sure to check back for that post!
https://www.sitepoint.com/net-to-ruby-methods-and-variables/
CC-MAIN-2019-26
refinedweb
1,416
68.2
TI used to work this way, up to the aborted initial landing attempt last summer. This was cut and replaced with the discard-everything-on-GC strategy, mainly due to a ton of extra time taken during GC while condensing the constraints generated during TI/compilation. This was not a great design, and it shouldn't be hard to improve so that the compiler itself computes the condensed constraints (which don't refer to any temporary type sets), and jitcode-retaining purging can be done by just copying those condensed constraints and the contents of persistent type sets / objects into a new arena allocator. This would be helpful for pages with an enormous amount of code and memory used during analysis, e.g. bug 775994. Created attachment 647272 [details] [diff] [review] part 1 (090fd1585e34) This separates the freeze constraints added during compilation into implicit and explicit portions. All type sets which describe stack values (SSA values, locals, args) are implicitly frozen, and whenever they change the associated script (and anything it was inlined into) will be recompiled. Type sets for object properties must be explicitly frozen, along with constraints describing the properties or objects they are associated with. This split avoids the need for condensed constraints. Instead, when purging analysis-temporary we can just regenerate the implicit constraints for the stack from scratch, and copy over the freeze constraints for the heap and certain TI-generated constraints for property reads and call returns. I haven't benchmarked this patch but I doubt it affects ss/v8/kraken much. There is a potential for more recompilation but generally in oddball scenarios like arguments or 'this' which are never accessed at all. Of more concern is the effect on chunked compilation, as any change in the stack types for a script will cause all its jitcode to be discarded, not just that for chunks which used those types. That is not a huge problem I think: chunked compilation benefits more from incremental compilation than incremental discarding, and for code which is working on typed arrays (i.e. almost everything that benefits from chunked compilation) propagating types more eagerly should totally mitigate this issue. Will port that code over from bug 767223 in a future patch. Created attachment 647285 [details] [diff] [review] part 2 (previous) Propagate types more eagerly for reads from typed arrays and from singleton objects (globals) or objects where the property can be found on the prototype chain. Also, don't generate type constraints at all for accesses on typed arrays. Created attachment 647638 [details] [diff] [review] part 3 WIP (previous) Allow purging analysis-temporary outside of a GC. Currently this is only triggered via a new JS_GC_ZEAL setting, but jit-tests -mna pass when purging analysis state every 100 or 200 allocations. Next step is to stick in some heuristics and see how effective / performant this is on code-intensive demos. Created attachment 647951 [details] [diff] [review] part 3 WIP (previous) Trigger purging when a compartment's analysis-temporary is above N bytes after compiling (specified with PURGE_TRIGGER_BYTES env var). Also adds a bunch of spew. Without the spew, if I set the cap at 150MB then things run fine, 100MB is a little choppy, 50MB very choppy. 150MB saves about 300MB over peak memory usage, but I think we should be able to do better. Going through the spew I get for 100MB (will attach in a minute), 78% of the compilations being done are recompilations without any intervening GC. If this is right, these are almost all going to be due to changing type information, which shouldn't be happening for this typed array heavy code if part 2 is doing its job. So something still needs to be fixed, will investigate. If these recompilations are fixed, things should be in much better shape, with much less need for reanalysis as well and less purging. The number of analysis bytes after a purge is never above 30MB, so it might be possible to get a 50MB cap to work. Also of note is that 87% of the compilations being done are not in the first chunk of a script, and 49% of compilations are at chunk 20 or higher. So a lot of time is being spent in scripts which are very large, and chunked compilation will be important for IM on pages like this. It also seems like we only compile a few chunks out of these large scripts, e.g. 13 chunks out of a script with more than 600, and chunking things at the bytecode level will allow incremental analysis and compilation throughout the pipeline. Created attachment 647953 [details] analysis, compilation, purging details for a 100MB cap Spew when running the demo with a 100MB cap. Created attachment 648108 [details] [diff] [review] part 3 WIP (previous) Fix various issues that were triggering recompilations for no good reason, some due to this patch series and some outstanding. This wipes out nearly all of the recompilations, except for those triggered when inlining calls in hot scripts and after a GC. vs. the previous patch, with a 100MB cap I get 10218 compilations instead of 30329, and 24 purges vs. 65. The purges are still a little choppy --- they take about 50ms on my machine, about 30ms of which is freeing up the analysis arena in the foreground (moving this to the GC background thread should wipe this out, but the background thread needs a little refactoring first). This still has profiling spew in it, will post a clean patch in a few minutes. Created attachment 648110 [details] [diff] [review] analysis, compilation, purging details for a 100MB cap Update spew for the most recent patch. Created attachment 648134 [details] [diff] [review] part 3 WIP (previous) Patch with profiling spew removed. Vlad, if you want to check out how this behaves on the demo, go ahead. Various issues: - The demo does occasionally crash when accessing type objects, due to what looks like a dangling reference to the old type allocator. Haven't had time to debug this yet. - The default cap is 100MB, which can be changed with the PURGE_TRIGGER_BYTES env var or by hand editing js/src/methodjit/Compiler.cpp. The final patch will make this a config option I think. - Pauses from purging aren't logged anywhere, in the final patch they'll be logged to the console in the same way as GC timing info. (In reply to Brian Hackett (:bhackett) from comment #8) > - Pauses from purging aren't logged anywhere, in the final patch they'll be > logged to the console in the same way as GC timing info. It would also be nice to have telemetry for that, in a followup bug if you prefer. If you have it at the point where it is being logged to the console, anybody would be able to hook up the telemetry. Created attachment 649516 [details] [diff] [review] part 3 (previous) Created attachment 650738 [details] [diff] [review] part 3 (previous) Deeper restructuring of type information to greatly reduce the cost of analysis purges. On the demo, reduces the typical cost of purges for me from 50ms to 5ms. This is done by splitting a new analysisLifoAlloc off from typeLifoAlloc, where the former contains all script analysis data and is (nearly) totally cleared during analysis purges, and the latter contains retained type data about object properties etc. and is completely left alone during purges. FWIW, this patch series also seems to improve my startup times for the demo too, though I haven't measured anything. Potentially the savings from fewer page faults and swapping more than makes up for the cost of doing reanalysis.()). ::: js/src/frontend/BytecodeEmitter.cpp @@ +2642,5 @@ > return false; > + > + /* > + * Always end the script with a JSOP_STOP. Some other parts of the codebase > + * depend on this opcode, e.g. js_InternalInterpret. Good idea to put a comment here. Could you also include FrameRegs::setToEndOfScript as a less esoteric example? (In reply to Luke Wagner [:luke] from comment #12) >()). This would be fine to do, but better as a followup I think. part 3 changes this stuff again to a more operational typeset->constraintsPurged(). (In reply to Brian Hackett (:bhackett) from comment #13) Follow-ups don't get done. Let's introduce the code in a good state. Part 3 can build on it if it adds something else type-y. This is a pretty minor thing, and strongly asserted as is. It will be easier for me to do as a followup than to change an early patch in the series and need to rebase everything else top of it. Alright; so you'll include that patch in this bug? Yeah, I'll have it ready later today.? @@ +3975,5 @@ > + if (!script->hasFreezeConstraints) { > + /* > + * Freeze type sets for arguments, locals and monitored type sets. This > + * includes all type sets in the TypeScript except the script's return > + * value types. This comment explains what the code below does (which is pretty easy to see); it would be useful if the comment explained why and the general scheme being used. ::: js/src/jsinfer.h @@ +500,5 @@ > */ > bool needsBarrier(JSContext *cx); > > /* The type set is frozen if no barrier is needed. */ > bool propertyNeedsBarrier(JSContext *cx, jsid id); this can be removed (or, better, replaced with something that describes the query) Comment on attachment 647285 [details] [diff] [review] part 2 (previous) Review of attachment 647285 [details] [diff] [review]: ----------------------------------------------------------------- Looks good ::: js/src/jsinfer.cpp @@ +986,5 @@ > + return Type::UnknownType(); > + > + const Shape *shape = obj->nativeLookup(cx, id); > + if (shape && shape->hasDefaultGetter() && shape->hasSlot()) { > + Value v = obj->getSlot(shape->slot()); use HasDataProperty instead @@ +1039,5 @@ > + * of defined global variables or from the prototype of the object. This > + * reduces the need to monitor cold code as it first executes. > + */ > + if (!assign) { > + JSObject *singleton = object->singleton ? object->singleton : object->proto; So this code will eagerly merge in the type of any property on the proto chain into the type set of the get, ignoring the own properties of the object? Could you document that we are speculating that it is not common to shadow a prototype property with an own property of a different type? @@ +1040,5 @@ > + * reduces the need to monitor cold code as it first executes. > + */ > + if (!assign) { > + JSObject *singleton = object->singleton ? object->singleton : object->proto; > + if (singleton) { if (JSObject *singleton = ...) { LifoAlloc seems to be a twitch wrt performance. Your change makes sense; but can you split off those changes into a separate bug blocking this that I'll review quickly and we can land independently? Created attachment 651005 [details] [diff] [review] part 4 (previous) Subclass StackTypeSet and HeapTypeSet from TypeSet. All methods for adding a constraint on a type set (other than TypeSet::add(), which is only callable from jsinfer.cpp) are in one of these subclasses. Nicely, uses of the type sets partition such that no dynamic downcast methods are needed, and only a couple short methods are on both subclasses (e.g. addSubset). (In reply to Luke Wagner [:luke] from comment #18) >? This ties into the comment above TypeConstraintFreezeStack. TypeConstraintFreeze only applies to one compilation, so once a type is added that invalidates the compilation, no more invalidation is needed. (This is not actually necessary anymore given pierron's changes to how invalidation works, I'll remove it). TypeConstraintFreezeStack applies to all compilations of the script; any time type information within the script changes, all its jitcode is discarded. This means the constraint can fire multiple times, and shouldn't disable itself after the first time it invalidates any code. Comment on attachment 651005 [details] [diff] [review] part 4 (previous) Review of attachment 651005 [details] [diff] [review]: ----------------------------------------------------------------- Thanks! ::: js/src/jsanalyze.cpp @@ +291,3 @@ > } else { > JS_ASSERT(nTypeSets == UINT16_MAX); > + code->observedTypes = (types::StackTypeSet *) &typeArray[nTypeSets - 1]; Can you add a TypeSet::asStackTypeSet() { JS_ASSERT(isStack()); return this; } restricted assert and use it here to avoid the cast-hammer? ::: js/src/jsinfer.h @@ +449,5 @@ > +{ > + public: > + > + /* > + * Make an type set with the specified debugging name, not embedded in a ::: js/src/jsinferinlines.h @@ +595,4 @@ > TypeScript::SlotTypes(JSScript *script, unsigned slot) > { > JS_ASSERT(slot < js::analyze::TotalSlots(script)); > + return (StackTypeSet *) script->types->typeArray() + script->nTypeSets + slot; Ditto above for all these above C-style casts. Comment on attachment 650738 [details] [diff] [review] part 3 (previous) Review of attachment 650738 [details] [diff] [review]: ----------------------------------------------------------------- This approach is pretty nice; I like that you set it up so that you can basically just clear one LifoAlloc.)? ::: js/src/jsanalyze.h @@ +610,5 @@ > + Lifetime *lifetimes; > + }; > + > + LifetimeVariable *variables() { > + return (LifetimeVariable *) this; Could this be variable(size_t i) { JS_ASSERT(i < ... some length); return ((LifetimeVariable *)this)[i]; } ? ::: js/src/jsinfer.cpp @@ +1910,5 @@ > + } > +#endif > + > + if (!jitsOK) > + cx->compartment->types.addPendingRecompile(cx, script, pc);. @@ +6070,5 @@ > + AutoEnterTypeInference enter(cx); > + > + uint64_t start = PRMJ_Now(); > + > + /* Make sure all JITScripts have a ScriptLiveness attached for GC compat. */ "GC compat" is rather mysterious... ::: js/src/jsinfer.h @@ +425,3 @@ > > + bool purged() { return !!(flags & TYPE_FLAG_PURGED); } > + void setPurged() { flags |= TYPE_FLAG_PURGED | TYPE_FLAG_CONSTRAINTS_PURGED; } I think isStack()/TYPE_FLAG_STACK was a better name (and matches StackTypeSet better in the next patch). ::: js/src/jsinferinlines.h @@ +1357,5 @@ > + */ > + unsigned count = getPropertyCount(); > + for (unsigned i = 0; i < count; i++) { > + Property *prop = getProperty(i); > + if (prop) if (Property *prop = ...) ::: js/src/methodjit/Compiler.cpp @@ +337,5 @@ > okay = false; > break; > } > > + types::TypeSet::WatchObjectStateChange(cx, fun->getType(cx)); Could you comment as to why this is necessary? @@ +485,5 @@ > mjit::Compiler::performCompilation() > { > + char buf[100]; > + snprintf(buf, sizeof(buf), "performCompilation:%d,%d,%d", > + (int) isConstructing, (int) cx->compartment->needsBarrier(), (int) chunkIndex); rm @@ +1003,5 @@ > status = cc.compile(); > } > > + /* Check if we have hit the threshold for purging analysis data. */ > + cx->compartment->types.maybePurgeAnalysis(cx); It seems strange to put this in the jit. Is there a more natural place to put it? E.g., the !compartment->activeInference branch of ~AutoEnterTypeInference comes to mind. ::: js/src/methodjit/Compiler.h @@ +430,5 @@ > js::Vector<DoublePatch, 16, CompilerAllocPolicy> doubleList; > js::Vector<JSObject*, 0, CompilerAllocPolicy> rootedTemplates; > js::Vector<RegExpShared*, 0, CompilerAllocPolicy> rootedRegExps; > + js::Vector<uint32_t> monitoredBytecodes; > + js::Vector<uint32_t> typeBarrierBytecodes; Can you write a comment explaining what these lists mean and what should/shouldn't be added? ::: js/src/methodjit/MethodJIT.h @@ +679,5 @@ > js::mjit::CallSite *callSites() const; > JSObject **rootedTemplates() const; > RegExpShared **rootedRegExps() const; > + uint32_t *monitoredBytecodes() const; > + uint32_t *typeBarrierBytecodes() const; Needs a comment explaining how it is used and what all needs to be included. ::: js/src/vm/Stack.cpp @@ +649,5 @@ > + > + if (analysis && !analysis->ranLifetimes()) > + analysis = NULL; > + > + JS_ASSERT(analysis || liveness); This whole blob could use a comment as, on first glance, what is happening is non-obvious. It's rather weird that we have these two representations of liveness; one might naively hope that was only 1. Is the reason that most analyzed scripts will live and die without getting purged and therefore the ScriptLiveness::create call would usually be a waste? Also, will ScriptLiveness go away with the recent bug filed about flushing everything to the stack so GC doesn't need liveness info (can't find bug # atm)? If 'yes' to the above: can we name it something gross like PurgedScriptGCLiveness/JITScript::purgedScriptGCLiveness to make this all more clear and discourage other uses from popping up? Also, how much memory, after purging (in say the demo) is spent on ScriptLiveness? (In reply to Luke Wagner [:luke] from comment #24) >)? I haven't seen any website besides this demo which uses enough analysis memory to need purging at the default 100MB point. Per comment 11 purges are about 5ms each, and I get about 10 when running the demo. I instrumented the demo with times in analysis phases / compilation and get this before and after the entire patch series. Numbers are total ms. Before: analyzeBytecode: 3320 analyzeLifetimes: 254 analyzeSSA: 2936 analyzeTypes: 5979 performCompilation: 19608 After: analyzeBytecode: 2903 analyzeLifetimes: 587 analyzeSSA: 2308 analyzeTypes: 2109 performCompilation: 3550 I suspect much of the difference in performCompilation is due to the changes made to reduce recompilations, but the amount of time spent in other phases has improved significantly. Even with the patch series applied, performance is better with a 100MB purge threshold than a much higher one. >? I wanted to do this, but this approach doesn't work out with the analysis design. The opcodes which have type barriers and/or are monitored depends on type information, and are determined during inference.type analysis. If we reanalyze the types in a script, we would need to know that the opcodes being monitored/barriered are the same as in the previous incarnation of the type information, which we can't know because type information may have changed since the last time the script was analyzed. > @@ . Eh, we pattern match bytecode in plenty of places, and for stupider reasons (s/RegExp.exec/RegExp.test/). Performance isn't intolerable without this, but this cuts a fair number of recompilations and it doesn't make sense to leave the gain on the table. int32 coercions generated by autotranslators are easy enough to pattern match. > It seems strange to put this in the jit. Is there a more natural place to > put it? E.g., the !compartment->activeInference branch of > ~AutoEnterTypeInference comes to mind. We do this a bunch, every time type information is queried or changed, and checking whether to purge requires counting the number of bytes in the allocator. > Also, will ScriptLiveness go away with the recent bug filed about flushing > everything to the stack so GC doesn't need liveness info (can't find bug # > atm)? Yeah, this would go away with bug 781657. The complexity cost here is the only really significant one, we still don't create that much jitcode and liveness info is much smaller. (In reply to Brian Hackett (:bhackett) from comment #25) > We do this a bunch, every time type information is queried or changed, and > checking whether to purge requires counting the number of bytes in the > allocator. There is no other good pinch point for catching analysis-purge in analysis? If not, file a bug to make sure we add maybePurge to IM in the right place. Comment on attachment 650738 [details] [diff] [review] part 3 (previous) There were several other changes requested. I see a bunch of nits and requests for comments. I can incorporate those into the finished push without needing a review, right? Can you explain specifically what you are looking for? Comment on attachment 650738 [details] [diff] [review] part 3 (previous) Oops, I thought there was something else outstanding. Landing this with purging disabled (see TypeCompartment::maybePurgeAnalysis) until bug 781657 lands. See bug 781657 comment 5. Backed out for talos crashes: Ack, didn't show up with a -t none try run. TypeSet::addTypesToConstraint didn't cope correctly with the case when the constraint triggered type changes on the original type set. This caused a bunch of Talos metrics to jump in various directions, fwiw (SunSpider 0.9.1 regression, V8 version 7 improvement, V8 regression, all on Mac): FWIW, it appears this may have caused some significant regressions on AWFY as well. Link? I didn't see any difference on benchmarks when testing this. I'm looking at the 64-bit MBP numbers on AWFY. Something between revs f27460e427cc and 9209d9af04d4 caused a regression on V8. There are also some clear differences in the "Assorted Tests". I cannot say, for sure, that any of these regressions were caused by this bug (so I apologize if this bug isn't the culprit), but something in the range certainly changed things. I do not have the ability to bisect. I bisected the AWFY regression to this patch. I can reproduce it in the shell, the easiest way is running v8/run-richards.js which regresses from a score of 9900-10000 to 9500-9800. The tree is closed right now but this should be backed out once it's reopened. We probably should, but please make sure that we consider & balance that regression against the huge memory usage win (which we don't really track/report on!).. (In reply to Brian Hackett (:bhackett) from comment #40) >. richards was an example of how to reproduce a regression. In fact, this regressed the following benchmarks on AWFY: SunSpider: crypto-aes bitops-bits-in-byte 3d-raytrace V8: deltablue raytrace richards Kraken: beat-detection crypto-ccm crypto-sha256-iterative We need to back this out before it's too late - we've been down *that* road before very recently (see: 7/24 e-mail from Dave). I'll test this in-browser shortly, I guess. Created attachment 655255 [details] [diff] [review] partial revert of part 1 (1bc0e4eac6e5) This partially reverts the changes in part 1 so that freeze constraints generated during compilation remain the same as before; implicit freezing of all stack contents only occurs after a compartment's analysis data has been purged. If anyone can reproduce an in-browser regression it would be good to check if this patch fixes it. Putting this up as I was working on this for bug 785358 before realizing the problem was something else. Would rather not commit this if no one can confirm it helps anything, as it adds back some complexity I'd been hoping to remove.
https://bugzilla.mozilla.org/show_bug.cgi?id=778724
CC-MAIN-2017-22
refinedweb
3,519
52.8
The #1 Python tool for miscellaneous emoji info Project description emoji-search The #1 Python tool for miscellaneous emoji info Installation With Python installed, simply run the following command to add the package to your project. pip install emoji-search Usage The following is an example usage of the package: from random import choice from emoji import Emoji, categories, search, category def random_emoji() -> Emoji: return search(choice(category(choice(categories)))) print(random_emoji()) 🤯 You can also run the tool from the command-line: usage: emoji-search [-h] [--search SEARCH | --category CATEGORY | --categories | --palette] Search for emoji information optional arguments: -h, --help show this help message and exit --search SEARCH Emoji to search for --category CATEGORY Category to get list of emojis --categories Get list of emoji categories --palette Get JSON object of all categories and their emojis emoji-search --search '🎈' > balloon.json Then check out all the information! { "symbol": "🎈", "description": "A balloon on a string, as decorates a birthday party. Generally depicted in red, though WhatsApp’s is pink and Google’s orangish-red.\nCommonly used to convey congratulations and celebration, especially when wishing someone a happy birthday.\nMicrosoft and Samsung's balloons were previously blue; SoftBank's was shown floating in the sky.\n\nBalloon was approved as part of Unicode 6.0 in 2010\nand added to Emoji 1.0 in 2015.\n", "name": "Balloon", "aliases": ["Party", "Red Balloon"], "apple_name": "Balloon", "unicode_name": "", "vendors": { "Apple": [ "iOS 13.3", "iOS 10.2", "iOS 8.3", "iOS 6.0", "iOS 5.1", "iOS 4.0", "iPhone OS 2.2" ], "Google": [ "Android 10.0 March 2020 Feature Drop", "Android 8.0", "Android 7.0", "Android 5.0", "Android 4.4", "Android 4.3" ], "Microsoft": [ "Windows 10 May 2019 Update", "Windows 10 Anniversary Update", "Windows 10", "Windows 8.1", "Windows 8.0" ], "Samsung": [ "One UI 1.5", "One UI 1.0", "Experience 9.0", "Experience 8.0", "TouchWiz 7.1", "TouchWiz 7.0", "TouchWiz Nature UX 2" ], "WhatsApp": ["2.19.352", "2.17"], "Twitter": ["Twemoji 13.0", "Twemoji 1.0"], "Facebook": ["4.0", "3.0", "2.0", "1.0"], "JoyPixels": [ "6.0", "5.5", "5.0", "4.5", "4.0", "3.1", "3.0", "2.2", "2.0", "1.0" ], "OpenMoji": ["12.3", "1.0"], "emojidex": ["1.0.34", "1.0.33", "1.0.19", "1.0.14"], "Messenger": ["1.0"], "LG": ["G5", "G3"], "HTC": ["Sense 7"], "Mozilla": ["Firefox OS 2.5"], "SoftBank": ["2014", "2008", "2006", "2004", "2001", "2000"], "Docomo": ["2013"], "au by KDDI": ["Type F", "Type D-3", "Type D-2", "Type D-1"] } } Feel free to check out the docs for more information. License This software is released under the terms of MIT license. Project details Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/emoji-search/
CC-MAIN-2021-21
refinedweb
465
62.54
Sometimes applications fail. If you are the author and it fails on your machine, typically you fire up the code in a debugger, figure out the issue, fix it, and rebuild the code. If the applications is out in the wild, perhaps with millions of users, it gets much more complicated. Yet, the goal is still to fix the application to improve user experiences. Without knowing the details of the failures, they’re very difficult to fix. In the old days, people used to write amazing exception handlers in their applications. The FoxPro world had several folks giving talks around the world just on good exception handlers. We called them error handlers at the time. They would try to capture as much information about the error as possible, perhaps including the user’s machine configuration, filenames, call stacks, etc. Some would even include recorded user actions. The handlers would try to send the information back to the application author. After all, the application user has no idea what an application really does under the covers (even in non-error conditions): it could be secretly gathering credit card numbers. That’s one of the biggest reasons why Easter Eggs in software are verboten: the author has hidden some code in the application that could be doing anything. In the old days, not many people were concerned with user’s privacy. In fact, when you run an application, or even visit a web site, you’re actually asking someone (perhaps a remote computer or software developer) to do something on your own machine. Perhaps this is merely showing some text, but it could be running a script that reads your personal information or plants a virus. Keep in mind a computer can execute a billion instructions in a second. In order to do handle errors, some code would have to run to handle the exception. Without operating system support, a totally crashed application wouldn’t be able to run exception handling code. Many years ago, Microsoft was getting lots of reports of “Blue screens”: crashes of Windows. These were seriously hurting customer experiences, and even today, BSOD, or Blue Screen of Death is a well-known term. Instrumenting Windows to have an error recording and reporting service lead to a huge reduction in these errors. It turns out that at one point, 90% of the BSODs were due to poorly written device drivers, specifically video drivers). To lend credence to that, device drivers run in kernel mode, and thus have full access to the entire system. User applications run in “User mode”: a user application is isolated from the system where it’s much harder to crash the entire computer; users experience only the application failing. It wasn’t necessarily all the fault of the device driver authors: perhaps the documentation or device driver architecture could have been improved to prevent erroneous code. Thus was born Windows Error Reporting, which enables Microsoft to capture information about application failures after they fail and send it to the application authors (internal or external to Microsoft) so that they can be fixed. When an application fails, WER is invoked. It checks various settings to determine whether to upload the data, or present a dialog first. The end user or the Domain policy for the user’s machine can control the behavior of exceptions: See also Microsoft is very concerned preserving privacy when capturing information, especially without consent. We’re also concerned about using customer paid network bandwidth when sending data. WER encapsulates and provides common exception handling tasks so all applications can take advantage of them: 1. Common user permissions, control, consent and user experience 2. Capture information 3. Send it back, handling various connectivity states Sometimes you want to write custom data to the Window Error Reporting service. This requires capturing all possible crashes before the OS WER kicks in, then formatting the data and calling the WER functions to package up the info and send it. You can easily add a Try…Catch block at the main entry point of your application. The Catch can then capture information about the error. However, Try..Catch only catches exceptions on the currently executing thread. Thus you must surround all your thread routines with Try..Catch. This gets cumbersome, especially with ThreadPools, Tasks, Windows Workflow Foundation Activities. An easier approach is to subscribe to the Appdomain.UnhandledException Event as demonstrated by the code below. The sample code adds 3 controls to a window: a checkbox, a button and a textbox. The textbox just shows what ‘s happening. The button throws an exception from a threadpool thread. Even though the code is surrounded by a Try..Catch, because it’s run on a different thread, the Try..Catch is not relevant. This is to simulate what happens to users when they write cod that spawns threads, The checkbox registers a domain unhandled exception handler using the Appdomain.UnhandledException Event The sample below shows how it works. Start Visual Studio, File->New->C# Windows WPF Application. Replace the Mainwindow.Xaml.cs code with the code below. Hit Ctrl-F5 to run the program without debugging Click on the button to throw an exception. This dialog appears: Now click on the checkbox to subscribe to the Unhandled Exception event for the appdomain, then click the button to cause the exception. The UnhandledException Handler code is invoked and it writes an event to the event log. It also shows a separate window indicating the exception. When the window is closed, the application terminates, but does not invoke WER because to the OS, it did not crash. You can see the event log by: Windows key+X, “Event Viewer” on Windows 8, or Windows key , then type “Event”, choose Event Viewer. BTW, I (my kids too!) really like my Surface RT on which the Event viewer shows too, and my Lumia 920 Windows 8 phone, which does not. In fact, the Windows Error Reporting also shows up in the Event Viewer. Choose Filter Current Log to make it easier to see: <Code> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks;(); Loaded += (oLoaded, eLoaded) => { try { var sp = new StackPanel() { Orientation = Orientation.Vertical }; var chk = new CheckBox() { Content = "Add Exception Handler" }; sp.Children.Add(chk); var btn = new Button() { Content = "Throw an exception", Width = 100, HorizontalAlignment = HorizontalAlignment.Left }; sp.Children.Add(btn); var txtB = new TextBox() { Text = "textbox", MaxLines = 10, Height = 100 }; sp.Children.Add(txtB); chk.Checked += (ochk, echk) => { chk.IsEnabled = false;//no going back AppDomain.CurrentDomain.UnhandledException += (oEx, eEx) => { var eventLogName = //like "WpfApplication1" System.IO.Path.GetFileNameWithoutExtension( Assembly.GetEntryAssembly().Location); if (!EventLog.SourceExists(eventLogName)) { EventLog.CreateEventSource(eventLogName, "Application"); } string strToAdd = string.Format( "Hello from {0} {1}", eventLogName, eEx.ExceptionObject); EventLog.WriteEntry(eventLogName, strToAdd, EventLogEntryType.Error); txtB.Dispatcher.Invoke(() => { // put UI on UI thread txtB.Text += "\r\nUnhandled Exception " + eEx.ToString(); var odlg = new Window() { Content = txtB.Text, Width = 500, Height = 500, Left = this.Left + 300 }; odlg.ShowDialog(); // once an unhandled exception has occurred // the application may be in an unpredictable // unstable state, and thus continuing // execution can be unwise Environment.Exit(0); }); }; }; this.Content = sp; btn.Click += (obtn, ebtn) => { ThreadPool.QueueUserWorkItem(oThrd => { // from this threadpool thread, // tell the main thread // to change the textbox content txtB.Dispatcher.Invoke(() => { txtB.Text += "\r\nThrowing an exception " + DateTime.Now.ToString(@"[{0:hh\:mm\:ss\.fff t}]"); }); throw new InvalidOperationException("Foobar"); }); }; } catch (Exception ex) { this.Content = ex.ToString(); } }; } } } </Code>
http://blogs.msdn.com/b/calvin_hsia/archive/2013/01/31/10390072.aspx
CC-MAIN-2014-23
refinedweb
1,251
50.12
set-monad: Set monad The set-monad library exports the Set abstract data type and set-manipulating functions. These functions behave exactly as their namesakes from the Data.Set module of the containers library. In addition, the set-monad library extends Data.Set by providing Functor, Applicative, Alternative, Foldable, Monad, and MonadPlus instances for sets. In other words, you can use the set-monad library as a drop-in replacement for the Data.Set module of the containers library and, in addition, you will also get the aforementioned instances which are not available in the containers package. It is not possible to directly implement instances for the aforementioned standard Haskell type classes for the Set data type from the containers library. This is because the key operations map and union, are constrained with Ord as follows. map :: (Ord a, Ord b) => (a -> b) -> Set a -> Set b union :: (Ord a) => Set a -> Set a -> Set a The set-monad library provides the type class instances by wrapping the constrained Set type into a data type that has unconstrained constructors corresponding to monadic combinators. The data type constructors that represent monadic combinators are evaluated with a constrained run function. This elevates the need to use the constraints in the instance definitions (this is what prevents a direct definition). The wrapping and unwrapping happens internally in the library and does not affect its interface. For details, see the rather compact definitions of the run function and type class instances. The left identity and associativity monad laws play a crucial role in the definition of the run function. The rest of the code should be self explanatory. The technique is not new. This library was inspired by [1]. To my knowledge, the original, systematic presentation of the idea to represent monadic combinators as data is given in [2]. There is also a Haskell library that provides a generic infrastructure for the aforementioned wrapping and unwrapping [3]. The set-monad library is particularly useful for writing set-oriented code using the do and/or monad comprehension notations. For example, the following definitions now type check. s1 :: Set (Int,Int) s1 = do a <- fromList [1 .. 4] b <- fromList [1 .. 4] return (a,b) -- with -XMonadComprehensions s2 :: Set (Int,Int) s2 = [ (a,b) | (a,b) <- s1, even a, even b ] s3 :: Set Int s3 = fmap (+1) (fromList [1 .. 4]) As noted in [1], the implementation technique can be used for monadic libraries and EDSLs with restricted types (compiled EDSLs often restrict the types that they can handle). Haskell's standard monad type class can be used for restricted monad instances. There is no need to resort to GHC extensions that rebind the standard monadic combinators with the library or EDSL specific ones. [1 ] CSDL Blog: The home of applied functional programming at KU. Monad Reification in Haskell and the Sunroof Javascript compiler. [2 ] Chuan-kai Lin. 2006. Programming monads operationally with Unimo. In Proceedings of the eleventh ACM SIGPLAN International Conference on Functional Programming (ICFP '06). ACM. [3 ] Heinrich Apfelmus. The operational package. Modules [Index] [Quick Jump] - Data Downloads - set-monad-0.3.0.0.tar.gz [browse] (Cabal source package) - Package description (as included in the package) Maintainer's Corner For package maintainers and hackage trustees
http://hackage.haskell.org/package/set-monad-0.3.0.0
CC-MAIN-2018-51
refinedweb
541
57.37
J. The: -. Example. Settings This plugin does not have any customizable settings. Installation This plugin can be installed by copying the plugin jar into your application's /WEB-INF/lib directory. No other files need to be copied or created. Resources - Integrating Struts 2 + JSF + Facelets (Matt Raible) 1 Comment Navid Mitchell First off I want to say I think this plugin is great. Thank you for writing it. I just wanted to ad a little more info because I got stumped while trying to use this plugin. To clarify how the plugin resolves the proper JSP page to render. The plugin creates the Faces View ID using the following combination "Package Namespace" + "/" + "Action Name" + "Default JSF Suffix" So for a action like the following with a namespace of Test <action name="Calendar" class="net.mitchellsoftware.CalendarAction2"> <result name="success" type="jsf"/> <interceptor-ref <interceptor-ref </action> You Will end up with a view id of /Test/Calendar.jsp This also needs to be the path of your actual page. However, and this is what stumped me. If you provide a path to your JSP page in the result and the path is different than the one created above, such as below. <result name="success" type="jsf">/WEB-INF/pages/Calendar.jsp</result> Your page will still be rendered as expected, since the plugin makes sure to pass the proper View Id to JSF. But now none of the controls will work since the POST within the rendered HTML will not point to a valid action. So the Moral of the story is do not provide a path within the result. Happy coding Navid
https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=44198
CC-MAIN-2018-34
refinedweb
274
64.81
A 30 Minute Look At ASP.NET vNext This week at TechEd, the ASP.NET team announced some pretty exciting updates on the way for ASP.NET. Top Links Blog Posts - ASP.NET vNext: the future of .NET on the Server (.NET Web Development and Tools Blog) - Introducing ASP.NET vNext (Scott Hanselman) - ASP.NET vNext (David Fowler) - The Next Generation of .NET – ASP.NET vNext (.NET Team Blog) ASP.NET team session videos from TechEd - INTRODUCING: The Future of .NET on the Server (Scott Hunter and Scott Hanselman) - Channel 9 Live: ASP.NET Developer Q&A (Scott Hunter and Scott Hanselman) - DEEP DIVE: The Future of .NET on the Server (David Fowler and Scott Hanselman) ASP.NET site content - Getting Started with ASP.NET vNext (Mike Wasson) - MVC Music Store Sample Application for ASP.NET vNext (Cephas Lin) - BugTracker Sample Application for ASP.NET vNext (Erik Reitan) Getting Involved - ASP.NET vNext Discussion Forum - ASP.NET vNext chat on JabbR - ASP.NET vNext Home repository on GitHub - The place to get started with the code What Is It? In case you haven't read up on it, I'll just quote from the ASP.NET site: The. To me as a web developer, this means I get: - All the advantages of the .NET platform (performance, stability, security, comprehensive API), and - The development experience of C# and Visual Studio... with - The simplicity, portability, quick dev refresh cycle and flexibility of an interpreted web framework. And I like the sound of that. Source Code All the source code and samples are published under a new ASP.NET organization on GitHub. There are lots of interesting repos to look at; here are some top ones to get started with: Home repository This is the place to get started. The readme for this repo explains how to install and run the Hello World samples. Music Store sample Ah, the Music Store. The team wanted some samples to validate and test vNext as they developed it, and this was one of them. I updated the source code to ASP.NET MVC 5 and threw it over the wall to them, and it seems to have held up. Cephas Lin has a Music Store walkthrough posted in the vNext content on the ASP.NET site, and it's pretty easy to follow along. BugTracker sample The BugTracker is a single page application using SignalR, Knockout.js and Web API. I'm pretty happy that they had a single page application as one of their validation cases from the beginning. KRuntime If you're feeling adventurous, this it the actual runtime. It includes things like the compilation system, SDK tools, and the native CLR hosts. (parental warning advisory if stumbling across some C++ gives you nightmares) Quick Walkthrough I promised I'd skip the detailed walkthrough, because you really should be looking at the "official" ones I've linked to above. My point here is not really guide you through them, but to give you a look at what the experience is like if you're not feeling up to doing it yourself. So let's see what I can get running in 30 minutes or so (until my next meeting). If you want to follow along, read the walkthroughs. Important Notes Before We Get Started I'm doing this on my dev machine. It runs side by side with my existing .NET and Visual Studio 2013 installs. This looks a bit fiddly because we're doing this all from the commandline. Don't worry if that's not your bag - this will all be supported via Visual Studio. This is an early preview. But, it's good that this level of control is available. Note that I'm doing all of this without firing up Visual Studio or installing any other software. You'll see the letter K pops up from time to time. This was internally called Project K before it was released. I have no idea if the k will go away now, but I kind of like it. So we've got kvm (k version manager), kre (k runtime engine), kpm (k package manager), and k (the actual bootstrapper to run our app). The Home Repo samples First, let's try out the ASP.NET vNext Home repo. I've already got this locally, but for the purposes of science I'll pretend that I don't. Since I'm just kicking the tires here, instead of cloning the repo I'll just download the zip to my desktop, unblock if necessary, and unzip it. Here's what that gets me: C:\Users\Jon\Desktop\Home-master\Home-master>dir Volume in drive C has no label. Volume Serial Number is 5E2E-AE5E Directory of C:\Users\Jon\Desktop\Home-master\Home-master 05/13/2014 02:29 PM <DIR> . 05/13/2014 02:29 PM <DIR> .. 05/13/2014 01:51 PM 851 .gitattributes 05/13/2014 01:51 PM 245 .gitignore 05/13/2014 01:51 PM 1,513 CONTRIBUTING.md 05/13/2014 01:51 PM 356 kvm.cmd 05/13/2014 01:51 PM 17,278 kvm.ps1 05/13/2014 01:51 PM 28 kvmsetup.cmd 05/13/2014 01:51 PM 592 LICENSE.txt 05/13/2014 01:51 PM 481 NuGet.Config 05/13/2014 01:51 PM 6,390 README.md 05/13/2014 02:29 PM <DIR> samples 9 File(s) 27,734 bytes 3 Dir(s) 11,363,086,336 bytes free The next step in the readme tells me to execute kvmsetup.cmd, which tells me this: Copying file C:\Users\Jon\.kre\bin\kvm.ps1 Copying file C:\Users\Jon\.kre\bin\kvm.cmd Adding C:\Users\Jon\.kre\bin to process PATH Adding C:\Users\Jon\.kre\bin to user PATH Adding C:\Program Files\KRE;%USERPROFILE%\.kre to process KRE_HOME Adding C:\Program Files\KRE;%USERPROFILE%\.kre to machine KRE_HOME Press any key to continue ... And with that, we've got the version manager installed. Important: this is the version manager, not the runtime. We can install multiple versions of the runtime engine, and use kvm to select the active one for a project. Next, the readme tells me to install a named version of the K Runtime Engine: kvm install 0.1-alpha-build-0421 C:\Users\Jon\Desktop\Home-master\Home-master>kvm install 0.1-alpha-build-0421 Downloading KRE-svr50-x86.0.1-alpha-build-0421 from Installing to C:\Users\Jon\.kre\packages\KRE-svr50-x86.0.1-alpha-build-0421 Adding C:\Users\Jon\.kre\packages\KRE-svr50-x86.0.1-alpha-build-0421\bin to process PATH Now we've got a runtime installed, so we can run some samples. The readme recommends running the console sample first, and I think that makes sense since it's an incredibly simple app that verifies things are installed. So I cd to samples\ConsoleApp and run kpm restore. This looks scary, but it's really fast, and it's a good thing. The idea is that instead of running on big, monolithic framework assemblies, ASP.NET vNext is grabbing a bunch of small, focused NuGet packages. C:\Users\Jon\Desktop\Home-master\Home-master>cd samples\ConsoleApp C:\Users\Jon\Desktop\Home-master\Home-master\samples\ConsoleApp>kpm restore C:\Users\Jon\Desktop\Home-master\Home-master\samples\ConsoleApp>CALL "C:\Users\Jon\.kre\packages\KRE-svr50-x86.0.1-alpha-build-0421\bin\KLR.cmd" --lib "C:\Users\Jon\.kre\packages\KRE-svr50-x86.0.1-alpha-build-0421\bin\;C:\Users\Jon\.kre\packages\KRE-svr50-x86.0.1-alpha-build-0421\bin\lib\Microsoft.Framework.PackageManager" "Microsoft.Framework.PackageManager" restore Restoring packages for C:\Users\Jon\Desktop\Home-master\Home-master\samples\ConsoleApp\project.json Attempting to resolve dependency ConsoleApp >= 1.0.0 Attempting to resolve dependency System.Console >= 4.0.0.0 GET'System.Console' GET'System.Console' Attempting to resolve dependency mscorlib >= Attempting to resolve dependency System >= Attempting to resolve dependency System.Core >= Attempting to resolve dependency Microsoft.CSharp >= Attempting to resolve dependency ConsoleApp >= 1.0.0 Attempting to resolve dependency System.Console >= 4.0.0.0 OK'System.Console' 931ms OK'System.Console' 972ms GET OK 1696ms Attempting to resolve dependency System.IO >= 4.0.0.0 GET'System.IO' GET'System.IO' Attempting to resolve dependency System.Runtime >= 4.0.0.0 GET'System.Runtime' GET'System.Runtime' OK'System.Runtime' 659ms OK'System.IO' 838ms OK'System.Runtime' 841ms GET OK'System.IO' 954ms GET OK 1779ms Attempting to resolve dependency System.Text.Encoding >= 4.0.0.0 GET'System.Text.Encoding' GET'System.Text.Encoding' Attempting to resolve dependency System.Threading.Tasks >= 4.0.0.0 GET'System.Threading.Tasks' GET'System.Threading.Tasks' OK 1919ms OK'System.Text.Encoding' 746ms OK'System.Text.Encoding' 837ms GET OK'System.Threading.Tasks' 843ms OK'System.Threading.Tasks' 1051ms GET OK 1356ms OK 1721ms Resolving complete, 8357ms elapsed Installing System.Console 4.0.0.0 Installing System.Runtime 4.0.20.0 Installing System.IO 4.0.0.0 Installing System.Text.Encoding 4.0.10.0 Installing System.Threading.Tasks 4.0.0.0 Restore complete, 8495ms elapsed Now I run it with k run: C:\Users\Jon\Desktop\Home-master\Home-master\samples\ConsoleApp>k run Hello World C:\Users\Jon\Desktop\Home-master\Home-master\samples\ConsoleApp> Like I said, not all that exciting. Just a quick verification check. Now that I know that's working, I'll quickly pop into one of the other sandbox samples, the HelloWeb one. Notice how simple the startup.cs file is (the official walkthrough explains it in detail). C:\Users\Jon\Desktop\Home-master\Home-master\samples\HelloWeb>dir Volume in drive C has no label. Volume Serial Number is 5E2E-AE5E Directory of C:\Users\Jon\Desktop\Home-master\Home-master\samples\HelloWeb 05/13/2014 02:29 PM <DIR> . 05/13/2014 02:29 PM <DIR> .. 05/13/2014 01:51 PM 310,647 image.jpg 05/13/2014 01:51 PM 506 project.json 05/13/2014 01:51 PM 227 Startup.cs 3 File(s) 311,380 bytes 2 Dir(s) 11,368,951,808 bytes free C:\Users\Jon\Desktop\Home-master\Home-master\samples\HelloWeb>copy startup.cs con using Microsoft.AspNet.Builder; namespace KWebStartup { public class Startup { public void Configure(IBuilder app) { app.UseStaticFiles(); app.UseWelcomePage(); } } } 1 file(s) copied. C:\Users\Jon\Desktop\Home-master\Home-master\samples\HelloWeb> Now I'll call kpm restore , just like before. This time kpm restore takes a bit longer, because there are more included packages (listed in project.json) and their dependencies. And I'm ready to run it. This time, instead of k run, I'll call k web since it's a web app. If I forget and call k run, it reminds what's what: C:\Users\Jon\Desktop\Home-master\Home-master\samples\HelloWeb>k run 'HelloWeb' does not contain a static 'Main' method suitable for an entry point Fine, k web it is. It tells me the server's started, but how do I view it? Well, the readme tells me it's at, but if I didn't know I could consult the commands section of project.json: "commands": { "web": "Microsoft.AspNet.Hosting server=Microsoft.AspNet.Server.WebListener server.urls=" } Simple enough. And browsing to that gives me a cool hello world page: Nerd note: That page is shown because we've got app.UseWelcomePage() in startup.cs. There are no images or css in the project because everything's contained in the emitted HTML. It's actually really impressive - it's got embedded fonts, images as data:urls, CSS, and a minimized version of jQuery (for some nice animations), so it's a 287KB HTML payload... but since it's being served locally and you're not going to run this in production, not a problem. Nerd smackdown: David Fowler reminded me that this welcome page has been in Katana for a while. Music Store Okay, now that I've got this stuff installed, let's see how fast I can get the Music Store sample running. Step 1: Grab the zip from, verify it's not blocked, and unzip on desktop. Step 2: Run kpm restore. Step 3: Select the hosting opeion (Helios, SelfHost, CustomHost - explained here). In this case I'll stick with selfhost, so I run k web and browse to localhost:5002: Yippee! Again, the point is that it's pretty quick and painless to get started and play with the samples; just follow the walkthroughs. If you're used to Node or Rails a lot of these steps should seem pretty familiar. If you're not and this freaks you out, don't be freaked out... this will all work smoothly from within Visual Studio in the release version. This is a preview. Take a look! Have Fun! Let us know what you think! Videos The best way to get up to speed is by watching the videos I mentioned earlier.
http://weblogs.asp.net/jongalloway/a-30-minute-look-at-asp-net-vnext
CC-MAIN-2015-06
refinedweb
2,192
61.33
If uses the Address table so it assumes that the zip code already exists. There isn’t a service that uses the AddressZipCode table which is the one you need to import to. That means you need to create a custom service. Fortunately creating custom services especially this one is pretty easy. The basic steps are: 1. Create a query under the Query node that uses the table(s) you are interested in as datasources, in this case the AddressZipCode table is your datasource. 2. Under Tools > Development Tools > AIF run the Create document service wizard choosing the query you created in step #1. This will create the service for you. 3. Change the namespace of the service. (You don’t have to do this but I would recommend it in order to keep your services consistent with the out-of-the-box services.) You do this in the AOT > Services > YourService – there’s a Namespace property on the service. Set it to what the other services have for their Namespace property which is. 4. Assign a security key to the new service, again you do this in the AOT > Services > YourService. You won’t be able to use the service until a security key is assigned so this is a required step. 5. Enable the service in AX under Basic > Setup > AIF > Services. If your service isn’t displayed when you come into the window, click the Refresh button. 6. If you are using the web service adapter, in the Services form click the Generate button to generate the web service. 7. Enable the service on your Endpoint. 8. Run the service to start importing your zip codes. Join the conversationAdd Comment
https://blogs.msdn.microsoft.com/axsupport/2010/09/01/importing-zip-codes-into-ax-via-aif/
CC-MAIN-2017-47
refinedweb
283
66.03
NET FrameworkYou can make use .Net Framework (Click here for more information on Microsoft.NET Framework) as a development environment or a platform for developing userfriendly web-based applications that can allow seamless access by users from anywhere in the world and from any type of client machines. You can apply the openstandards such as XML (eXtensible Markup Language), SOAP (Simple Object AccessProtocol) and HTTP (HyperText Transfer Protocol) for developing your web-applications and web applications created with such open standards can interact wellwith other applications of other platforms. You can use different programming languages such as C#, VBScript, VB.NET,Managed C++ for developing your applications in .NET Framework, as the .NETFramework is not dependent on one particular language or platform and can supportmany kinds of platforms and programming languages that are in use today. Further,you can use .NET Framework for running your applications in almost all platformssuch as Linux, Macintosh and Unix without any hitches. The presence of many off-the-shelf libraries in .NET Framework can assist you indeveloping your applications in a faster, cheaper and easier manner. The mostrecent .Net Framework version is capable of supporting over 20 differentprogramming languages today. As per the classification by the Microsoft, there are two categories of .NETFramework and they are CLR and .Net Framework class library. Common Language Runtime: The CLR is responsible for providing a common runtimeenvironment or services with which all .NET applications can run. Further, thevarious capabilities of CLR can enable any developer to write even big applicationswith ease using the features such as strong type naming, life-cycle management,dynamic binding that is capable of making any business logic into re-usablecomponent and finally the cross-language exception handling. .Net Framework class library: This class library constitutes various predefinedfunctional sets that are very useful while developing the applications by developers.There are three main components in this class library and they are:· ASP.NET.· Windows Forms.· ADO.NET. With the .Net Framework you can make your codes written in fewer lines and otherfavourable features such as easy web settings, easy deployment of applications, easycompilation procedures, easy Web configuration makes the .NET Framework a greatplatform to work with. In an overall scenario, the developers will be able toconcentrate more on Web controls and spend an efficient time in application designand implementation and to have an effective control over the flow of the applicationsequence. Another great feature that any developer can take note of is the feature of .NETFramework taking into cognisance all the Web controls, server-side blocks of codesand Web forms and getting them compiled whenever a call for the page compilationis completed. Once the components of .NET framework are compiled in your machine, the compiledversion can easily be uploaded with all the relevant pages in the /bin directory of thesystem. The process of uploading is very easy when compared to the complicatedprocess of web-application in ASP, where in you have to first upload the applicationpages with the relevant components and you also need to register them with theoperating system. In .NET Framework the simple uploading in /bin directory of the operating system isenough and you need not carry out the complicated process of registering thecomponents of web-application with the operating system. With the help of an XML based web.config file you can carry out the web settingswhich is nothing but configuring the .NET applications for successful running. TheXML based web.config file can be modified through a program and when any suchmodification is done, the system recognises the change and registers it immediatelythat makes configuration of .NET applications easy and quick. Caching is a process or a method with which the most commonly and frequentlyused resources and data will get loaded onto the memory for easy and fast access.There are three types of caching in .Net Framework and they are output caching,data caching, and fragment caching. MVC Extensions for ASP.NET -- Deliver Lightweight and High Performance UserInterfacesDevExpress, the Award-Winning ASP.NET Vendor Is Set to Release Over 30 MVCExtensions as Part of Its Upcoming Release of DXperience There are currently over 15 compilers being built by Microsoft and other companiesthat produce code that will execute in the CLR. CLR engine is divided into modulesthat contain code, metadata, and resources. The code is stored in commonintermediate language (CIL) format. The module's metadata includes the types suchas names, inheritance relationships, method signatures, and dependencyinformation. The module's resources consist of static read-only data such as strings,bitmaps, and other aspects of the program that are not stored as executable code. CLR is also helpful for security purposes. CLR provide permissions to a componentbased on what process it runs in, validates the code based on evidence such asinformation about code at load time and the website from which component wasobtained to assign permissions on a component-by-component basis. Moreover, CLRchecks the code to see if it has been manipulated. The metadata in a CLR componentcan contain a digital signature that can be used to verify that the component waswritten by genuine person and that it has not been modified. You can verily identifyif anyone has tried to modify with the code. For example, if someone tries to changethe code of transferring money from the intended recipient to himself the CLR willprevent the altered code from running. The ASP.NET HTML Server Controls that you can apply in ASP.NET page are asfollows: • HTMLAnchor: Creates a server-side control that links to the <a> HTML element.The <a> element is used to create a link to another page. You can place anHTMLAnchor control within the HTMLForm control. • HTMLButton: Creates a server-side control button that maps to the <button> HTMLelement. This ASP.NET HTML Server Control has various methods to modify theappearance of an HtmlButton control. You can assign style attributes to the button,include formatting elements or assign property value. You can also include imageswithin the button elements themselves, or even include other Web Forms controls. • HTMLForm: Creates a server-side control that allows you to place multiple controlsin it. The HTMLForm control must have an opening and closing tags. If both the tagsare not available, either the elements in it will not be viewed or run in the browserwindow or the compilation error message will occur. All web controls are obtained from a common base class. This ensures that theobject model remains consistent across various controls. For example, in order tomove the cursor consistently across a form you can specify the Web controlTabIndex property. This is very difficult while using normal HTML. You can alsodisable a particular web control by exposing the Enabled property. This process isalso difficult in HTML and ASP. ASP.NET ASP.NET Web Server Controls consists of Web form controls, List controls,and Rich controls. All the web form controls are defined within the namespaceSystem.Web.UI.WebControls. This namespace is a collection of classes that enablesyou to create new ASP.NET Web Server Controls. The controls that you can use webform controls category are button control, checkbox control, radiobutton control,table control, image control, label control, and panel control. These web formcontrols have a common set of properties that can be used across multiple controls. The controls listed in the List controls category are dropdown list control, repeatercontrol, datalist control, and datagrid control. These controls use the concept of databinding. The controls listed in the Rich controls category include calendar control andadrotator control. These controls are specifically being employed for complex tasks. • White Pages• Yellow Pages• Green Pages The white pages consist of the description such as name and address of the companyoffering the service. The yellow pages consist of industrial categories based onstandard taxonomies such as North American Industry Classification System andStandard Industrial Classification. The green pages describe the interface to the webservice in detail so that anyone can write an application after using the web service.Web services are described in UDDI directory through a document called Type Modelor tmodel. Normally, this tModel contains a WSDL file that describes a SOAPinterface to an XML Web service, but the tModel is flexible enough to describe almostany kind of web service. Apart from using the web services from UDDI, you can also search a particular webservice in UDDI. In addition, you can search for companies’ information that postedweb services. In certain times, you might know the names of the companies thatoffer web services but you may not be aware of the web services that they offer. TheWS Inspection is a specification in UDDI that allows you to search for a collection ofweb services that are located in a particular company name. You can evaluate theseweb services according to your requirements. Just as you have created a ASP.NET Custom Server Controls you can customize it tooto create a unique identity. You can even consume a single ASP.NET Custom ServerControls for multiple web forms. For ASP.NET Custom Server Controls only one copyof the control is needed in the Global Assembly Cache (GAC). Moreover, ASP.NETCustom Server Controls are very helpful if you want a dynamic layout for your webapplication. The ASP.NET Repeater Control will not render the result unless you bound it to adata source through its DataSource property. The ASP.NET Repeater Controlsupports several events such as ItemCreated, ItemCommand, ItemDataBound, Load,and Unload. These events help developer to create an event when the user clicks thebutton. Chat applications with many features are even sold for a sum but some sites mayrequire a very simple feature to interact with the customer service personnel who isonline. Such simple chat applications can be built on your own. Let us see somealgorithm and the code snippets that go in the way of creating a simple chatapplication. To store the messages that are typed during a chat you can either use static arraysor use a database for that purpose. Using a database is a good way of storingmessages. However you can also use static arrays for that purpose. The chatapplication that we are going to see will work on any browser that supports<iFrame>, since we are using <iFrame> to display the chat window of theapplication. We will be refreshing the page in the <iFrame> to refresh the chatwindow alone without refreshing the whole page in which the <iFrame> is present. To enter the chat you need an .aspx page where the user enters the name of theroom and the user id. Then the user presses a Join chat button. You can pass theseparameters to the ChatPage.aspx where you will be having an iFrame for displayingthe messages and a text box control to type the messages and a button to send thetyped messages. To pass the parameters collected from the user to theChatPage.aspx you can use the following code which looks like,); Within the ChatPage.aspx, once you type the message that is to be sent and whenyou click the Send button, you need to add the message that is typed. You check thetext box for that purpose and if it contains any text you just add the message to thestatic array. if ( Request.Params["Room"] != null )sRoom = Request.Params["Room"].ToString();elses themessages that are typed. You can thus create a simple chat application which can be used in all the sites thatneed interaction with the user. .Net being the platform for distributed application now, ASP.Net can be used to storeimages that are small to be stored in a database like SQL Server 2000 and laterversions.can create a .aspx page which can have a HTMLInputFile control which is used toselect the image file that is to be saved in the database. You can also create a textbox control in which you can add the image name or somecomment or an image id for the image saved. Use a button control to upload theimage to the database. Namespaces like System.Data.SqlClient, System.Drawing,System.Data, System.IO, and System.Drawing.Imaging are used in this task. In the OnClick property of the button you can write the following code to upload animage to the database. You can also write the above code in a function and call that function in the OnClickevent of the upload button. The code given above performs the following steps in theprocess of inserting an image into the database. To retrieve the image from the SQL Database you can perform the following steps. Using the above steps you can retrieve and display the image from the database tothe web page. You can use these algorithms and take advantage of the “image” data type availablein the SQLServer 2000 database to store small images that correspond to aparticular record in the table of the database. This method of storing avoids thetedious task of tracking the path of the web folder if the images are stored in a webfolder. Tracking Emails - Know Whether the Recipient Opens itIt is very easy to track whether the user has read the email. The concept is verysimple. You insert a link to a small transparent image in the mail sent, the mail beingsent in HTML format, and when the user opens the email the image is loaded sendingyou a querystring to the web page that tracks the email. The web page requests thequerystring or the parameter that is passed. This ensures that the email is read bythe user. When the page that is tracking is requested by the email sent you can get the valueof the date and time when the request comes and you can store them in a databaseor send you an alert indicating the time and date at which the email was read by theuser. This is the simple way that is used to track whether the emails sent are read ornot. To send emails you may be importing the namespace System.Web.Mail. You wouldbe creating a MailMessage object as given below. Imports System.Web.Mail string sBody; mailMsg.BodyFormat = MailFormat.Html;SmtpMail.SmtpServer = “your Server name”;mailMsg.From = "your email address";mailMsg.To = “to email address”;mailMsg.Subject = “subject line of the mesg”;mailMsg.Body = sBody;SmtpMail.Send(mailMsg); The above code sends an email to an email address as given in the mailMsg.Toproperty. For tracking an email, all you have to do is to add an image tag to thebody of the message i.e. sBody. This can be done by In the above line sParam is the parameter that is passed to the url and sYourDomainis your domain name where you create this page to track the email. If you send anemail with the body of the message as given above, when the user reads the email,the image tag will try to load the url given in the tag. This will send the parameter“sentto” that is given by you to the page requested. In the trackemail.aspx page youcan write code to retrieve the value of the parameter “sentto”. Once you receive theparameter you can do anything on that page to indicate that the user has read theemail. The code given below can be used in the trackemail.aspx page to retrieve theparameter. Response.Redirect("transparent.gif");} Once you have retrieved the parameter that is passed to the page you can redirectthe request to a transparent image so that this transparent image, “transparent.gif”loads in the email message of the user who is reading the mail. Make this“transparent.gif” as small as possible, usually of 1 pixel by 1 pixel height and width,so that it does not take time to load. Since it is transparent the user who reads yourmail may not know that an image has been loaded in the email message and theemail that he reads is being tracked. This way of tracking the email is so easy. Once you get the parameter in yourtrackemail.aspx page you can add a time stamp to the body of the email messagethat is sent to you in the Page_Load event of that page. This enables you to knowthe time and date at which the email was read by the user. The following are the different types of cryptographic primitives that are used in .Netto encrypt and decrypt data. The Private-key encryption uses a single shared key to encrypt and decrypt datawhereas the Asymmetric cryptography uses public/private key pair for that purpose.Cryptographic signing uses digital signatures to ensure that the data originates fromthe intended user. The digital signatures are unique to a particular party.Cryptographic hashes are another method of cryptography where data is mappedfrom any length to fixed-length byte sequence. The following are the classes that are provided to implement the private-keyalgorithms. DESCryptoServiceProvider, RC2CryptoServiceProvider, RijndaelManaged,and TripleDESCryptoServiceProvider. For implementing the public-key encryptionalgorithms DSACryptoServiceProvider and RSACryptoServiceProvider classes areprovided. These classes in public-key algorithms can also be used for Cryptographicsigning. Classes like HMACSHA1, MACTripleDES, MD5CryptoServiceProvider,SHA1Managed, SHA256Managed, SHA384Managed, and SHA512Managed are usedin Cryptographic hashes algorithms / digital signature algorithms. We will see some code for symmetric cryptography. Symmetric cryptography uses aprivate key and an initialization vector for processing the encryption of data. Youknow that encryption is done using key (or password) that is provided by you. Theintended party also should know that key to decrypt the data. Initialization vector isused when the mode of encryption used is CipherMode.CBC (Cipher Block Chaining).Using this mode the data is encrypted in blocks. The third block of data is encryptedusing the output of second block and the second block is encrypted using the outputof first block. If this chaining process happens, what data is used for encrypting thefirst block? Hence we give an initialization vector which is used to encrypt the firstblock of data. The above code can be used to encrypt some value entered in a textbox. The abovecode uses the RC2 algorithm. You can also use any other algorithm like DES orRijndael. The data that is entered in a text box is encrypted upon clicking a button inthe form. All the above code is written under the click even of the button. Theencrypted data is displayed in a message box. You can also display it in anothertextbox in the form and then use an decryption code to decrypt the data in the othertextbox. mStream.Position = 0crypTalgorithms we have not specified any key or initialization vector. This is because that.Net uses the default key for encryption. You can use other types of cryptographic encryption and decryption to protect yourdata. The type of algorithm used for that purpose depends on the scenario of theapplication that is created. When you open up a guest book you should be aware that you will not only getaccolades for the services but also curses when you do not provide proper services.There are usually many so called bad guys who scold you and also write some filthystuff in your guest book. You should know how to handle such messages. You cansimply delete such messages from the guest book. Hence a guest book should havea feature for you to delete unwanted messages or messages that spoil yourreputation. Creating a guest book is easy if you use ASP.Net since you can avoid a lot of codingthat is done if you are using other technologies. You can use a simple Accessdatabase to hold the messages that are written by the users of the guest book. Allyou have to do is to read the message from the database and display it in yourwebform. To display them it is better to have a datagrid in the webform so that youcan incorporate paging to display limited number of messages in a particular page.When you are using a database you are certain to use the ADO.Net for inserting,reading, updating, and deleting the records in the database. For the sake ofsimplicity we will see some code that is involved in inserting the records usingADO.Net and some code to read the records and bind them to the datagrid so thatthe guest book can be viewed. You need to create an aspx page for the user to enter information about him and hiscomments about the site. For this purpose you need to have text box controls andlabel controls in your aspx page. For writing the comments you can have multi-linetext box control. To have multiple lines in the textbox you can set the ‘TextMode’property of the textbox to ‘MultiLine’. RequiredField validators can be used if do notwant the user to leave any field blank. Once you create this page for entering data,you have to write the code to insert this data in to the database. Assuming that youhave created the required fields in the database, the following code gives you anidea of how to insert the data in to the Guest Book database. If IsPostBack ThenDim Name As String = TextBox1.TextDim Country As String = TextBox2.TextDim Comment As String = TextBox3.TextDim conn As OleDbConnection = New OleDbConnection("----your connectionstringhere----")Dim qry As StringDim cmd As OleDbCommand qry = "Insert into Guest_Book (name,country,comment) VALUES ('" & Name & "',''"& Country & "','" & Comment & "'" & ")"cmd = New OleDbCommand(qry, conn) Tryconn.Open()cmd.ExecuteNonQuery()Catch e As ExceptionThrow eFinallyIf conn.State = ConnectionState.Open Thenconn.Close()End IfEnd TryEnd If Response.Redirect("viewGB.aspx") End SubWhen the user is redirected to the view page to view the guest book the data fromthe MSAccess database is retrieved and bound to a datagrid in the view page. Asample code for this process in the view page is given below: ds = New DataSet()cmd.Fill(ds, "Guest_Book")DataGrid1.DataSource = ds.Tables("Guest_Book").DefaultViewDataGrid1.DataBind()End SubPrivate Sub DataGrid1_PageIndexChanged(ByVal source As Object, ByVal e AsSystem.Web.UI.WebControls.DataGridPageChangedEventArgs) HandlesDataGrid1.PageIndexChangedDataGrid1.CurrentPageIndex = e.NewPageIndexBindDG()End Sub By changing the “qry” string you can achieve task like deleting records from thedatabase and this can be done by the owner of the website. If you work around theDataGrid during the design time you can set properties so that you can sort therecords displayed in the grid of the view page. Thus a simple guest book can becreated using the concepts of ADO.Net very easily in ASP.Net.
https://www.scribd.com/document/43862096/bala1
CC-MAIN-2019-39
refinedweb
3,682
56.15
Heads up! To view this whole video, sign in with your Courses Plus account or enroll in your free 7-day trial. Sign In Enroll [MUSIC] 0:00 Hi there. 0:04 This is James. 0:05 I'm a developer and teacher at tree house. 0:06 In this workshop we'll be taking a look at ASP.NET core, 0:09 Microsoft's latest web framework. 0:13 We'll start with answering the question, what is ASP.NET Core? 0:15 From the official documentation, ASP.Net Core is a new, open-source and 0:20 cross-platform framework for building modern cloud based Internet connected 0:25 applications, such as web apps, IoT apps, and mobile backends. 0:30 ASP.Net Core is a significant redesign of ASP.Net. 0:35 It's the biggest release of ASP.NET since version 1.0. 0:40 While some parts of ASP.NET Core will feel familiar such as MVC Controllers and 0:44 Views, other parts will seem completely new. 0:49 ASP.NET Core is a complete rewrite of the ASP.NET web framework. 0:52 It's no longer based on the System.Web assembly. 0:58 Breaking away from ASP.NET legacy code was necessary in order for 1:01 the ASP.NET development team to meet their stated design goals 1:06 of producing a fast cross-platform cloud friendly web framework. 1:10 ASP.NET Core places the focus on MVC and 1:14 Web API which have been merged into a single API. 1:18 We'll take a closer look at the convergence of MVC and 1:22 Web API later in this workshop. 1:25 Web forms and webpages are not currently available in ASP.NET Core, 1:27 nor are they likely ever to be. 1:32 Microsoft has made it clear that web forms and web pages will 1:35 remain as part of the full .NET framework and not brought into ASP.NET Core. 1:40 The ASP.NET team does have a new feature on the roadmap named view pages 1:45 that is similar to the functionality of web pages. 1:50 See the teacher's notes for more information. 1:53 ASP.NET Core runs on either .NET Core or the full .NET framework. 1:55 This gives you the flexibility to choose the target framework 2:01 that makes the most sense for your situation. 2:04 .NET Core is a new cross-platform version of .NET that runs on Windows, 2:06 Linux or Mac OS. 2:12 .NET Core has a flexible deployment model that gives you the option to deploy it 2:14 along with your application in addition to the more traditional side-by-side user or 2:19 machine-wide deployment options. 2:24 Only a subset of the .NET frameworks API surface has been implemented in .NET Core. 2:27 For instance, 2:32 the system drawing namespace is currently only partially implemented in .NET Core. 2:33 If your application needs to manipulate bitmaps 2:39 you'll need to use a third party library that's compatible with .NET core. 2:41 Or target the full .NET Framework. 2:46 .NET Core only supports a single app model, console apps. 2:49 While that might seem limiting, 2:53 it's possible to build other app models on top of it which is what ASP.NET Core does. 2:55 We'll see it later in this workshop how that works. 3:01 The .NET command line interface or CLI shipped as part of the .NET Core SDK. 3:04 The .NET CLI is a set of commands that allows you to create, build, run, 3:10 publish, test and package .NET Core apps all from the command line. 3:16 Having the CLI available, ensures that you can develop .NET Core apps 3:21 including ASP.NET Core apps, regardless of what platform or tools you're using. 3:25 For instance, 3:30 you can develop apps on Linux using the text editor of your choice. 3:31 CLI is even used by Visual Studio. 3:36 When using Visual Studio to develop .NET Core apps Visual Studio 3:39 delegates to the .NET CLI to build, run and publish your app. 3:43 ASP.NET Core and .NET Core are fully open source projects being hosted on GitHub. 3:48 Development is being done completely out in the open. 3:54 You can monitor or 3:58 contribute to the teams ongoing development discussions via GitHub issues. 3:59 Or you can fork any of the repos, fix a bug or 4:04 implement a feature and issue a poll request against the main repo. 4:07 ASP.NET Core is another example of the new Microsoft. 4:11 A Microsoft that is embracing open source development. 4:16 Unlike previous versions of ASP.NET, 4:20 ASP.NET Core is not a single monolithic assembly. 4:22 Instead it's delivered as a set of granular and well factored NuGet packages. 4:27 This gives you a true pay-for-what-you-use-model. 4:32 You only reference and deploy the packages that your application needs. 4:35 In order to realize ASP.NET Cores cross-platform design goal, 4:40 Microsoft needed a cross-platform server for running ASP.NET Core apps. 4:44 Kestrel is that server. 4:49 Kestrel is a cross-platform, managed web server based on libuv. 4:51 libuv is a multi-platform support library with a focus on 4:56 asynchronous IO that was developed primarily for 5:00 NodeJS, but is used by other projects including now, Kestrel. 5:04 Kestrel is the only supported web server for running ASP.NET Core apps. 5:09 IIS is no longer directly supported, 5:14 meaning that IIS does not host ASP.NET Core apps within its own process. 5:17 Instead IIS is used as a reverse proxy to Kestrel using 5:23 the ASP.NET Core module, HTTP module. 5:28 This is the same overall approach used for hosting NodeJS apps in IIS. 5:32 ASP.NET.Core apps running on Castro have 5:37 been able to achieve amazing performance benchmarks. 5:41 In February 2016 ASP.NET.Core achieved 1.15 million requests per second. 5:44 In a sense exceeded that number. 5:52 To put that number into perspective, 5:54 1.15 million requests per second represents a 2300% 5:58 gain over ASP.NET 4.6 or 800% gain over NodeJS. 6:03 The second decimal place, 0.05 million or 6:08 50,000 is around the total number of requests per second that 6:12 ASP .NET 4.6 could perform of the same type on the same hardware. 6:16 Most applications will never need this kind of throughput. 6:22 But having this kind of headroom will help ensure that your applications feel fast 6:25 and responsive. 6:30 As previously mentioned, ASP.NET Core runs on Windows, Linux, and macOS. 6:32 This is the first time that this is possible 6:38 using Microsoft supported runtimes and frameworks. 6:41 Cross-platform support opens up new development and deployment scenarios, 6:44 including being able to support mixed environment development teams. 6:49 And deploying your applications on to cloud hosted Linux virtual machines or 6:53 containers. 6:58 In this workshop I'll be working with both Windows and macOS. 6:59 To get started with ASP.NET Core development visit the new dot.net website, 7:04 where you can find detailed installation instructions and 7:10 downloadable installers for the platform of your choice. 7:13 In the next video we'll use the .NET CLI to create our first project. 7:17
https://teamtreehouse.com/library/what-is-aspnet-core?t=169
CC-MAIN-2020-45
refinedweb
1,330
77.43
This entry is part of the Maximo Java Development series. Sometimes you have to implement some complex logic in workflows or escalation and you feel limited by the out-of-the-box Maximo actions. In these cases you can unleash the Java power and code your algorithm in a custom action class. In order to create a custom action class, you must extend the psdi.common.action.ActionCustomClass class. package cust.actions; import java.rmi.RemoteException; import psdi.common.action.ActionCustomClass; import psdi.mbo.MboRemote; import psdi.util.MXException; public class SampleAction implements ActionCustomClass { public SampleAction() { super(); } public void applyCustomAction(MboRemote mbo, Object[] params) throws MXException, RemoteException { // Write custom code here } } As usual… compile, rebuild EAR and redeploy. For a full example of a custom action class look here. To call this action from a workflow or escalation you have to register the new Maximo action. Go in System Configuration – Platform Configuration – Actions and create a new action. Choose Custom Class as Type, select the object for which the custom applies and provide the full class name (cust.actions.SampleAction) in the value field. Here is how the new Action should look. 8 thoughts on “Sample Action Class” Could you provide some additional details on how you would extend ActionCustomClass to move data from the base object to another object. I would like to have workflow invoke a custom action that copies data from one object to another and I am not sure how to tackle this objective. In the applyCustomAction you have a reference to the Mbo. Use relationships to navigate MBOs and update data accordingly. For example, if you want to set all the description of the child POLINES of a PO do something like this. String desc = mbo.getString("DESCRIPTION"); MboSetRemote polines = mbo.getMboSet("POLINES"); for(MboRemote poline=polines.moveFirst(); poline!=null; poline=polines.moveNext()) { poline.setValue("DESCRIPTION", desc); } Thanks for the quick Response Bruno, Is there a way to output the contents of the string polines in the systemOut.log? I have done customizations using the integration root logger, but I am not sure how this is done when developing custom actions. Also, POLINES is the name of the relationship that is used to map PO to POLINE correct? You can use whatever logger you want. Yes POLINES is the name of the relationship from PO object to POLINES as defined in the Database Configuration. hi, can u explain how can we take custom class parameters? there are 2 parameter in this class(mboremote and object). i want to take object parameter. thank you My applyCustomAction function gets called repeatedly after performing operation in first iteration. But continues to get called, Why it is so ? Can you help ? Could you provide some additional details on how you would extend ActionCustomClass to perform select action method for application. e.g. I want to create Investigation from Incident using Action. and for this standard Application Action has not supported the action. How can I achieve this using custom class in action ? which status i can do action using custom class
https://bportaluri.com/2012/06/sample-action-class-java-maximo.html
CC-MAIN-2021-43
refinedweb
512
50.53
I am trying to store a file into an ArrayList and then have user input from console search for an element in the Arraylist and return found or not. It keeps giving me -1. public class arrayl { public static void main(String args[] ) throws FileNotFoundException { System.out.println("Please enter title of book: "); Scanner input = new Scanner(System.in); String search = input.next(); //file with absolute path Scanner file = new Scanner(new File("c:\\Documents and Settings\\name\\Desktop\\Book.txt")); //arraylist named as test ArrayList<String> test = new ArrayList<>(); //creating loop that will read file while (file.hasNext()){ //adding file to arraylist test.add(file.next()); } //Using users input, named search, to find element in the arraylist and print return found or not System.out.println(test.indexOf(search)); file.close(); }
https://www.daniweb.com/programming/software-development/threads/439279/need-immediate-assistance-with-java-arraylist
CC-MAIN-2018-43
refinedweb
132
59.4
I have a problem with this part here, I want to sort the students in alphabet order, can you help me? I tried to swap between elements but the issue is student 2 and 4 info s[2] and s[4] show as random text. The code with issue: struct student { char name[31]; int grade1; int .. Category : alphabet I am trying to count the total of different alphabets used in a vector of strings. for exemple if inside the vector the strings are ; Marsha, Rose, Joe the output should be : 9 because it counts the duplicate characters only one time. Can anyone help? Source: Windows Que.. I’m making a code for cipher that reads alphabet in it’s binary code. Is there a way to implement custom alphabet (not using ASCII)? For example alphabet={a,b,c,d,e,…,z,],[,.,…, ,-} and for each character there’s a number 0,1,…,63. So, the bijetion will be from element of alphabet to 6bit number. How to male this implementation using simple .. // C++ program to count the uppercase #include<iostream> #include<fstream> #include <string> using namespace std; // Function to count uppercase int Count ( string str ) { int upper = 0; for (int i = 0; i < str.length(); i++) { if (str[i] >= ‘A’ && str[i] <= ‘Z’) upper++; } return upper; } // Driver .. Recent Comments
https://windowsquestions.com/category/alphabet/
CC-MAIN-2021-39
refinedweb
219
66.44
Setting up Cloud Operations for GKE My interest in observability in Google Cloud developed in large part in the context of working with GCP customers running workloads on GKE, and one of my very first posts here covered using Stackdriver for those workloads. The very first episode of Stack Doctor also went over what were at the time the “new” GKE monitoring capabilities. This was over two years ago, and there have been some great updates to those capabilities since then. I thought it was time to revisit Cloud Ops for GKE, have another look at the dashboards, and try out the new capabilities. Let’s dive in! The basics Right away, the new GKE monitoring dashboard looks very different from what we saw released at Kubecon in May of 2018. Instead of 3 tabs — infrastructure, workloads, and services — you now have lists of all the different entities in the workspace (which, as you may recall, can aggregate monitoring information from multiple projects). The first thing I thought of when I saw this was “Well, that’s great, but there is a default namespace in every cluster, how will I ever find what I need?” As it turns out — someone has already thought of that! There’s a really cool filtering feature that will actually help you to find exactly what you’re looking for. In this example, if you have a copy of the “frontend” service running in three different clusters — the filter lets you select the exact one you want. Once you apply the filter, the entire dashboard is filtered to match: One of the things that’s been kind of hard to do in the past is to get an aggregated view of the data. For example, what does my resource utilization look like across my namespace? This new view makes it really easy to get this kind of aggregation — and it will scale no matter how many resources are being aggregated, even if you have thousands of pods across hundreds of namespaces. But if you do want to see all of those resources — you can click View All. That will let you see all of the entities in that category. If that list is too overwhelming — you can filter from here, too! You can still select a row in the table to get its details. For example, you can see metrics for a pod by clicking on it, which opens the details panel: From there, click on the Logs tab to get the logs for the pod: If needed — you can filter logs by severity: Click the Open in Logging button: That opens the (new!) Logs Viewer with the query to get those logs pre-populated and executed: One other thing I really like is that you can easily create an Alerting Policy from the Metrics tab of the details screen: If you’ve been following me for a while, you probably know that I don’t necessarily think it’s a good idea to alert on these kinds of infrastructure metrics, but I can absolutely envision a use case where you might need to know about, for example, hitting memory limits or something like that. In summary… I’m really happy to see the team make great progress on this experience in the last two years, and I really like where this is going. Next time, I want to approach this from a different angle by forcing an alert/incident and seeing how useful it’s going to be for troubleshooting. Thanks for reading, and stay healthy out there!
https://medium.com/google-cloud/setting-up-cloud-operations-for-gke-a21b49979693
CC-MAIN-2021-31
refinedweb
594
62.72
Using MRI 1.9.2+? Switch to pry-debugger. Using MRI 2+? Switch to pry-byebug. Same features as pry-nav but with faster tracing, breakpoints, and more. pry-nav Simple execution control in Pry Teaches Pry about step, next, and continue to create a simple debugger. To use, invoke pry normally: def some_method binding.pry # Execution will stop here. puts 'Hello World' # Run 'step' or 'next' in the console to move here. end pry-nav is not yet thread-safe, so only use in single-threaded environments. Rudimentary support for pry-remote (>= 0.1.1) is also included. Ensure pry-remote is loaded or required before pry-nav. For example, in a Gemfile: gem 'pry' gem 'pry-remote' gem 'pry-nav' Stepping through code often? Add the following shortcuts to ~/.pryrc: Pry.commands.alias_command 'c', 'continue' Pry.commands.alias_command 's', 'step' Pry.commands.alias_command 'n', 'next' Debugging functionality is implemented through set_trace_func, which imposes a large performance penalty. pry-nav traces only when necessary, but due to a workaround for a bug in 1.9.2, the console will feel sluggish. Use 1.9.3 for best results and almost no performance penalty. Contributors - Gopal Patel (@nixme) - John Mair (@banister) - Conrad Irwin (@ConradIrwin) - Benjamin R. Haskell (@benizi) - Jason R. Clark (@jasonrclark) Patches and bug reports are welcome. Just send a pull request or file an issue. Project changelog.
http://www.rubydoc.info/gems/pry-nav/frames
CC-MAIN-2016-40
refinedweb
229
63.36
If you have worked with Java at all in the past, it is very likely that you have come across a NullPointerException at some time (other languages will throw similarly named errors in such a case). Usually this happens because some method returns null when you were not expecting it and thus not dealing with that possibility in your client code. A value of null is often abused to represent an absent optional value. Kotlin tries to solve the problem by getting rid of null values altogether and providing its own special syntax Null-safety machinery based on ?. Arrow models the absence of values through the Option datatype similar to how Scala, Haskell and other FP languages handle optional values. Option<A> is a container for an optional value of type A. If the value of type A is present, the Option<A> is an instance of Some<A>, containing the present value of type A. If the value is absent, the Option<A> is the object None. import arrow.* import arrow.core.* val someValue: Option<String> = Some("I am wrapped in something") someValue // Some(I am wrapped in something) val emptyValue: Option<String> = None emptyValue // None Let’s write a function that may or not give us a string, thus returning Option<String>: fun maybeItWillReturnSomething(flag: Boolean): Option<String> = if (flag) Some("Found value") else None Using getOrElse we can provide a default value "No value" when the optional argument None does not exist: val value1 = maybeItWillReturnSomething(true) val value2 = maybeItWillReturnSomething(false) value1.getOrElse { "No value" } // Found value value2.getOrElse { "No value" } // No value Checking whether option has value: value1 is None // false value2 is None // true Option can also be used with when statements: val someValue: Option<Double> = Some(20.0) val value = when(someValue) { is Some -> someValue.t is None -> 0.0 } value // 20.0 val noValue: Option<Double> = None val value = when(noValue) { is Some -> noValue.t is None -> 0.0 } value // 0.0 An alternative for pattern matching is performing Functor/Foldable style operations. This is possible because an option could be looked at as a collection or foldable structure with either one or zero elements. One of these operations is map. This operation allows us to map the inner value to a different type while preserving the option: val number: Option<Int> = Some(3) val noNumber: Option<Int> = None val mappedResult1 = number.map { it * 1.5 } val mappedResult2 = noNumber.map { it * 1.5 } mappedResult1 // Some(4.5) mappedResult2 // None Another operation is fold. This operation will extract the value from the option, or provide a default if the value is None number.fold({ 1 }, { it * 3 }) // 9 noNumber.fold({ 1 }, { it * 3 }) // 1 Arrow also adds syntax to all datatypes so you can easily lift them into the context of Option where needed. 1.some() // Some(1) none<String>() // None Arrow contains Option instances for many useful typeclasses that allows you to use and transform optional values Transforming the inner contents import arrow.typeclasses.* Option.functor().run { Some(1).map { it + 1 } } // Some(2) Computing over independent values Option.applicative().tupled(Some(1), Some("Hello"), Some(20.0)) // Some(Tuple3(a=1, b=Hello, c=20.0)) Computing over dependent values ignoring absence Option.monad().binding { val a = Some(1).bind() val b = Some(1 + a).bind() val c = Some(1 + b).bind() a + b + c } //Some(value=6) Option.monad().binding { val x = none<Int>().bind() val y = Some(1 + x).bind() val z = Some(1 + y).bind() x + y + z } //None Contents partially adapted from Scala Exercises Option Tutorial Originally based on the Scala Koans.
http://arrow-kt.io/docs/datatypes/option/
CC-MAIN-2018-17
refinedweb
603
58.89
The DataGridView .NET, not the cells themselves. DataGridViewColumns .NET assembly from RustemSoft is a DataGridView Columns software package specifically designed for .NET developers. The assembly allows you to use all strengths of the MS Windows .NET DataGridView Columns, that make it easy to build professional and forcing user interfaces. code samples that describe the concepts and techniques that you can use to build DataGridView features into your applications. ASP DataGridColumns .NET assembly More about ASPDataGridColumns.dll Download ASPDataGridColumns.dll Order ASPDataGridColumns.dll Skater .NET Obfuscator More about Skater .NET Obfuscator Download Skater .NET Obfuscator Order Skater .NET Obfuscator The .NET:. For this case we have to define two string arrays with key fields' names MasterFields and ChildFields. To get the filtering we must identify Master and Child tables' key fields. These fields names in both arrays must have the same order sequence.. Controls .NET assembly (WinForms) More about RustemSoft.Controls.dll Download RustemSoft.Controls.dll Order RustemSoft.Controls.dll. Syntax DataGridViewPictureColumn() DataGridView Calculator Column Calculator DataGridView Column control provides a calculator environment with Real and Complex arithmetic support. This formatted intelligent Calculator Column Masked TextBox Column The RustemSoft DataGridView MaskedTextBox Column control provides restricted data input as well as formatted data output. This control supplies visual cues about the type of data being entered or displayed. It uses a mask to distinguish between appropriate and improper user input. When the DataGridView MaskedTextBox Column cell is selected at run time, it represents the mask as a series of prompt characters and optional literal characters. Each editable mask position, representing a required or optional input, is shown with a single prompt char. For example, the number sign # is often used as a placeholder for a numeric character input. You can use the PromptChar property to specify a custom prompt character. The HidePromptOnLeave property determines if the user sees the prompt characters when the DataGridView MaskedTextBox Column cell loses input focus. Syntax DataGridViewMaskedTextBoxColumn() DataGridView Print Class Obviously the DataGridViewPrint class is not a DataGridView column control. The service class is intended to help you to create a print output based on your DataGridView content. The class has been included into Print Preview dialog (on your .NET form) to draw the DataGridView object content that should be printed. An object of the class is used for a .NET PrintDocument object. Syntax DataGridViewPrint(PrintDocument1, DataGridView1, bBlackWhite) PrintDocument1 - System.Drawing.Printing.PrintDocument reusable object that sends output to a printer DataGridView1 - System.Windows.Forms.DataGridView object that content you are going to print bBlackWhite - boolean parameter that defines if you like to use "Black and White" printing mode or you would like to send to printer the real coloring that your DataGridView control has currently on your form. Suppose you are building a project using Visual Studio.NET, and you decide that you want to start consuming RustemSoft DataGridViewColumns .NET assembly for a .NET DataGridView control on your Windows form. The first step that you will generally take is, you will add a reference to the DataGridViewColumns .NET assembly, which is residing in some directory on your PC hard drive. Visual Studio .NET will then add a new item under Solution Explorer called 'References', and it will create a row node underneath it called DataGridViewColumns. In order to add the reference to DataGridViewColumns .NET assembly please follow the steps: Select Project from the menu bar Choose Add Reference from the drop down menu Click on the Browse button Browse to and choose DataGridViewColumn.DataGridViewColumns C# using RustemSoft.DataGridViewColumns; C++ #using <DataGridViewColumnsTrial.dll> using namespace RustemSoft; Download the DataGridViewColumns .NET assembly code samples for VB.NET and C# that show how you can use the RustemSoft DataGridView Columns in Windows Forms .NET DataGridView. Note DataGridView Windows Forms control can accept a DataSet for its DataSource property and automatically display the contents of ONLY one of the DataTables in the DataSet unlike .NET DataGrid control can show a hierarchical view of Data Tables. This is a big disadvantage of DataGridView .NET Windows Forms control.
http://www.rustemsoft.com/datagridview_columns2.asp
CC-MAIN-2016-07
refinedweb
666
50.94
Created on 02-03-2017 04:56 PM - edited 08-17-2019 05:08 AM I was looking for a way to easily forward and analyze provenance data that is available in nifi. There were a couple of options available. option 1 is a very techy option , you could point you UI directly to the rest api and present a nice provenance visual with bulk replay capabilities. But, then it makes the developer responsible for keeping up with changes in the nifi rest api. It would be nice if we did not have direct dependency. Also, you might want to lockdown the rest api in production. option 2 is very easy , but it is limited in where i can send those provenance events. The apache nifi eng team resolved this situation with a ScriptedReportingTask controller service. It gives you an easy way of setting up the provenance reporting in Nifi and forwarding it to an end point of your choice. You also do not have a direct dependency between your application and nifi rest api. You can use ScriptedReportingTask to massage the events into a format that works with you application/endpoint. I chose groovy as the language for my script, but there is options for python,javascript and a few others. once you are logged in to nifi . Click the menu on the top right corner. Select controller settings option. On the Controller setting dialog, choose the Reporting Tasks tab. Click the + on the top right corner to create a new reporting task. On the Add reporting task dialog, search for ScriptedReportingTask. Double click on ScriptedReportingTask option in the results or select the row and click Add. You will see a new ScriptedReportingTask in the reporting tasks list. Click on the pencil icon , to edit the reporting task. You will see a reporting task window. Select groovy as the Script Engine choice and paste the script below in Script Body. Make sure to change the location of the file where your events will be written to. import groovy.json.*; import org.apache.nifi.components.state.StateManager; import org.apache.nifi.reporting.ReportingContext; import org.apache.nifi.reporting.EventAccess; import org.apache.nifi.provenance.ProvenanceEventRepository; import org.apache.nifi.provenance.ProvenanceEventRecord; import org.apache.nifi.provenance.ProvenanceEventType; final StateManager stateManager = context.getStateManager(); final EventAccess access = context.getEventAccess(); final ProvenanceEventRepository provenance = access.getProvenanceRepository(); log.info("starting event id: " + Long.toString(1)); final List<ProvenanceEventRecord> events = provenance.getEvents(1, 100); log.info("ending event id: " + events.size()); def outFile = new File("/tmp/provenance.txt"); outFile.withWriter('UTF-8') { writer -> events.each{event -> writer.writeLine(new JsonBuilder(event).toPrettyString()) }} Click ok and apply. Click on the "Play " Button to active the reporting task. I had set the scheduling frequency for the task on mine to 10 secs, so i could see the results right away. You can set it to a higher value as needed. You should the logs appear in /tmp/provenance.txt , in json format. you could use other formats if needed and also may be not prettify for better performance. The ScriptReportingTask is repsponsible for the ReportingContext , which is available to your scripts as the context object. You can log information to the nidi-log using the ComponentLog log object, which is also passed to you by the reporting task. If you need anyother variables to be set in from the nifi task, you can define them as dynamic properties. My script is very simple, it will look at 100 provenance events from the first provenance event. You can use the statemanager to keep track of the last provenance event that you received. You look at the implementation by @jfrazee to see how we can incrementally collect provenance events. Thank you to @Matt Burgess for putting together this very useful reportintask component. Hope this is useful.
https://community.cloudera.com/t5/Community-Articles/Using-the-ScriptedReportingTask-in-NiFi/ta-p/249364
CC-MAIN-2022-27
refinedweb
636
60.51
So I am curious lets say I have a class as follows class myClass: def __init__(self): parts = 1 to = 2 a = 3 whole = 4 self.contents = [parts,to,a,whole] del parts del to del a del whole Never, unless you are very tight on memory and doing something very bulky. If you are writing usual program, garbage collector should take care of everything. If you are writing something bulky, you should know that del does not delete the object, it just dereferences it. I.e. variable no longer refers to the place in memory where object data is stored. After that it still needs to be cleaned up by garbage collector in order for memory to be freed (that happens automatically). There is also a way to force garbage collector to clean objects - gc.collect(), which may be useful after you ran del. For example: import gc a = [i for i in range(1, 10 ** 9)] ... del a # Object [0, 1, 2, ..., 10 ** 9 - 1] is not reachable but still in memory gc.collect() # Object deleted from memory Update: really good note in comments. Watch for other references to the object in memory. For example: import gc a = [i for i in range(1, 10 ** 9)] b = a ... del a gc.collect() After execution of this block, the large array is still reachable through b and will not be cleaned.
https://codedump.io/share/dakaLDWkYvWb/1/when-am-i-supposed-to-use-del-in-python
CC-MAIN-2016-50
refinedweb
232
74.39
With! Dev environment and getting started A note on versions: the most recent version of Android is 4.2 (Jelly Bean), but as you can see from this Wikipedia chart, there aren't many people using it yet. You're better off coding for one or both of 4.0 (Ice Cream Sandwich) or 2.3 (Gingerbread), especially as Android is entirely forwards-compatible (so your 2.3 code will run on 4.2) but not always backwards-compatible. The code here should work on either 4.0 or 2.3. The quickest way to get your dev environment set up is to download the Android Bundle. You'll also need JDK 6 (not just JRE); note that Android is not compatible with gcj. If you already have Eclipse, or wish to use another IDE, you can set it up for Android as described here. Now, create a project called Countdown either using Eclipse, or from the command line. I set the BuildSDK to 4.0.3, and minimum SDK to 2.2, and (in Eclipse) used the BlankActivity template. My First Android Project: Layout For our very first program, we're going to do is to show a timer that counts down from 10 seconds when you click a button. Before writing the code, let's create the interface -- what the user will see when they start the app. Open up res/layout/activity_countdown.xmlto create an XML layout, using either the Eclipse graphical editor, or a text/XML editor, to enter this: <RelativeLayout xmlns: <TextView android: <Button android: </RelativeLayout> Note the references to @string/start and @string/__00_30. These values are stored in res/values/strings.xml: <string name="start">Start</string> <string name="_00_30">00:30</string> This illustrates the standard way of referring to Android resources. It's best practice to use string references rather than hard-coding strings. My First Android Project: Code Next, open up the CountdownActivity.java file in your editor, ready to write some code. You should already have an onCreate() method stub generated. onCreate() is always called when the Activity is first created, so you'll often do setup and app logic startup here. (Eclipse may also have created an onCreateOptionsMenu()method stub, which we'll ignore for now.) Enter this code: public class CountdownActivity extends Activity { private static final int MILLIS_PER_SECOND = 1000; private static final int SECONDS_TO_COUNTDOWN = 30; private TextView countdownDisplay; private CountDownTimer timer; @Override public void View.OnClickListener() { public void onClick(View view) { try { showTimer(SECONDS_TO_COUNTDOWN * MILLIS_PER_SECOND); } catch (NumberFormatException e) { // method ignores invalid (non-integer) input and waits // for something it can use } } }); } } You'll notice the thing that makes this a surprisingly easy first project: the Android API includes a CountDownTimer that you can use. We set up this, and the countdown display, as private member variables. In onCreate() we use the built-in setContentView method to grab our XML layout The R.foo.barsyntax is a standard way to refer to Android XML resources in your code, so you'll see it a lot. findViewById is another method you'll use a lot; here, it grabs the display and the Start button from the XML layout. For the Button to work when clicked, it needs an OnClickListener. This is an interface, so must be subclassed. We could create a whole new MyButton class to do this, but this is overkill for a single button. Instead, we do it inline, creating a new OnClickListener and its onClick() method. Ours simply calls showTimer() on the number of milliseconds we want to use (currently hard-coded). So what does showTimer()do? private void showTimer(int countdownMillis) { if(timer != null) { timer.cancel(); } timer = new CountDownTimer(countdownMillis, MILLIS_PER_SECOND) { @Override public void onTick(long millisUntilFinished) { countdownDisplay.setText("counting down: " + millisUntilFinished / MILLIS_PER_SECOND); } @Override public void onFinish() { countdownDisplay.setText("KABOOM!"); } }.start(); } The CountDownTimer class does most of the work for us, which is nice. Just in case there's already a running timer, we start off by cancelling it if it exists. Then we create a new timer, setting the number of milliseconds to count down (from the showTimer() parameter) and the milliseconds per count interval. This interval is how often the onTick()callback is fired. CountDownTimer is another abstract class, and the __onTick()__ and __onFinish()__ methods must be implemented when it is subclassed. We override onTick() to decrease the countdown display by a second on every tick; and override onFinish() to set a display message once the countdown finishes. Finally, start() sets the timer going. If you select 'Run' in Eclipse, you can choose to run this as an Android app, and an emulator will automatically be generated and run for you. Check out the Android docs if you need more information on setting up an emulator, or on running an app from the command line. Congratulations, you've written your first Android app! In the second part of this series, we'll have a closer look at the structure of an Android app, and make some improvements to the timer to input a countdown time, a Stop button, and menu options. We'll also look at running it on a physical phone rather than the software emulator. For more information in the mean time, you can check out the Android Development Training section of The Linux Foundation's Linux training website. kinjal Said: Nice gaiudline for me, thank. You!!!!!!!!!!! Abdoulaye Siby Said: Nice guideline indeed. But I must add one thing though ... Android is NOT forward compatible. They are starting to tighten the rules to get rid of badly designed applications. For example, an application will be terminated if it tries to open a network request or a socket connection from the main UI thread. All these will finally force developers to write responsive applications. Some of my own apps are still working well on Honeycomb, Gingerbread, and Ice Cream Sandwich, but not on Jelly Bean. Cheers Roger Said: Then Googles own RSS -Reader is danger of being closed too i guess. Abdoulaye Siby Said: I haven't used that app yet. But I am sure that they will update it before it becomes unusable. kaueeeee Said: bevkuff hi rhega yr tu toh....teri kasam chadgamas Said: question.how & where can i search of my appli of my googleplay of this unit ts1duo myphone unit db Said: When, oh when will we have an alternative to the vile langage java? DavidChipman Said: What's wrong with Java? I'll admit it's not my first choice for programming either, but "vile"? Craig Hubley Said: I'd go with "vile", too. Just very bad object model, never really was write-once-run-everywhere. Some good languages have been written IN Java though like Clojure. Abdoulaye Siby Said: Do you mind using JavaScript? You can try Titatium Studio from AppCelerator at KIRAN SHETTY Said: YEAH CrizZ Said: With the Adnroid NDK you could use C++ for Android development. CJ Said: Awesome! whitehawk66 Said: Oh my: I'll get back to this once I come up with a truly inspired notion. Staring into a computer screen churning out this kind of language would be a soul killer to me. Thankfully, I know how to create other things. Peace scottG Said: Great guide ty sadik Said: for me Nice gaiudline for Android programming Maria Said: Know something, I had no desire programirovat Android. Be kind in the future, please contact me in Russian. benny Said: For me it's just another new world of discovery! ToanPham Said: thank u guy, nice job Berka Said: Hello i can`t find CountdownActivity.java Where is it? Hope someone can help me! Dhiren Dash Said: On the left side pane, drop down "src", you will see, "com. . ". Drop down again and you will have a file with .java extension. And that s it. Dhiren Dash Said: This is not a tutorial for beginners. And there are no imports too. Christarius Said: NIce guide, thanks! Berka Said: Thanks but When i drop down The com.. I have a java filé called mainactivity is this The filé iam looking för? Vijay Said: The example didn't work for me without adding the following includes to CountdownActivity.java: import android.app.Activity; import android.widget.TextView; import android.os.CountDownTimer; import android.widget.Button; import android.view.View; otherwise, thanks for the tutorial! cab jones Said: I am confused about "need JDK 6 not just JRE." I downloaded the latest Android package (Windows). Java -version reports 1.7.0_10 and I have the folder C:\Program Files\Java\jdk1.7.0_10, ...\jre7. Perhaps that means I have JDK 7, but I can't precisely verify that since the caution was "not JRE). By the way, I have Cygwin installed, so I can use which or whatever. How do I verify that I have JDK 6 (at least)? I've done a tiny bit of one tutorial encountered no problems--perhaps I am being too much a worry-wart. ksanger Said: I was expecting a tutorial for a beginner. I've been at it all day trying to configure Eclipse and the Android SDK before finding a bundle. Actually had Eclipse setup ok until I upgraded the SDK which was no longer compatible and required an update to Eclipse which broke everything. So here I am trying to write a first program. Not a total noob, I've written in java using netbeans. Have not written for Android nor used eclipse. I am confused by the next step. "Now, create a project called Countdown either using Eclipse, or from the command line. I set the BuildSDK to 4.0.3, and minimum SDK to 2.2, and (in Eclipse) used the BlankActivity template." I had alreay run the tool Android and installed Android 2.3. Don't know what is meant by set the BuildSDK to 4.0.3 and the minimum SDK to 2.2? Does that mean install Android 2.2 using the tool "Android"? Or is there a setting in eclipse? Then take the next line. "used in the BlankActivity template". If in eclipse I sellect File, New Project, and then open up Android I get choices of "Android Application Project", "Android Project from Existing Code", "Android Sample Project", or "Android Test Project". Which of these is a BlankActivity template? Then again, if I close eclipse and open it up again, then select the file icon New, then open Android, I get different choices of "Android Activity", "Android Application Project", "Android Icon Set", "Android Object", "Android Project from Existing Code", "Android Sample Project", "Android Test Project", "Android XML File", "Android XML Layout File", "Android XML Values File", or "Template Develoment Wizard". Selecting Activity, Next, brings up "Blank Activity" as a choice. By creating a project called CountdownTimer will calling my new activity CountdownTimer do the same thing? Or do I need to create an Android project and add a blank activity to it? The blank activity form asks me to select a project. So you must mean create an Android project, but haven't specified which one. Then we must have to add an activity? In one paragraph I am lost again. I would not rate this as a beginner's first tutorial. Dark Penguin Said: I'm having a lot of trouble as well. I've tried one of the WROX books and two or three of the online tutorials, but there are always unresolved references or menu options missing due presumably to version conflicts. In this I have the import of CountDownTimer in place but I can't seem to use its constructor. For that matter, in the code presented I see where timer is declared but I don't see any initialization for it. Wish I knew Java better; I've hardly looked at it since the siren call of C#. Work order management Said: the Service Proz mission is "to provide practical, efficient, dependable and logical software that improves the operational efficiencies of home service businesses." Since the introduction of Cloud-based, on-demand service management software, the entire organization is connected all-day, every day, and anywhere in the world with the information they need. There are no more disagreements or misunderstandings because all information is always available. The Office Manager sees the full picture of the entire business including daily work orders, the schedule, customer appointments, and billing. The Dispatch team sees the planned schedule, its current progress, and swiftly reacts to changes. The Field Technician sees their scheduled work and all necessary details on their smartphone or tablet such as when, where, the type of work, skills needed, and customer details. work order management Manjunath Said: Nice Article, thanks Mani Said: Nice tutorial for me. How to I download the api level 10 manualy. Please tell the link. Abdoulaye Siby Said: I think it is safer and easier to use the tools provided by the Android SDK manager either in the Android Developer Tools (ADT) or in Eclipse or on the command line. The detail explanation is on the Android Developer site. Unfortunately I don't have the direct URL to the page where it shows the command line instructions, but I can tell you that it is part of the very first steps explaining how to setup an Android development environment. Good luck. chris Said: "This tutorial assumes some basic familiarity with Java, XML, and programming concepts, but even if you're shaky on those, feel free to follow along!" Sorry, it only assumes a working knowledge of Eclipse [about 30 hours] and how xml and java interact in Android [20 hrs]. In this respect, it is no different than most non audio-visual tutorials. Massive knowledge is assumed. DavidChipman Said: Some "tutorial", then.... It's not for "Beginners" as the title suggests. Alex Said: This is actually for the very beginners , this was my first application , and i manage it ! Paul A. Nardi Said: I agree that a little more infrastructure i.e., how to set up and RUN this app would be appropriate for this tutorial. This is usually the part that beginners struggle with the most and bloggers seem to have the most trouble explaining. Dark Penguin Said: If you're using Eclipse the typical procedure is that you set up an Android Virtual Device which you can configure to resemble the device your app should run on. Look for the AVD Manager icon in the Eclipse menu bar (the IDE's menu, not the Windows menu bar). Of course, you can also connect a real Android-powered device into the USB port and run your app on it. This page explains how to do it either way. This seemed a great tutorial, but it all went pear shaped for me when I tried to do the next part on creating GUIs. The xml files it tells me to modify either aren't there or they're not where they are supposed to be per the examples, and by taking my best educated guess as to which file I'm supposed to edit works out about as well as you'd expect. Arindam at venturehire Said: nice post,thanks Clint Mar Said: Nice code .. tnx for this :) rakesh Said: really nice tutorial for Android beginner ! Very informative and fruitful keep writing like this. Thanks Tanzanite Infotech hicham Said: very useful tut,but quite complicated for beginners. ps our developer "juliet kemp" is really pretty! wahyu Said: OK thank's for this tutorial.... alot Ravi Said: Worth trying this:. These guys are providing free online classes for android. Rahul Said: Nice guide thanks Cristian Said: Very nice guide Juliet. Its appreciated طاهره Said: سلام دوست من عالی بود. Ivan Said: If I open "src" there is only "Android test" and "Main". Im stuck here, help me plz LMDXD Said: Tubol!
http://www.linux.com/learn/docs/683628-android-programming-for-beginners-part-1
CC-MAIN-2015-27
refinedweb
2,641
66.23
Corejava Interview,Corejava questions,Corejava Interview Questions,Corejava regardless of any other intentions. A concrete class implementing both interfaces can... above in the hierarchy). Java programming language allows an abstract class... programming language, Marker interfaces are those interfaces that don't have any corejava - Java Beginners corejava pass by value semantics Example of pass by value semantics in Core Java. Hi friend,Java passes parameters to methods using pass... arguments to the method call is passed to the method as its parameters. Note very Corejava - Java Interview Questions . Tokenize an input string by using both split & StrinTokenizer and store... having only numeric values by using Pattern class. Hi Friend, 4 CoreJava Project CoreJava Project Hi Sir, I need a simple project(using core Java, Swings, JDBC) on core Java... If you have please send to my account Corejava Interview,Corejava questions,Corejava Interview Questions,Corejava programming language consists of one or more abstract methods that must...; Inheritance In java programming language, multiple... to introduce the single inheritance in java programming language Corejava Interview,Corejava questions,Corejava Interview Questions,Corejava of these are part of every object created in java language programming. These methods Help Very Very Urgent - JSP-Servlet Help Very Very Urgent Respected Sir/Madam, I am sorry..Actually... of the ID from Combo box,both Employee ID and Employee Name text box must be filled... requirements.. Please please Its Very very very very very urgent... Thanks Interview Questions corejava how to merge the arrays of sorting i want source code of this one plz--------------------------------------------- Hi Friend, Try the following code: public class MergeSort{ public static void main corejava Java programming tutorial for very beginners Java programming tutorial for very beginners Hi, After completing my 12th Standard in India I would like to learn Java programming language. Is there any Java programming tutorial for very beginners? Thanks Hi Learning the Java Language Learning the Java Language Hi, I am beginner in Java and I want to learn Java very quickly. Tell me which url will help me in Learning the Java Language? Thanks Hi, Please see Java Tutorials section. Thanks displaying both image and records problem in jsp and servlet - JSP-Servlet displaying both image and records problem in jsp and servlet hello... and picutre on the web browser. i will be very happy if i can get the code for this as urgent as possible. Thanks for your cooperation. dipo. Hi How beneficial the Functions of the Management and place. The role of manager or management is very crucial at this point as he hi roseindia - Java Beginners hi roseindia what is java? Java is a platform independent object oriented programming language which ensures portability,security etc..., Threading, collections etc. For Further information, you can go for very good Learning programming language - Java Beginners Learning programming language Hi, I am srikanth i want to learn java programming language without knowing C language.I am very new to programming and i want to learn this language.Can you suggest me to learn the language Programming help Very Urgent - JSP-Servlet Programming help Very Urgent Respected Sir/Madam, Actually my code..... Now what I require is: When I click or select any of the ID from Combo box,both... Please please its very urgent.. Thanks/Regards, R.Ragavendran..   Where to learn java programming language and want to learn Java and become master of the Java programming language? Where to learn java programming language? Thanks Hi, Java is Object.... These tutorials and example will help you in learning Java programming language very About Java Programming Language About Java Programming Language Java is an Object oriented application programming language developed by Sun Microsystems. Java is a very powerful general-purpose programming... with some coding, its better.. PLEASE SEND ME THE CODING ASAP BECAUSE ITS VERY VERY URGENT.. Thanks/Regards, R.Ragavendran... Hi friend, Code multi language multi language Hello friends please help me Hi how can i do a java program using swing that changes the language like malayalam/tamil etc with languages on a drop down menu I am using netbeans IDE hi... - Struts also its very urgent Hi Soniya, I am sending you a link. I hope...hi... Hi Friends, I am installed tomcat5.5 and open the browser and type the command but this is not run please let me - Struts please help me. its very urgent Hi friend, Some points to be remember...Hi Hi Friends, I want to installed tomcat5.0 version please help me i already visit ur site then i can't understood that why i installed all - Java Beginners hi all hi, i need interview questions of the java asap can u please sendme to my mail Hi, Hope you didnt have this eBook. You.../Good_java_j2ee_interview_questions.html?s=1 Regards, Prasanth HI About JSP Expression Language - JSP-Servlet About JSP Expression Language Hi i am new to JSP i am now going...! Nice problem but you do not need to worry as you have made a very small mistake...- - - - - - - - - - - - - - - - - - - - - - -<%@ page language="java" import="java.util.*" Ask Java Questions Online programming language used on the Web for both client and server processing. Unlike C... learners and professionals as Roseindia Technologies, a front running software... is tough but a powerful language used in various software fields including Java as a general purpose language Java as a general purpose language Java is an Object oriented application programming language developed by Sun Microsystems. Java is a very powerful general-purpose Java as a general purpose language Java as a general purpose language Java is an Object oriented application programming language developed by Sun Microsystems. Java is a very powerful general-purpose programming Roseindia JSF Tutorial source code available for the learners at single place. Roseindia JSF Tutorials are aimed to guide the learners with complete coverage of JSF topics required... Tutorials are available for the learners willing to learn Java Server Faces (JSF bi language support - Struts bi language support Hi, Expert how can i use hindi font support in struts application multiple language selection multiple language selection Hi how can i do a java program using swing that changes the language like malayalam/tamil etc with languages on a drop down menu Very Big Problem - Java Beginners Very Big Problem Write a 'for' loop to input the current meter reading and the previous meter reading and calculate the electic bill.... Please give my answer in a for loop only and as soon as you can. Hi Corejava Interview,Corejava questions,Corejava Interview Questions,Corejava Ask C/C++ Questions online language, but both the languages are popular among programmers. C is a general... of both high level language and low level language. It is widely used for creating video gaming and hardware design. Both C and C++ is very popular Hibernate Query Language Hibernate Query Language Explain Hibernate Query Language(HQL) of Hibernate? Hi Samar, Hibernate Query Language is a library for mapping relational database to java classes. It is similar in visual aspect to SQL Java Programming Language Java Programming Language Hi, For beginner which programming concepts is important? Discuss the importance of Java programming language. In the discussion please let's know how to use Java in developing web applications Language Translate Probelm Language Translate Probelm I want to build an application showing... providing language translation. translate api converts - "What is your name.... Hi... - Java Beginners and send me..... its very urgent Hi friend, Plz specify the technology.. go How to Insert image and data both together in database in JSP/Servlet ? How to Insert image and data both together in database in JSP/Servlet ? //form.jsp <%@ page language="java" %> <HTML> <HEAD><TITLE>Display file upload form to the user</TITLE></HEAD> < C Language - Java Beginners answer for the above questions since it is very much needed urgently hi, - Java Beginners hi, what is the need for going to java.how java differ form .net.What is the advantage over .net.Is there any disadvantage in java Hi... where as .Net is not. 3)Java is a language as well as provides run time Hi.... - Java Beginners Hi.... I hv 290 data and very large form..In one form it is not possible to save in one form so i want to break in to part....And i give...; Hi friend, Some points to be member to solve the problem : When Be a Sun Certified Java Programmer will also be quite beneficial for the learners. Our trainers’ tip and tricks... is a hard nut to crack for most of the java learners and only extraordinary...). The pattern of the question is multiple choice and drag & drop in both hi plzz reply hi plzz reply in our program of Java where we r using the concept of abstraction Plz reply i m trying to learn java ... means in language of coding we r not using abstraction this will be used only for making ideas What is Hibernate Query Language (HQL)? What is Hibernate Query Language (HQL)? Hi, What is Hibernate Query Language (HQL)? thanks Ple help me its very urgent Ple help me its very urgent Hi.. I have one string 1)'2,3,4' i want do like this '2','3','4' ple help me very urgent struts internationalization for Korean language struts internationalization for Korean language Hi All, Please suggest me an example where struts is implemented for korean locale using struts internationalization concept. Regards Nagaraju on hibernate query language - Hibernate on hibernate query language Display the contents of 2 fields in a table in a single column using SQL statement.Thanks! Hi friend,read for more information, Hi, Hi, Hi,what is the purpose of hash table Java as an Internet Language Java as an Internet Language Java is an object oriented language and a very simple language... a general purpose language that had many features to support it as the internet hi - JSP-Servlet Form Code in JSP and Servlet Hi, I am looking for a form code in JSP and Servlet. HI,Here is the form code:----<html><title>registration form</title><head><script Is Java a pure object oriented language? Is Java a pure object oriented language? Hi, Is Java a pure object oriented language? thanks Hi No, Java is an object oriented programming language but not purely a object oriented language. In OOPs programming.
http://www.roseindia.net/tutorialhelp/comment/2221
CC-MAIN-2015-06
refinedweb
1,724
55.13
Mongo db with Pycom GPy Hello, I'm trying to access mongo db with my GPy board. I have used PyMongo library before to access mongo db in my python scripts. But for that, I had installed PyMongo using pip install on my system. How can I achieve the same using GPy board? Pointers to any examples of pycom boards accessing dbs would also be helpful. @TravisT @jcaron Thank you guys! That is exactly what we decided to do. Connect to a webservice on the internet with wifi and make that communicate with the database. I would agree with @jcaron. What would be easier is to communicate to some sort of backend, like Flask, that parses your data and stores it. A good example would be using a Flask server with MQTT and Mongo, then you can use MQTT from the Gpy to send data back and forth to the backend. This pulls a lot of the overhead on your resourced constrained Gpy. @sprasad Not sure what your use case is, but in general it would probably be more appropriate for the GPy to call a webservice on a server, and have that server connect to the database, rather than trying to connect directly to the database from the GPy. But of course YMMV. can you run the following and post back the output: import nmongo print(dir(nmongo)) It could be that the library did not upload correctly and hence doesnt work. It might be wirth connecting via FTP and checking the file contents are complete Thanks for the pointer! I uploaded required files onto the board and tried running the example commands from the shell and got this error AttributeError: 'module' object has no attribute 'connect' Tried to search online but seems like not many people have tried this out! Any tried and tested version of the same? A quick google search for "mongodb micropython" brought up this:
https://forum.pycom.io/topic/3039/mongo-db-with-pycom-gpy
CC-MAIN-2020-45
refinedweb
320
71.44
With Python-Embedded XML, or in short PeXml, users can embed Python script in XML. The Python script will be evaluated at run time to generate data values. For example, PeXml can convert the following> into <!-- After Evaluation --> <Data> <StudentID>SID0000023</StudentID> <Class>Tue 2pm</Class> <ExtraCredit>No</ExtraCredit> </Data> where the Python functions are implemented in a user-defined Python module. #dg.py import random index = 0 def round_robin(l): global index index = index + 1 return l[index % len(l)] def extra_credit(probability): if random.random() < probability: return 'Yes' else: return 'No' XML is widely used as input (or output) into web-service or other middle-tier transactions. When testing these transactions, a test engineer needs to pass in different values to validate different business logic. More often than not, the business logic can be highly complicated where random dummy data won't suffice. PeXml is designed to solve this issue by allowing test engineers to Test automation is always high at concept but low at practice. Key challenges are: Complexity: A few lines of source code from a smart developer can implement very complicated business logic that require tens of even hundreds combinations of input parameters to exhaust. Traditionally a tester has to manually enumerate all combinations. It is a straightforward task but it requires far more amount of time than the often tight testing schedule would permit. Test automation introduced another layer of complexity. Suppose we have documented all test cases. Manual execution of the test cases can tolerate defects in the test cases while automated execution cannot. A human tester can detect and fix errors when going through test cases, but a test program will simply crash. Thinking about testing the test program? The time it requires is explosive. Load testing is a special type of automated test. Typically millions or even more transactions were executed during a load test. All of them have to be fully automated and it cannot tolerate any errors. If there is any error, the tester will scratch his head really hard to figure out whether it is an error of the test program, or the system cannot sustain the load. For example, a transaction emitted an error "data not found", a legitimate functional error at first glance. But the root cause could be that under heavy load a data loader failed to upload data into the database. Flexibility: Suppose the tester had suffered endless sleepless nights and finally fixed all bugs in the test program. Usually at this time the testing cycle was closer to its end. He would hope to reuse the test program in next release so all the sleepless nights worth something. Tragedy is that business logic changed in the new release and he has to redo most of the things. Changes of business logic are main drivers for new releases, especially for enterprise customers, who deem low priority for user interface look and feel and high priority for business process. In a fast pacing world where everyone wants to lower costs and improve productivity, tweaks of business process are more than usual. Just name a few examples: A supply chain manager wants to cut a few steps for a new product, a manufacturer wants to add a few tools on the production route, or an online retailer wants to gather new types of data of shoppers. Specific to test automation, flexibility also means the capability to quickly switch between different scenarios. In load testing, normally a customer wants two scenarios: normal vs. stressed. Mix of load is also important. A database administrator may want to understand the system performance when most of transactions are read transactions vs. most are write transactions. Data Dependency: There are two levels of data dependency. One is among parameters within one transaction, which we name Local Dependency. It is a normal practice that a certain combination of two or more data values triggers a particular business process. For example, a process control system may record oven temperatures at the beginning and the end of a baking process, and trigger an alarm if the difference is larger than a threshold. Test program has to have the capability to generate temperatures within the threshold for happy-path test cases and beyond the threshold for unhappy-path test cases. The other is Global Dependency. Complex business processes can be built by gluing up multiple web services or other type of transactions. When validating such a business process, data integrity needs to be preserved among all transactions. For example, an online retailer may invoke multiple transactions for a customer. The customer's ID, a key parameter for all transactions, has to be persistent through all of them. An elegant solution is to separate a piece of test program into two parts: one to model the process and the other to model the data. The benefit is that changes on the process model won't spill over to the data model, and vice versa. Flexibility is achieved by introducing configuration files for both the process model and the data model. A process model is usually no more than a sequence of transactions. With a configuration file, steps can be easily added, removed, or exchanged in a sequence to model changes of the business process or switch between test scenarios. However a configuration file is naturally weak at expressing involved logic, especially when it comes to data dependency. For a data model, normally a configuration file can specify a constant value, a random number, a range of numbers, or a list of strings. Anything more than that require some sort of programming languages. Scripting languages such as Python is a lightweight programming language that requires less programming skills and no compilation into binary code. Embedding scripting texts such as Python scripts into a configuration file will automatically solve the problem. Nowadays XML is the de facto standard for transactions' input and output. Thus we came up with the idea of Python-Embedded XML that can flexibly encode complicated data model and preserves local and global dependency. PeXml comes with two parts: a C++ DLL and a C# DLL. Correspondingly, the attached source code package contains two Visual Studio 2008 projects, a C++ project: PythonInterpreter for the C++ DLL and a C# project: PythonXML for the C# DLL. The C++ DLL uses Boost.Python to invoke Python interpreter and evaluate Python script. The C# DLL uses XML DOM to traverse XML tree and calls the C++ DLL for Python evaluation. We choose this two-tier architecture because Boost.Python "enables seamless interoperability between C++ and the Python programming language"; and our test program is in C# so anyway we need to switch from C++ to C# at some point. In principle, it is not a difficult task to implement everything in C++. It might be more preferable since both Python and Boost.Python are platform-independent. If everything is in C++, PeXml will also be platform-independent. Interested readers can carry it out as an exercise. Because PeXml uses both Python and Boost.Python, readers need to have both installed before using PeXml. For beginners, the best way is to download pre-built Windows installation packages. Multiple packages exist. What we use are ActivePython 2.7.2 and BoostPro 1.47.0. Readers also need to make sure that both the Python DLL and Boost.Python DLLs are in the system path. Otherwise PeXml will complain that DLLs are not found. python27.dll - Usually located at C:\Python27 or C:\Windows\system32 boost_python-vcnn-xx-yy-1_47.dll - Usually located at C:\Program Files\boost\boost_1_47\lib If readers want to compile the source code, in the C++ project: PythonInterpreter they need to set "Additional Include Directories" and "Additional Library Directories" to the right include and lib paths for Python and Boost.Python. Build the PeXml solution will generate two DLLs, both are needed when using PeXml. PythonInterpreter.dll PythonXML.dll To use PeXml, readers create a new C# project with Visual Studio 2008 and add reference to PythonXML.dll. Readers also need to copy both DLLs into the current path, otherwise it will complain that DLLs are not found. We need to add the following namespaces: using System.Xml; using PythonXml; static void Main(string[] args) { Interpreter interp = new Interpreter(); interp.InitPython(@"D:\\Python", "dg"); string>"; XmlNode node = interp.Interp(xml); System.Console.WriteLine(node.OuterXml); } First it initialize a new instance of class Interpreter, then it calls class Interpreter InitPython(string path, string package) to initialize a Python interpreter (or virtual machine) and import the user-defined Python module from path path with name package.py. The user-defined module defines functions that will be embedded in the XML. It can import other Python modules. Global variables can be defined to store values. At run time, different functions can refer to global variables to implement data dependency. path package Then it calls XmlNode Interp(string xml) to evaluate a Python-Embedded XML and return an instance of XmlNode. The purpose to return a node object is that normally there will be some post work needed to perform on the node. Someone may want to check values of a couple of parameters; some may want to manipulate values of others. These type of tasks can be easily performed on a node object. XmlNode PeXml also provides a group of methods to set and get scalar values of global variables defined in the Python module. public void SetString(string key, string value) public void SetInt(string key, int value) public void SetDouble(string key, double value) public string GetString(string key) public int GetInt(string key) public double GetDouble(string key) Using the dg.py at the beginning of this article as an example, the test program can set the value of the global variable index by index interp.SetInt("index", 5) Or it can get the current value of index by int index = interp.GetInt("index") The Python script embedded in the XML has to be an expression that evaluates to a string, or a function that returns a string. This removes the burden that PeXml handles different types of returned values. Since all data values in XML are strings, this restriction is appropriate. For numerical values, Python has a built-in function str() to convert them to string. For example, str() str(5) str(6.0) will convert the integer and float numbers to corresponding strings. If users want to embed constant values into XML, they need to put it in Python string format, which is simply a string quoted by single or double quotation marks, and with special character escaped. For example, 'a Python string' 'C:\\Program Files\\boost\\boost_1_47' # a path where character \ is escaped 'It\'s a Python string' # character ' is escaped Python interpreter will treat them as string expressions and return their corresponding values. Global variables is defined at the top of the user-defined Python module. In a Python function, a global variable has to be indicated by the global statement. Otherwise Python will treat it as a local one. global For example, the following code snippet declares a global variable index, which is referenced in function round_robin(). round_robin() index = 0 def round_robin(l): global index index = index + 1 return l[index % len(l)] Global variables are used to implement local and global data dependency. If round_robin() is called multiple time within a XML, it will return, in order, the values in the list. This can be used to generate mutually exclusive values. For example, depending on the initial value of index, the following XML <Data> <Number>str(dg.round_robin([1, 2, 3, 4])</Number> <Number>str(dg.round_robin([1, 2, 3, 4])</Number> <Number>str(dg.round_robin([1, 2, 3, 4])</Number> <Number>str(dg.round_robin([1, 2, 3, 4])</Number> </Data> will be translated to <Data> <Number>1</Number> <Number>2</Number> <Number>3</Number> <Number>4</Number> </Data> No matter what's the initial value of index, one thing we can guarantee is that the Number parameters in the XML must have distinct values.Boost.Python initialize a singleton virtual machine for a process. Thus Python global variable can also be used to implement global data dependency within a process. For example, suppose we have four transactions, Step1, Step2, Step3, and Step4. Their respective XMLs are Number Step1 Step2 Step3 Step4 <!-- Input XML for Step1 --> <Data> <Number>str(dg.round_robin([1, 2, 3, 4])</Number> </Data> <!-- Input XML for Step2 --> <Data> <Number>str(dg.round_robin([1, 2, 3, 4])</Number> </Data> <!-- Input XML for Step3 --> <Data> <Number>str(dg.round_robin([1, 2, 3, 4])</Number> </Data> <!-- Input XML for Step4 --> <Data> <Number>str(dg.round_robin([1, 2, 3, 4])</Number> </Data> If the test program invokes the four transaction in a sequence, no matter what's the order of the sequence, we can guarantee that each step must have a distinct value for Number. Why Python? We choose Python because of its outstanding interoperability with other programming languages. There is Boost.Python for seamless interoperability with C++ and there is also IronPython for interoperability with C#.Why Boost.Python? For one, we prefer its seamless interoperability. For two, Boost.Python cleverly uses object to maintain reference count, and programmers won't need to worry about memory leak or garbage collection. Why not make path and package name of the user-defined Python package as attributes in the XML Declaration? It is possible to put them as attributes in XML Declaration, such as <?xml version="1.0" encoding="UTF-8" PythonPath="D:\\Python" PythonPackage="dg" ?> But in this way logically the Python package is a property of a XML, conflicting against the concept of using global Python variables for global data dependency among multiple XMLs. PeXml does not handles all Boost.Python exceptions. Unhandled Boost.Python exceptions will terminate the process. This is OK for us as we use PeXml mainly in test programs. The users are expected to have the know-how to deal with those exceptions. If this is intolerable for any users, proper exception handling can be implement following the example of PythonEval() in PythonInterpreter.cpp. PythonEval() Length of string values returned from PythonInterpreter.dll is capped by 1K bytes. This is because we choose to use explicit marshalling between C++ and C# for strings. The C# side will initialize a StringBuilder with 1K bytes and pass it to C++ side to receive the returned string value. The advantage is safety. The disadvantage is flexibility. In our practices we didn't encounter any XML value longer than 1K bytes. Anyway, the limit can be enlarged effortlessly. July 7th, 2012 -.
http://www.codeproject.com/Articles/415789/Python-Embedded-XML-and-Test-Automation
CC-MAIN-2014-52
refinedweb
2,443
56.66
The charAt() method of the String class returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing. The indexOf(int ch, int fromIndex) method of the String class. public class CharAt_IndexOf_Example { public static void main(String args[]){ String str = "This is tutorialspoint"; System.out.println("Index of letter 't' = "+ str.indexOf('t', 14)); System.out.println("Letter at the index 8 is ::"+str.charAt(8)); } } Output Index of letter 't' = 21 Letter at the index 8 is ::t
https://www.tutorialspoint.com/Difference-between-charAt-and-indexOf-in-Java
CC-MAIN-2022-21
refinedweb
107
69.18
You don't have to become expert in XML to use SOAP. For most programmers, SOAP is just a technique for distributed computing. You write a function call on your computer here, and it retrieves a result from a computation there, on a server perhaps half a world away. With well under an hour of installation and practice, you can learn to write distributed Python programs using SOAP to exchange services and results from programs written in almost any language. Compared to other distributed programming tools like DCOM or CORBA (or, more properly, the IIOP which transports CORBA,) SOAP is For example, you might use SOAP and Python to write an application for your handheld computer that retrieves data from a mainframe using Cobol. SOAP translates the details of computing language, hardware, and even human-language encoding. Russian-language words appear in proper Cyrillic, and so on. A growing number of Python programmers are using SOAP. ActiveState Tools Corporation provides product updates using SOAP as a vehicle. Digital Creations Inc.'s Zope is SOAP-enabled. With just a little setup time, you too can experience SOAP's benefits. Programming with SOAP is easy, but first we must assemble the proper pieces to make SOAP work. In principle, you can use Python 2.0 or later. However, PySOAP depends on the xml.parsers.expat module, which is difficult to install correctly. Installing the Windows binary for Python2.1 final is the easiest way to get PySOAP running. If you work from sources, you'll need expat 1.1 or later. Once you are able to import xml.parsers.expat you're ready to download PySOAP from Sourceforge. For this tutorial, I used version 0.9.5. Unpack it into a local directory, and copy the *.py sources into a standard library location as appropriate. On a Unix-like machine, for example, you might cp SOAPpy095/SOAP.py /usr/local/lib/python2.0/SOAP.py This makes SOAP available to all Python2.0 developers on your host. Under Windows you'd want copy SOAPpy095\SOAP.py \python2.1\lib Now you're ready to exercise SOAP. Run import SOAP # XMethods.net provides several interesting SOAP # services. See the references below for details. server = SOAP.SOAPProxy( "", namespace = "urn:xmethods-Temperature") # 47978 is Rensselaer's zip (postal) code. print server.getTemp("47978") This returns the temperature in Fahrenheit degrees of a small town in northwest Indiana, in the US Mid-West. You have just begun your career as a SOAP programmer..
http://www.onlamp.com/lpt/a/python/2001/06/14/pysoap.html
crawl-002
refinedweb
417
61.12
Google Code Jam Qualification Round Africa 2010, Revisited March 26, 2013 We begin with the O(n2) time and O(1) space solution, stated somewhat differently than the previous solution, just for variety. The call-with-current-continuation is the Scheme idiom that permits an early return from a function; the function returns #f if there is no solution: (define (soln1 target vec) (let ((len (vector-length vec))) (call-with-current-continuation (lambda (return) (do ((i 0 (+ i 1))) ((= i len) #f) (do ((j (+ i 1) (+ j 1))) ((= j len)) (when (= target (+ (vector-ref vec i) (vector-ref vec j))) (return (list (+ i 1) (+ j 1)))))))))) Our second solution uses the avl trees from the Standard Prelude. We have to be careful not to take the same item twice if two items have the same value. Note that we add 1 to the position on input instead of output: (define (soln2 target xs) (let ((items (make-dict <))) (do ((i 0 (+ i 1)) (xs xs (cdr xs))) ((null? xs)) (set! items (items 'insert (car xs) (+ i 1)))) (let loop ((xs xs) (i 1)) (cond ((null? xs) #f) ((items 'lookup (- target (car xs))) => (lambda (item) (if (= i (cdr item)) (loop (cdr xs) (+ i 1)) (sort < (list i (cdr item)))))) (else (loop (cdr xs) (+ i 1))))))) The third solution is similar to the second, but uses the hash tables of the Standard Prelude instead of avl trees: (define (soln3 target xs) (let ((items (make-hash identity = #f 97))) (do ((i 0 (+ i 1)) (xs xs (cdr xs))) ((null? xs)) (items 'insert (car xs) (+ i 1))) (let loop ((xs xs) (i 1)) (cond ((null? xs) #f) ((items 'lookup (- target (car xs))) => (lambda (item) (if (= i item) (loop (cdr xs) (+ i 1)) (sort < (list i item))))) (else (loop (cdr xs) (+ i 1))))))) The fourth solution requires a little bit more work. First a vector of value/position pairs is build, then i iterates through the vector, performing a binary search on the portion of the vector from i+1 to the end for a value of the target less the value portion of i. There is no need to check for duplicate positions, because the search vector starts at position i+1; for the same reason, it is necessary to add 2 to i and 1 to the position found in the vector. (define (soln4 target xs) (define (comp a b) (if (< (car a) (car b)) -1 (if (< (car b) (car a)) 1 0))) (define (bsearch target vec lo hi) (if (< hi lo) #f (let ((mid (quotient (+ lo hi) 2))) (cond ((< (car (vector-ref vec mid)) target) (bsearch target vec (+ mid 1) hi)) ((< target (car (vector-ref vec mid))) (bsearch target vec lo (- mid 1))) (else (vector-ref vec mid)))))) (let loop ((xs xs) (i 0) (vs (list))) (if (pair? xs) (loop (cdr xs) (+ i 1) (cons (cons (car xs) i) vs)) (let ((vec (list->vector vs))) (vector-sort! vec comp) (let ((len (vector-length vec))) (let loop ((i 0)) (cond ((= i len) #f) ((bsearch (- target (car (vector-ref vec i))) vec (+ i 1) (- len 1)) => (lambda (item) (sort < (list (+ i 2) (+ (cdr item) 1))))) (else (loop (+ i 1)))))))))) I really like this solution. Though it looks complicated, there is an underlying elegance that I find appealing. And there isn’t much difference between O(n) and O(n log n) unless n gets really large, and the space requirement of the O(n) solution effectively prevents n from getting really large. You can run the program at. I tried solving the problem with a binary search tree and checking for the conjugate. I realized that there is a problem though when there are items of the same price. The key value pair for a tree would be the item price and the item position. If there are two items with the same price then we have duplicate keys! From the provided example we have L={2,1,9,4,4,56,90,3} which would cause a problem when turned into a tree. A solution to this problem could be to have key value pairs of item price and a list of positions. Extra work would be required to keep a complexity of O(nlogn) when building this new tree.
https://programmingpraxis.com/2013/03/26/google-code-jam-qualification-round-africa-2010-revisited/2/
CC-MAIN-2017-47
refinedweb
706
67.32
At the SciPy 2010 conference, a speaker showed several short code samples and asked us what each sample did. The samples were clearly written, but we had no comments to provide context. This was the last sample. def what( x, n ): if n < 0: n = -n x = 1.0 / x z = 1.0 while n > 0: if n % 2 == 1: z *= x x *= x n /= 2 return z The quiz was at the end of the day and I was tired. I couldn’t tell what the code does. Then I found out to my chagrin that the sample above implements an algorithm I know well. I’ve written the same code and I’ve even blogged about here. This exercise changed my opinion of “self-documenting” code. Without some contextual clue, it is hard to understand the purpose of even a small piece of code. Meaningful variable and function names would have helped, but a tiny comment might have helped even more. Not some redundant comment like explaining that the line x = 1.0 / x takes a reciprocal, but a comment explaining the problem the code is trying to solve. For another example, what do you think this code does? uint what() { m_z = 36969 * (m_z & 65535) + (m_z >> 16); m_w = 18000 * (m_w & 65535) + (m_w >> 16); return (m_z << 16) + (m_w & 65535); } It’s clear enough what the code does at a low level — it’s just a few operations — but it’s not at all clear what it’s for. Try to figure out what the code samples do before reading further. But if you give up, the first example is described here and the second example comes from here. In an ordinary face-to-face conversation, more information is conveyed non-verbally than verbally. We may think that our literal words are most important, but so much is conveyed by voice inflection, facial expression, posture, etc. Something similar is going on with source code. When we read a piece of source code, we typically bring a huge amount of implicit knowledge with us. Suppose a coworker Sam asks you to look at his code. The fact that the question came up at work provides a large amount of context; this isn’t just a random code fragment on the web. More specifically, you know what kinds of projects Sam works on. You know why Sam wants you to look at the code. He may be showing you something he’s proud of or he may be asking for help finding a bug. You know a lot about his code before you see it. Now suppose you’re a contractor. Sam was hit by a bus and you’ve been asked to work on his projects until he gets out of the hospital. You may complain to his office mate that Sam’s code is an awful mess, but she can’t understand what you’re talking about. She thinks his code is perfectly clear. Now suppose you’re a contractor on the opposite side of the world from Sam. You have even less context than if you were in his office talking to his office mate. After a great deal of agony, you send your contribution back to Sam’s company. You comment your code beautifully, but Sam’s colleagues complain that your code is poorly written and that you didn’t solve the right problem. Institutional memory is more valuable than source code comments. It costs a great deal to replace a programmer, even one who leaves behind well-commented code. Related posts: Do you really want to be indispensable? Preserving (the memory of) documents The buck stops with the programmer 30 thoughts on “What does this code do?” Rather than a comment, how about giving the function a meaningful name? Mat: I agree that meaningful function names can be very helpful, maybe more helpful than comments. But a project can still be a mystery even if all function names are skillfully chosen. In the first case, a meaningful name would have been perfectly sufficient, but in the second, a brief comment on the method — or just John’s link — would have been welcomed by me. # This is a comment. Every function/class/structure etc should have a short description which explains its goal. When a part of a function is heavily optimised (or just obscured), it should have a comment explaining the desired functionality and what this code snippet does. In other words, I believe that both functions demonstrated here should be commented, but for the first one a short description or the name of the algorithm should be enough. Fast exponentiation is fairly documented. Without tiredness, no comment needed. The biggest gotcha (to me) in the first example is requiring n to be an integer. what( 3, 1.0 )has very different side effects than what( 3, 1 ) Communicating the assumptions a method has is often as important and communicating what the method is for. uint multiply_with_carry_generator() { m_z = 36969 * (m_z & 65535) + (m_z >> 16); m_w = 18000 * (m_w & 65535) + (m_w >> 16); return (m_z << 16) + (m_w & 65535); } Self-documenting code is a fallacy. There are several intrinsic issues with the notion. A symbolic language of operations and instructions can not convey the same level of detail and context as the written word. Alas, neither are satisfactory in their own right. This should be no surprise to anyone, and I believe it’s only been a surprise to those who have decided not to observe the texts from which they gleaned their formal education. Maths are a fantastic analog. A mathematical expression does not stand alone in self-documenting form, despite the level of concision that mathematical notation provides. A chart illustrating statistical findings is without point unless context is provided. A program is little other than collection of instructions, who’s point is often obscured without a description of the function of the program. There is no reason program instructions differ from equations or figures. The figure may say a thousand words, and the same for a program, but it does not stand alone. Beyond the lack of context created by the void of documentation — program instructions often deserve a description of rationale. Irrespective of the constraints of a language or environment, there is always more than one way to solve a problem. Clearly provided rationale benefits future on-lookers and should be considered a necessary element of any algorithm implementation. Dubious and redundant comments are naturally unnecessary — just as a mathematical proof can omit many given postulates. But even a mathematical proof cannot omit written word. I see no reason program instructions would be different, and scoff at the repeated attempts to convince the communities otherwise. Writing legible code is a noble goal, and we should all share this goal and continue to reduce to practice methods for providing logical syntax and grammar which is descriptive as possible. Asserting that intent can be clearly described using descriptive grammar, and that this practice is independently satisfactory for expressing our intent as authors, is ignoring all evidence to the contrary. Ignoring evidence is the antithesis of the scientific method, and a bane to progress. To accept any postulate ignoring evidence is to rely on faith. Faith belongs in religion, not in the discipline of developing software. I’d like to add that meaningful variable names don’t always help. Suppose you’re coding up the quadratic formula. The code would be more readable with variables a, b, and c rather than quadratic_coefficient, linear_coefficient, and constant_term. It would be better to explain the meanings of a, b, and c in a comment than to use long variable names. Long variable names are often very useful, but sometimes there’s a conflict with problem domain conventions, as in the quadratic equation example. Or maybe the length of variables just makes the code too cluttered. I’d err on the side of long names, but you can’t make that a rigid rule. Larry Wall suggested that the length of a variable’s name should be proportional to its scope. I think that’s a sensible rule of thumb. It exponentiate x with n. #!/usr/bin/python def what( x, n ): .... def main(): for x in xrange(-10, 10): for n in xrange(0, 10): print("x=%d, n=%d what=%d" % (x, n,what(x, n))) if __name__ == '__main__': main() John: You imply that there is a difference between being “clearly written” and “understandable.” For example, you describe the snippet as “clearly written” but not easily understood. I’m not quite sure I get the distinction. By analogy, suppose we were talking about regular English writing. How would the following statement make sense? “That sentence is clearly written, but I don’t understand it.” The best I could come up with is “the sentence is legibly presented on the page, and conforms to English grammar, but cannot restate with much degree of confidence what the author intended to convey.” This seems pretty weak, given how people usually use the term “clear” when discussing writing. Does your understanding of “clearly written” code extend beyond layout and being able to compile? If so, how? The first one I figured out pretty quick. The reciprocal and multiplying x repeatedly based on n is a pretty good clue. The second I wasn’t able to figure out. While and65535 and shift16 are used to move upper and lower bits around, the numbers 36969 and 18000 are just magical constants that are meaningless without context. Rename the functions to “exp” and “rng” and I wouldn’t complain, that is all that’s needed to understand the code. What is not said is why these particular versions of algorithms were chosen: Were they more efficient? Better distribution of values? First one found on google? Comments and well structured code are great. Documentation to reinforce those comments are even better. Too few engineers recognize the tangible benefit to well written documentation. Paul: I agree that it’s odd to call something “clear’ that isn’t understandable. The code example is clear at the lowest level of abstraction. It is conventional, not deliberately obfuscated, etc. But the meaning isn’t clear. I normally wouldn’t use “clear” to describe such code. I only meant that it was clear at the most concrete level. nes: The first example is special only because of my experience. I was presented with an algorithm I knew well and I couldn’t recognize it out of context. I’m not claiming that it is an especially tricky algorithm. I probably would have figured out its purpose if I had had more time and patience. But the code was not as easily recognizable as I would have supposed. Perhaps the title of this post is misleading. I didn’t intend this to be a puzzle per se; I wanted to use the examples as an introduction. My point was that we depend on context more than we are aware. In reality, thought, very few commercial code bases are documented at all, and when they are it’s usually useless – my favourite looks something like this: // Add 2 to the result $i += 2; The ability to make sense of other people’s undocumented brainfarts is one of the attributes that distinguishes good and bad programmers. The second function looks like a random number generator to me. I think the rule is quite simple. First, try to attain self-documenting code. This wont cover everything, but I suspect it can cover 80% codebase of every projects. Second, if the self-documenting code are hard/impossible to achieve due to either domain conflicts or gamma ray burst, then have comments to assist the context of the code. Third, sometimes comments cannot convey big enough pictures. In that case, have documents, which might have all those fancy graphs, diagrams and nice formatting. Better yet, put the link or any other way to access the document in the comment. There you have it, simple three rules to follow. Notice that the more you go from rule #1 to rule #2 to rule #3, there are more documentation maintenance that we have to do. Code is easier to update than comment (ie. its hard noticing that you are updating hash from MD5 to SHA-2 without noticing the function name is hashMD5() for example) and comments are easier to update than documents (now which one of the documents that refers to THIS particular line of code that I changed… etc). There is no perfect approach to anything, but at least we can start with the most “right” first and then start breaking the inconvenient rule one by one. Note that for each rule, there will be some cost/consequences down the line. Lastly, note that when choices have to be made, no one can get it right 100% of the time. Accept the fact even the best programmers might make some mistakes. This will some you from some heart attack few months later when you revisit those codes that you are writing today. This is an easy fix… The first one can be re-written like this… def do_fast_exp( x, n ): if n 0: if n % 2 == 1: z *= x x *= x n /= 2 return z The second one can be re-written… uint simple_random_number_generation() { m_z = 36969 * (m_z & 65535) + (m_z >> 16); m_w = 18000 * (m_w & 65535) + (m_w >> 16); return (m_z << 16) + (m_w & 65535); } In any event… self documenting code is useful at the top of the document for me. I have yet to come across a piece of code with instructions which assisted with making it better. I am quite serious when I say the only thing code comments have been good for is figuring out if the person knew what they were doing or if they were chasing imaginary problems. We all do it sometimes… What worries me is non-linear code… or code which is written schizophrenically. Trying to figure out where everything ties in can be impossible. Code is executed linearly… so why not write it like that… jmo… Sorry, but the purpose of the first one should have been pretty obvious to any engineer. This article was an I.Q. test of sorts. I failed. I guess the other lessons that can be learnt is not to analyze code when tired or under time pressure. IMHO, it’s difficult to easily recognize undocumented code when there are no visual landmarks that immediately scream out its purpose. Analyzing code line-by-line until its purpose is absolutely clear takes time. Khairul, that’s exactly the problem — we *have* to analyze code when we’re tired and under pressure. That’s why things like sensible naming, judicious comments, and maybe even external documents are essential. Looking at that second example and with the “simple_random_number_generator” name for it as a hint, I’d still find it woefully under-commented — in fact, I immediately have a further question: Did the author of this code get those numbers from someone who knew what they were doing, or did they just make them up? Is this generator actually any good (and for what values of any good?). If it were my code, and I were commenting it what I consider “right”, I’d add a comment along the lines of “Basic pseudo-random numbers. Constants from $source, periodicity $N.” The heuristic I’ve heard, which certainly applies here, is that comments are to explain why. I prefer the code in your examples to what I usually get handed to straighten out. I usually receive code where the only comments are lines of code that have been commented out. I particularly loathe large blocks of commented out code which contain one or two lines of operational code. #include virtual=”/_includes/main_nav.inc.asp” –> <li 0 Then%> class=”on”><a …
http://www.johndcook.com/blog/2010/07/21/what-does-this-code-do/
CC-MAIN-2014-49
refinedweb
2,642
63.9
User talk:Sikon From Uncyclopedia, the content-free encyclopedia "I think que le monde serait очень сверлильн se la gente usasse soltanto languages that they know." As I'm sure is rather obvious, I got that from a translator (As well as the Italian, which could easily be equally flawed) and intentionally neglected to look it up on my handy Russian dictionary. Boring translated to drilling, I assume. Although I think a little bit of muddled translation seems perfectly at home in the encyclopedia, I am quite interested in the Russian language though, and curious about the difference between your Самбади my Сомбоды. By the way, if that one transliteration bothers you, maybe you should head over to my linguistic and cultural morass of a Gulag article. ADD NEW STUFF TO THE BOTTOM! edit Long article It's been some time since I wrote something more than a screen long. And still the article is not long enough to qualify as its subject - below 200 in Special:Longpages. :( Perhaps I should double it in size. - Guest 13:57, 7 Aug 2005 (UTC) edit ) Guest, I'm sorry to bother you but regarding your recent edit of ), the article is once again a dead end page. Would it be possible to put a related template as a substitute ? Thanks for your time. 64.12.117.8 05:16, 18 Sep 2005 (UTC) - It's no longer a dead-end page, thanks to User:Splaka who made the image link to (. - Guest 05:27, 18 Sep 2005 (UTC) - Thanks for thhe help guys. 64.12.117.8 06:48, 18 Sep 2005 (UTC) edit Unused Image ) text.png has become a homeless ickle puppy and you are its keeper. Do you wish to rehouse the wittle doggy or have it DESTROYED? edit Yoda Maybe we can strike a deal. More or less, I would like to either a) myself write the story of how Yoda trained Jesus and how he was the first Pope. Subsequently, as the first Pope, he fought Roman Emperor Palpatine and lost. Palpatine subsequently became the new Pope (therefore, working in how he looks like Benedict), and Yoda turned invisible or b) Have help working out some kind of story that does include some of those ideas along with others. If we and others can work together on the article, it would be awesome. I hate to change edits other people made (if you need proof, since I did change what was in the Yoda article, you could investigate upon other things I've worked on, but haven't created). Something that gets to me, currently a talking point of mine with the Colonizations, ist that people don't have the 'Yes, and' creative attitude. People will delete what is already there and restart without, for instance, issuing a Rewrite request or talking about it on discussion. ((Cough, power junkies with monopolize a topic, cough)). What is your opinion on things? ~Squire TheDiddler BMF (talk) 21:56, 19 Nov 2005 (UTC) edit Template:NRV When adding NRV to a page, the proper usage is {{NRV|~~~~~}}, that way you don't have to worry about typing the date in correctly, it'll be done for you. --Sir gwax (talk) 19:53, 30 Dec 2005 (UTC) edit Ban Patrol When putting someone on Ban Patrol, it's generally worth checking to see if someone else hasn't already put them there. --Sir gwax (talk) 18:47, 17 Jan 2006 (UTC) Oops, didn't notice. I'll be more careful in the future. - Sir Sikon [formerly known as Guest] 18:58, 17 Jan 2006 (UTC) edit SImplified C Example Even More I took your lead and simplified the C program on Java to: int main() { return puts("Hello, World!\n"); } --Electrostatic 06:07, 19 January 2006 (UTC) edit Test In Progress On VFD you said something about a png file format. Which I've heard of, but I don't know exactly what you want me to do. I'd like to change it though, if you feel that strongly about:27, 19 January 2006 (UTC) edit wiki formatting By watching you edit Sdrawkcab, I noticed you know a lot about advanced formatting of pages. In that same article, if you look closely, there are periods being placed randomly at the end (er, beginning?) of some lines, right in the middle of the sentances, in some cases. Is there a way to turn this off? Keithhackworth MUN 13:12, 23 January 2006 (UTC) edit Thanks! I'm surprised (but very appreciative!) of your nomination of Richard M. Stallman. Really, I have you to thank as the inspiration for starting it. His bio had bothered me for a long time.... And when you tagged the slapped-together-mess of the two existing articles as 'random' I figured, "Yeah, he's right. Busted. :)". Otherwise, I probably would have just walked away from it, rather than trying to work on the half-baked blob idea I had. I'm not sure it's front page-worthy, because I don't know how well known he is among average people, but... who cares? It was a nice pat on the back. :) Thanks again. --T. (talk) 11:30, 25 January 2006 (UTC) edit Psych vs. Unix Guest, I like your Creeping featurism article (I like Next even better!), but even with the Talk:Euroipods section, it seems to be more about Unix than about internet-user psychology. I should be flattered that you'd choose the Unpsychlopedia template, but that one was meant to be somewhat more wiki-specific... Anyway, do you think Creeping featurism might be more at home on the Unix template instead? Mind you, I'm not complaining, and I don't intend to change it myself... it's just a suggestion, so feel free to ignore it! (The Unix template probably gets more traffic too, though... <g>) --Some user 06:15, 26 January 2006 (UTC) edit Thanks Thanks for your nomination of HowTo:Breathe! Teaching people how to breathe makes the world a better place and bring hope to those who suffocate. --Xiao Li 09:54, 3 February 2006 (UTC) edit Kinnnnnnnn-niggit! I am pleased to be the first to offer you congratulations, sir. :) Well done. --T. (talk) 15:14, 4 February 2006 (UTC) - Heh. I'm not sure if receiving a FIYC automatically makes me a knight (and I think it was a minor issue not worthy of such a great award), but the consensus on IRC seems to be that it does. - Sir Sikon [formerly known as Guest] 15:24, 4 February 2006 (UTC) edit Spasiva --Rataube 13:27, 6 February 2006 (UTC) edit Thanks for the nom I just realized I hadn't thanked you yet for the nom. I honestly don't know what you were thinking, I mean that article was actually delted once by Keitei, but it isn't actually going as bad as I thought it would. So yeah,, 12 February 2006 (UTC) I as well thank you for the VFH nomination. Everyone who voted against so far is probably a communist.--Skunkbucket 20:02, 16 February 2006 (UTC) edit Babel:1337/1337 Please review your edit of this article on 2 February 2006. Your edit arbitrarily cut off (in mid-sentence) a large swath of material after Line 74, which also included the quasi-feature tag and categories. Was this massive trimming deliberate?, or did you intend to simply revert the previous edit on Line 29 only? --DW III 16:32, 18 February 2006 (UTC) - Well, I was reverting the "j00/j00r" edit, if I screwed something up, I did it unintentionally. Sorry. - Sir Sikon [formerly known as Guest] 03:15, 20 February 2006 (UTC) - No prob then; I'll patch it up. --DW III 03:27, 20 February 2006 (UTC) edit Wheres my dog Wheres my dog? edit WotM Thanks (again!) for the support, and for your humourous/ironic correction to the XHTMLnazi award. ;-) ~ T. (talk) 14:17, 28 February 2006 (UTC) edit Practical Joke Hi! I'm not complaining or anything about the tag you put on the article I made. I made it because I have a thing on my user page that says: You have new messages. (diff). It links to that page. Do you have any suggestions of ways I can make the article better so it doesn't get deleted? Thanks! -) 23:49, 2 March 2006 (UTC) - Thanks for removing the tag! I plan on improving the article furthur, and also thanks for doing some editing on it! I appreciate it. -) 13:32, 3 March 2006 (UTC) edit Cthulhu Since we were able to trace the excellent question back to you, Cthluhu has asked that you be given this as a token of his gratitude. He also wished that I tell you you've made an excellent minion--<< >> 23:44, 3 March 2006 (UTC) edit iArticles:00, 4 March 2006 (UTC) edit Thanks for the vote Even if it was an auto-for, it's really appreciated, Sikon. I'm still getting established as a writer almost half a year after getting here, and getting a major contributor's thumbs-up makes me smile. :)--<< >> 19:31, 5 March 2006 (UTC) edit Template:Redlink The template looks better if the words are centered. If they're aligned to the right, it just becomes ugly. Please specify why you want the template to be ugly. --Boy Toy bitch at me 16:15, 12 March 2006 (UTC) - The words were aligned to the left, regardless of whether the center tag or the margin parameter was used. Centered it. - Sir Sikon [formerly known as Guest] 18:14, 12 March 2006 (UTC) - Not on IE, actually. But I don't have any other browser, so there's my problem. Thank you for cenetering it. --Boy Toy bitch at me 20:06, 12 March 2006 (UTC) edit A common Spaghetti-eater Don't worry, "se la gente usasse" is not flawed. Yep, nice work to SW: NWN! I added Tommy Tallarico and something else. 82.52.23.188 12:30, 14 March 2006 (UTC) edit sux - grrr! I do say that this color scheme sucks! It's in an effort to match the land masses on the UnNews potato globe. If you can match better, please do. ~ T. (talk) 12:15, 18 March 2006 (UTC) - Make them black text and brown links, or white text and gray links, whatever, but please not black text and white links. It hurts my eyes. - Sir Sikon [formerly known as Guest] 12:16, 18 March 2006 (UTC) edit Thanks for the edit. You fixed the pic I put in 127.0.0.1, so, thank you. - 04:12, 19 March 2006 (UTC) edit You have mail - Attack you? Lir "attacked" Imrealized, not you, and if by "attacking" you mean praising him for copying your style (I think you should be proud to have a style), then yes, I guess it's a personal attack, and everyone's talk page is full of personal attacks... I don't understand who you think is trying to get you, if it's me, it's untrue, and I'm 90% sure nobody haolds any malice against you. Maybe if you say who this is, we could try and get this problem solved? (P.S. Strange, you recognize my Russian origin but apply American categories to me, as if I'm familiar with U.S. political life...) - Sir Sikon [formerly known as Guest] 07:23, 19 March 2006 (UTC) PP and I were indirectly attacked too. User:Someone's_User is most likely an attack...unfortunately I think I was an afterthought rather than a target. – Mahroww a.k.a. Horatio Meyer Stein 07:46, 19 March 2006 (UTC) - Hello...I can't seem to find this "Lir" character- crazy I know since he/she/it sent me a pleasant note and I wanted to thank this person. The funny thing is, if I just got on this site about a week ago and am already able to "copy" someone else's style in that manner, especially someone who writes as well as Some User, then "Lir" (sounds Russian, don't it?) must think I'm one of the best writers on this site, which I don't need to tell you is a really great thing for he/she/ idiotit to say, especially with so many good writers who on here, don't ya think? --Imrealized 08:35, 19 March 2006 (UTC) - Perhaps - judging by Assholes, I also think you're a decent writer. "Lir" doesn't sound Russian, though. At any rate, he's not my sockpuppet, I don't know whose he is. - Sir Sikon [formerly known as Guest] 08:43, 19 March 2006 (UTC) - Lir is someone who obviously likes Runescape and neck ties – Mahroww a.k.a. Horatio Meyer Stein 08:55, 19 March 2006 (UTC) - Indeed, would:58, 19 March 2006 (UTC) edit My apologies I see that you think leaving that content ("excuse me, why do you delete content from someone else's talk page? he can figure what to do without you, thanks") on SU's page is worth something... I viewed it as antagonizing content so I moved it. But, as you well know, I am just joining in the fun. WHEEEEEEEE! – Mahroww a.k.a. Horatio Meyer Stein 08:38, 19 March 2006 (UTC) edit Another Question Now another question I have is why is a paragraph that I wrote on my user page written on Someone's User's (is that right?) page...I know that everything is open for ganking on here, but isn't that going a bit to far? Do you know who Someone's User is, and why they are that uncreative that they have to steal other people's ideas? Just wondering..--Imrealized 09:16, 19 March 2006 (UTC) - No, I don't know who it is. These sockpuppets (Someone's User, Lir, and whoever else) belong to at least two different IRCers, that's all I know. - Sir Sikon [formerly known as Guest] 09:47, 19 March 2006 (UTC) edit hocok template I just realised you used my sock template (or at least my proposal for one). Did you happen to catch the "hidden" message? – Mahroww a.k.a. Horatio Meyer Stein 10:03, 19 March 2006 (UTC) - What hidden message? What "your" sock template? I used the one on UnMeta, posted by Todd Lyons. - Sir Sikon [formerly known as Guest] 10:16, 19 March 2006 (UTC) - Don't be so naive. I had Todd take a look at it. Somehow I doubt you were unaware of it's origin. Anyway, there's a "hidden" message. – Mahroww a.k.a. Horatio Meyer Stein 19:19, 21 March 2006 (UTC) edit Lir, Not Lir Man, I don't think you're Lir. I don't know who you are. What I do know is that I came to this site to write some funny shit, not to take a wonderful trip back to effin' Romper Room and have little popularity contests and "Do, do, do...I think I'll effe with the n00b because I am a talentless hack and I'm 15 and I've got no life of my own." I'm all for fun...this is witless, sophmoric shite. So you're not Lir, that's great. Perhaps you can go ask "the cabal" just who the effe you really are. --Imrealized 00:06, 20 March 2006 (UTC) edit Babel Atheism I remember you asking on IRC, so I decided to have a look. It turns out that there isn't an official one yet. But some guy did make a draft, which is located here. It's not extremely funny, but you could always make one:51, 20 March 2006 (UTC) edit Jumped the Gun Hey man, I just wanted to apologize to you... In all my n00bish glory I really jumped to conclusions, perhaps being bothered at being called a "sockpuppet" (and even more frustratingly, having no idea what the hell that meant until I looked it up and having no idea who it was that left that template). Anyway, I've no excuse really but I wanted to apologize for being an ass. You seem like a good guy and that was rotten of me. Hope there's no hard feelings. --Imrealized 13:22, 20 March 2006 (UTC) edit Sockpuppet The cabal has analyzed your codes and can definitely conclude that you are a sockpuppet of Lir. In the name of peace and justice, you will be banninated. - Fx 13:18, 22 March 2006 (UTC) edit Well Done Redirecting Blank Article to Nihilism... Very clever. :) edit sdrawkcaB what does the [[ru:Абырвалг]] do on sdrawkcaB? --Keithhackworth MUN 12:59, 29 March 2006 (UTC) - It's a multilingual link that appears in the left menu. By the way, it isn't necessary to use piped links for sdrawkcaB. - Sir Sikon [formerly known as Guest] 13:45, 29 March 2006 (UTC) Thank you for voting for me for WOTM, though RCMurphy xxx'ed your name out, I'm still counting it!--Sir Slackerboya CUN VFH (talk) 06:20, 31 March 2006 (UTC) - I didn't vote for you, an anon did. - Sir Sikon [formerly known as Guest] 09:06, 31 March 2006 (UTC) edit Excellent reading I enjoyed your Microsoft patant reading muchly. Thank you for blessing the internet with its existence.--<< >> 01:00, 1 April 2006 (UTC) edit Template:QVFD So I see you recreated Template:QVFD. I trust from the fact that it is different from before that you understand why we don't tag things for QVFD with a template. But on the issue of user notification, I don't think it is a good idea. Either things are insta-huff worthy and any admin will huff the page, probably before they ever see it on QVFD or it isn't huff-worthy and the page's author need never know that some other user wrongly) 23:21, 3 April 2006 (UTC) - You admins can't seem to make up your mind. Splarka said the template could only be kept if changed into a user notification. Delete it mercilessly, then. - Sir Sikon [formerly known as Guest] 00:17, 4 April 2006 (UTC) - I'll talk to Splarka. Thanks. ---Rev. Isra (talk) 00:51, 4 April 2006 (UTC) edit Is Crap/Cock Sucking funny? I'm very much inclined to revert the edit that replaced "Crispie DreadinK Elves" with "Krap DesKtop Environment/KocK-suKKinK DesKtop Environment, but first I'd like to ask you, is it just me not getting the joke? I see that you let it go. Logixoul 07:55, 5 April 2006 (UTC) - I don't care, both variants are acceptable for me. - Sir Sikon [formerly known as Guest] 09:24, 5 April 2006 (UTC) edit Insert funny title here I protected the featured article to prevent arseholes from spoiling a great gag. If you need to make any amendments, let, so I know I said I'd be cool with it if people didn't like my changes to Insert title here (I'm writing this after Sbluen lifted the ban) and yeah, I'm still cool with it, but might I ask why, in fact, you (that is, Guest) reverted it? (Was it too hard to understand the new way or what? 'Cuz that's a legitimate reason.) Whatev. --Lenoxus 01:28, 19 May 2006 (UTC) edit International Phonetic Alphabet Hi there, I was taking a look at the phonetic stuff you added to International Phonetic Alphabet, and I was wondering where you learned English, as you seem to have a non-rhotic accent (i.e. for words that have an "er" in them, you transcribe a schwa). Now, there's anything wrong with that in the least, but as I was changing them, I realized it's rather futile unless I can get a semi-consensus on what the proper pronounciation of English words is! I have a Western Canadian accent, so a lot of your transcriptions sounded a little funny to me. But maybe I'm overthinking this (and maybe you transcribed the words with a program or something). I ask you since you had the rather brilliant idea of transcrribing the article into IPA. Cheers! -- Major4 10:23, 19 May 2006 (UTC) - This doesn't reflect how I actually pronounce words, I've seen so many diferent transcriptions that I'm hopelessly confused about these accents. I'm a Russian and, for an example of my pronunciation, turn to Media:Unnaws2.ogg. :) - Sir Sikon [formerly known as Guest] 15:20, 19 May 2006 (UTC) edit Reuploading "Africa sad" Do you want me to do it in PNG to make it clearer? Or for some other reason? If it's for clarity, then I'll need to redraw it. --Jordanus 05:01, 21 May 2006 (UTC) edit Hi, Sikon! Heya! Remember me? I just was knocking about and found your userpage.. so, what's your favourite cartoon? See ya! edit Remember THIS from Wookieepedia? You range-block my entire university for two months just for changing a single letter in the template? My, my. That's pretty cruel. As cruel as how a Sith, Dark Jedi, or anyone affiliated with the Galactic Empire would punish anyone. --The Batheticator 19:07, 22 May 2006 (UTC) - After doing a bit of research on the matter, Mr. Batheticator, you vandalized that template multiple times. Reverting vandalism gets annoying, especially when it's reverting a pretty lousy pun in the first place. Furthermore, here at Uncyc, we make the Empire look like a bunch of rookies. You've been warned. —Hinoa KUN (talk) 19:43, 22 May 2006 (UTC) - Hinoa, a "Kuralyov" permabanned one of the computers from my university for the first offense of changing a single letter. I didn't feel too good about that rather harsh punishment for something comparatively small so I kept doing it out of revenge, until Sikon made the range-ban. - As you can see here, Kuralyov decided to give that computer a punishment several orders of magnitude harsher than Imperialles did 21 minutes earlier, for the first-ever vandalism on Wookieepedia from anywhere in my university. I changed a letter on one or two templates to give myself a big laugh and this is the punishment I get? What would you have done if this had happened to you? --The Batheticator 23:49, 22 May 2006 (UTC) - This wouldn't have happened to me because I wouldn't have engaged in vandalism in the first place. No, I'm not going to life the block. If you hadn't want to get banned, you shouldn't have vandalized. Besides, I don't lift blocks given by other admins. - Sir Sikon [formerly known as Guest] 00:18, 23 May 2006 (UTC) - As the other wookieepedia admins have decided to shorten IP bans, we'll probably be removing that one. And by "we'll be removing", I mean "I'll be removing." And by "I'll be removing", I mean "That's funny, it no longer appears, but I didn't do anything." So you can come back, but we will ban you for further vandalism, obviously. (Silly Dan, from Wookieepedia) And another thing: this User:Dan MacQueen guy is not me. Though this User:Silly Dan guy is. Does it count as impersonation if he used my real name before I registered my usual pseudonym? Do I have to register two usernames on every wiki in existence now? Bah. —Silly Dan (talk) 02:25, 7 August 2006 (UTC) edit ED Reskin. Remember that chat oli you and I had on IRC? Many pints later, you mentioned the concept of an ED reskin. Having perfected the idea, we now have two distinct problems: - RC doesn't want a domain war, - Chron doesn't want ED having any attention from us. Check the idea out at here. There are plenty of variations around in there some where. If you have any ideas then please tell me ASAP. The reskin needs. 12:05, 7 June 2006 (UTC) edit Ancient Grecian Flamewar Sikon... thanks for the nom and vote on Euripides. I figured the least I could do in return is try to fulfill your request for a parody of Talk:Euroipods. I think it's underway at Talk:Euripides — hope it's what you had in mind.-- Imrealized 05:35, 23 June 2006 (UTC) edit Practice what you preach... You advertise UnMeta on your userpage and aske people to contribute, but you don't! So... can you contribute to the UnMetan pages? Or if you're too lazy, at least delete some of the QVFD'd articles. ~ 16:36, 23 June 2006 (UTC) There's more now... lots more... ~ 15:27, 11 July 2006 (UTC) edit There you go, all done with audio for... UnNews:Microsoft unveils Internet Genuine Advantage I hope I didn't dissappoint. Thanks for the great, 13 July 2006 (UTC) edit Goatse Vandalism at UnMeta I think it's over now, but I can't block the user, nor do I have a rollback button. ~ 11:26, 1 August 2006 (UTC) edit Thanks for the support<center> Thanks very much for supporting my potential adminship. I'm still in shock, what with all of these celebrities supporting me. You rock,:11, 27 August 2006 (UTC) edit VFP - Against. I don't get it, either. - Sir Sikon [formerly known as Guest] 18:40, 19 September 2006 (UTC) Red & Blue = Red states & Blue states, left/right, dem/repub, etc. You know, the partisan foolishness that's been tearing the US asunder since 2000 or so? That's why I put the US civil war era flags where the Axis&Allies flags would go on what was the Axis&Allies box. I thought everyone knew about the red/blue thingy...it would appear that I was wrong.--Sir Modusoperandi Boinc! 18:51, 19 September 2006 (UTC) - All Americans may know about it, but not people outside the US. - Sir Sikon [formerly known as Guest] 04:37, 20 September 2006 (UTC) - Sorry, whatever country it is that I am from gets a lot of US and US centric news...You're lucky to miss out on it (see Red/Blue States, if you care). Well, now you know, it's some spooky shit; but you have to know about it to get the satire.--Sir Modusoperandi Boinc! 05:10, 20 September 2006 (UTC) edit bribe on VFP Durka Durka!!! change your vote to support on my Osama Image and I'll give ya a piece of cake Durka Durka!! SOADLuver 19:24, 1 October 2006 (UTC) edit Isn't it time for a software update? Hi, do you know which admins here are the developers? I think that the site could use a few updates such as: - Allowing pages to be semi-protected like on Wikipedia. This would mean that only IPs and newly registered users would be prevented from editing the pages, while established users could. This would be more useful on pages that are getting vandalized a lot than fully protecting the page and preventing everyone from editing. - Some new buttons at the top of the window when editing pages (e.g. a button to automatically place the code for a redirect). - I've also been thinking that it might be good to stop letting IPs create pages. I think this would seriously cut down on the number of trash pages that are created.--Mister Nosey 14:44, 14 October 2006 (UTC) - 1. Wake up, it's already implemented and the Wikia version is synchronized with Wikipedia regularly. 2. Make this suggestion to Angela on IRC, she runs Wikia. 3. No. - Sir Sikon [formerly known as Guest] 14:57, 14 October 2006 (UTC) edit Ganges/hymns to ganga please do not delete the page as it is used in article Ganges as a template. thanks. -- mowgli 16:56, 20 October 2006 (UTC) edit Chris Benoit Facts The Chris Benoit Facts page has been getting deleted. This is completely legit. If this site can have Chuck Norris Facts, why can't Chris Benoit have his own facts, when he has actually done something? - The Chuck Norris facts were spared by a community vote, many were against it, and, frankly, the only reason it survived was because Chuck Norris is a running gag here on Uncyclopedia. Chris Benoit... not quite. In general, our standards are higher than random lists of inane factoids. - Sir Sikon [formerly known as Guest] 18:07, 22 October 2006 (UTC) edit UAOIAOIAOIAOI Sikon, I don't mean to seem needlessly critical, but I feel compelled to ask that you reconsider the huffing of Uncyclopedia's Article on Its Article on Its Article on it's Article on Itself. I'm not saying the joke should be extended any further than that, but I personally thought that was the punchline of the whole gag, or at least it was the one bit of it that made me laugh the most. I know it was just a silly little stub, but... please? With cherries on top? c • > • cunwapquc? 03:01, 9 November 2006 (UTC) edit:03, 10 November 2006 (UTC) edit Air Drum Hello how are you? About the article, I just created it 10 minutes ago, and I think it is pretty similar to Air Guitar and Handgun. In case of that, is it really up to deletion? Cheers -- It's gneomI 13:40, 11 November 2006 (UTC) - Expand it, and it will survive. NRV means just that. - Sir Sikon [formerly known as Guest] 13:41, 11 November 2006 (UTC) edit why hello, why did you huff philology, there was no reason to? -- VFP Eincyc (talk) 08:21, 16 November 2006 (UTC) - Um... --Sir Modusoperandi Boinc! 08:25, 16 November 2006 (UTC) edit Deadwood article deleted There was no good reason for swiftly deleting the article based on the HBO series "Deadwood" I started. There wasn't even a vote for deletion. I demand to have it restored immediately. - Diceman 11:51, 17 November 2006 (UTC) edit Thanks :) ...for the Burninator. I'm hoping to be able to get further through Category:Stub before the week is out to clean out the old garbage, but I've got a couple of papers due soon. Wish me luck. :) ~ T. (talk) 02:06, 19 November 2006 (UTC) edit Linux Pride I've de-peed it. Still VFH-able? I welcome a nomination because I'm such a camwhore - David Gerard 22:53, 19 November 2006 (UTC) edit Thanx I will reward your kind words with candy kisses. -:42, 25 November 2006 (UTC) edit NRV on Mark Kermode Come on dude dont you reckon that that NRV tag was a bit quick on the Mark Kermode page. I will concede that it isnt finished (or close) yet, but come on i had spent like 10 mins, you cant expect a page written in 30 mins, i will improve and cleanup etc. but its not a bad article. Ne wayz, ta ra --TheReal 19:17, 1 December 2006 (UTC) - If you're still working on the article, put {{construction}} on it, or prepare it in your userspace. - Sir Sikon [formerly known as Guest] 19:20, 1 December 2006 (UTC) edit You are Great Fun I bet you have LOTS of friends! The thing I like the most about you is the way that you communicate so well. Keep it up. You have a genuine fan here. I love the work you do. SilkTork 19:25, 1 December 2006 (UTC) edit iJesus and iJesus 2.0 Two articles that you deleted during FFW that I personally thought were really good. Can I get the code? Crazyswordsman...With SAVINGS!!!! (T/C) 02:32, 4 December 2006 (UTC) - User:Crazyswordsman/IJesus User:Crazyswordsman/IJesus 2.0 - Sir Sikon [formerly known as Guest] 03:19, 4 December 2006 (UTC) edit Please Sir, y did u delete my TWATTY article? -Timmy McGee - Because it sucked, and please use proper English and sign your posts on talk pages properly. - Sir Sikon [formerly known as Guest] 06:24, 9 December 2006 (UTC) edit Haha Thanks. I try, heh. Crazyswordsman...With SAVINGS!!!! (T/C) 18:43, 9 December 2006 (UTC) edit n00b hello Sikon, i'm a newb, clearly, and am looking for some guidance, i read a lot of the "informational" posts, and tons of random articles, posted a bunch of NVR's for crap that made me so angry, "I want to bite someone in the face!!!" - Giraffe in quicksand and tried my hand at an article, tornadocane and posted in pee review to no avail. sorry if i wasted my time, beat me senseless when you get a chance, {{Chazz 11:04, 13 December 2006 (UTC)}} edit vanity Hey, why was my recent article deleted because of vanity? It's a band we just made up... --Dasistgutja 20:21, 13 December 2006 (UTC) - Refer back to my talk page for answers. 20:24, 13 December 2006 (UTC) edit Reverting images Why's that? --AAA! (AAAA) 11:15, 15 December 2006 (UTC) edit NEW!!! Have a look at this Are your edits being edited? Delete this when done :) kjhf 16:25, 17 December 2006 (UTC) edit XMas May you focus on your successes and forget your failures here at the end of the year. Never forget how we all improve one another's lives. Season's Greetings.--<< >> 17:35, 17 December 2006 (UTC) Merry Christmas my Merry Russian.:29, 18 December 2006 (UTC) edit From me :25, 19 December 2006 (UTC) edit Merry Christmas Codespammer alert! I mean, erm, Merry Commercial Conformity Period (commonly known as Christmas). -- Hindleyite Converse 21:07, 19 December 2006 (UTC) edit Stuff deleting articles A short article should not tbe deleted for no real reason. I mean, isn't the reason for allowing ANYONE to edit articles to encourage them to contribute? When you keep deleting articles you give the articles absolutely no chance to grow. Every time it has a beginning it gets snuffed out...I mean "huffed", by users who think there is something inherently wrong with a short article. edit A crazy idea Instead of cloning and manipulating child nodes with 7,000 lines of error-checking just to avoid messing up the votebox, wouldn't it be easier to just float:left the votebox after the <h1 class="firstHeading"></h1> and change the title with something like this? function titleOverride() { newTitle = document.getElementById("titleOverride").innerHTML; if (newTitle) getElementsByClassName("firstHeading")[0].innerHTML = newTitle; } - Nonymous 15:09, 23 December 2006 (UTC) - I don't control whether the votebox is a child node of firstHeading, Wikia does. Dynamically moving it out and checking that nothing is screwed in the process would require JavaScript code at least as complex as what's already there. Also, innerHTML is more bug-prone compared to DOM manipulation, especially in IE. - Sir Sikon [formerly known as Guest] 15:20, 23 December 2006 (UTC) edit Merry Christmas If you are another child that thinks they need a present, leave a message here (Santa never forgets, but he is getting on a bit.) Ho Ho Ho from Santa Claus 15:46, 23 December 2006 (UTC) - That sounds very... unusual and unlike you, Grandfather Frost. - Sir Sikon [formerly known as Guest] 15:49, 23 December 2006 (UTC) edit CVP Redirect I was debating doing that myself, but wondered if it worked better as a honey-pot, or a flame for the moths. Of course, I only debated, and didn't do anything because I was feeling lazy. Just wondered if you had thought of that aspect, and if you feel it's better this way, no complaints on my part. Sir Famine, Gun ♣ Petition » 12/23 16:24 - And that was exactly what I was afraid of: more drama. - Sir Sikon [formerly known as Guest] 16:57, 23 December 2006 (UTC) edit Your block on Benson. edit {{title}} Hey, I was wondering why you restricted the new title changing javascript to only main, UnNews: and Game: namespaces? There was no problem being able to change any page's title with the old version, so I don't get why it's restricted in the javascript version. I just thought I'd ask you if there was a specific reason for it rather than just enabling it. I think it'd be better to have it enabled in all namespaces so there's no need for the old version anywhere. • Spang • ☃ • talk • 01:53, 27 Dec 2006 - Because Splarka told me to do so. - Sir Sikon [formerly known as Guest] 05:06, 27 December 2006 (UTC) edit You huffed my good cop article what's up with that? —The preceding unsigned comment was added by 86.137.171.167 (talk • contribs) 10:02, 30 December - This pun is like shooting fish in a barrel...with a cannon...point-blank... Sir Famine, Gun ♣ Petition » 12/30 15:37 edit You huffed Candlejack. Several times. You're not cool by doing so. Just leave it. Beelzebud 21:10, 30 December 2006 (UTC) edit A gift For Linux tech support in the IRC (since I have nothing else to give, I give my gratitude).--<< >> 21:19, 30 December 2006 (UTC) edit Limitations of Superpowers as Applies to God I added something to Limitations of Superpowers as Applies to God having noticed it on VFH. I hope that you find it amusing. Dame GUN PotY WotM 2xPotM 17xVFH VFP Poo PMS •YAP• 17:09, 4 January 2007 (UTC) edit Hugs edit Huffed article complaint Perhaps you recall an article by the name of Demetri Martin you have recently huffed. The explanation you gave was "No content. Only images." Since when has this been reason alone to delete an article? In most cases, it would fair to do so, but in this case, the images are relevant to the article's subject (I suggest if you don't "get it", you watch one of Demetri Martin's performances, then you'll get teh pictures); I already went over this with another admin, Hinoa, who also wanted to NRV the article before, and he agreed it was suitable. Please reconsider putting the article back, if there is any way to do that, or if not, allowing me to re-make it, providing none of the images have been huffed. -:09, 17 January 2007 (UTC) edit Username change Hi, the admin formerly known as Guest. Don't laugh, but I want to change my user name as well. I was just wondering... I used this nick for Kazaa, Napster and SoulSeek, but I guess it's too much goofy for appearing in discussion lists over here. Noblesse Obligé, I am a sir now and sir NeedABrain, you know... :p How do I do it? Is it acommplished just by moving my user page? -- herr doktor needsAbolt [scream!] 18:48, 19 January 2007 (UTC) - No, you'll need Wikia staff for that. Try asking Sannse. - Sir Sikon [formerly known as Guest] 20:54, 19 January 2007 (UTC) - Thank you. He told me it's a complex operation, so I think I'll leave the things as they are for a while. Or almost. -- herr doktor needsAbolt [scream!] 15:41, 20 January 2007 (UTC) - Sannse is a she, actually. - Sir Sikon [formerly known as Guest] 15:55, 20 January 2007 (UTC) - Oooops! I'll remember, 20 January 2007 (UTC) edit Aaacid transpAAAAAAAAArency PNG I've uploaded Image:Aaacid.png per Talk:AAAAAAAAA#AAAAAAAAcid (I suppose). Have aaaaaaaat it. --Closeapple 07:59, 21 January 2007 (UTC) edit I thank you... ...for seeing Sissy in its context ;-), Hugs, Dame GUN PotY WotM 2xPotM 17xVFH VFP Poo PMS •YAP• 23:43, 31 January 2007 (UTC) Why did you edit my text? I thought it was ok. :S edit My Blocking Hey Sikon. It's me Kip the Dip, but you might know me by my IP address: 207.69.137.0/24. I'm here to request that you lift my block. You stated that I was a vandal. I promise you that I hate vandalism, whether on Wikipedia or Uncyclopedia. I never intentionally vandalized Uncyclopedia, and I did read the beginner's guide and the rest of the ignorable policies. If this is about that Fergie article, I wasn't trying to be stupid and not funny. If anything, I improved the article. (Which totally sucked, just check the history and see what the original creator had to say.) I know it wasn't hilarious, but I acknowledged in the Talk page that it needed work. Anyway, I'm asking you if you could lift my ban. Pretty please? : ) -User:Kip the Dip - How did you post this if your IP is blocked? - Sir Sikon [formerly known as Guest] 18:05, 23 February 2007 (UTC) edit Thanks! Thanks so much for unblocking me! After I had to jump through so many hoops, it just shows what loyal nerds editors you people have! And don't worry, I'm going to read your ignorable policies several more times! (Kip the Dip) edit I wonder If i'm not mistaken you the ond did that article about firefox . Im wondering if you are going to do an article on thunderbird herself or not . I defiantly like that article on firefox . Richardson j 12:04, 11 March 2007 (UTC) ps I'm only able to use opera on my wii game console . - You own a game console? Then you don't deserve having your request fulfilled. - Sir Sikon [formerly known as Guest] 04:48, 12 March 2007 (UTC) - What do you have angenst me having a game console in fact i have 6 game consoles . Richardson j 08:48, 12 March 2007 (UTC) - Then the Emperor has already won. - Sir Sikon [formerly known as Guest] 11:29, 12 March 2007 (UTC) - well i allready made a report to one of the administrators about whether you class as a cyberbully or not by Richardson j 22:12, 12 March 2007 (UTC) edit Love the Rose Tyler Article Having been following the recent huffing battle (yeah I know, what a sad life I lead...) - particularly as it linked through to Schrödinger's cat on the very day that I gave the page a much needed, erm, twist. Haven't got the hang of all these back slapping templates yet, but feel free to pat yourself on your back (or find an adult who can do it for you) --Asahatter (annoy) 19:06, 6 May 2007 (UTC) edit !!!!!!!!!!1 y biio QQQ edit Contents edit Contents edit Contents edit Restore the article, RIGHT NOW!!! Can you please restore the article May (Pokemon) then move to my user page for the article construction. Thanks. Pika8888 13:55, 1 October 2007 (UTC) - Done. I noticed you already created User:Pika8888/May (Pokemon), so I restored it to User:Pika8888/May (Pokemon):23, 1 October 2007 (UTC) - Actually, I just noticed that User:Pika8888/May (Pokemon) (which MadMax restored) is the same as the deleted version. You can work on it:26, 1 October Windows Vista This article is made stupid not funny a lot. One editor (NXWave) even seems to revert every reversion I make. It's one of Uncyclopedia's best articles and it'd be a shame for it to be ruined like the other Vista article, so could you keep an eye on it with me? SteveSims 08:05, 20 December 2007 (UTC) edit Need your help Please for create template:C @Tolololpedia thx 125.160.123.69 08:55, 24 February 2008 (UTC) (Borogx not login) edit Aaaadition? What do you think? Talk:AAAAAAAAA!#Aaaaaa.3F Bassgoonist 20:05, 5 March 2008 (UTC) edit 'Lo Sikon Good to see you're still alive. Is this your triumphant return, or are you just popping in to feed the cat? :-) RabbiTechno 15:44, 9 December 2008 (UTC) - See userpage. I just noticed traffic to my blog from my Uncyclopedia userpage and decided to reduce it to a bare minimum. - Sir Sikon [formerly known as Guest] 17:07, 9 December 2008 (UTC) edit Award from UN:REQ MadMax 20:14, 30 July 2009 (UTC) edit Oh hello. Hello. :29, May 2, 2012 (UTC) - Sik Nelson Mandela Ok, so now that I have a firm grasp of the obvious (that being that you don't think much of my Nelson Mandela page), could you maybe offer some advice? —The preceding unsigned comment was added by 41.150.32.198 (talk • contribs) 01:39, September 26, 2012
http://uncyclopedia.wikia.com/wiki/User_talk:Sikon?oldid=5584305
CC-MAIN-2015-18
refinedweb
7,464
71.95
Is there any way that we can get the quotient and remainder for a modulus operation in perl ? For example : I have a variable $var = 4999. I perform a modulo operation on it (%100) and get values of 49(quotient) and 99 (remainder) and assign it to two different variables. Is there any module or way to do this in perl ? I'm not aware of any module that does this but it's easy enough to roll your own: $ perl -Mstrict -Mwarnings -E ' my ($var, $mod) = (4999, 100); my ($quot, $rem) = (int $var / $mod, $var % $mod); say $quot; say $rem; ' 49 99 [download] -- Ken As pointed out, it's not difficult to do it with just a few lines of code. If you wanted to, you could also just create a subroutine like the untested code below: use strict; use warnings; sub modulo { my $number = shift; my $divisor = shift; my $remainder = $number % $divisor; my $quotient = ($number - $remainder) / $divisor; return ($remainder, $quotient); } [download] The module you seek is actually just a pragma: integer. sub quotient_remainder { use integer; my( $dividend, $divisor ) = @_; my $quotient = $dividend / $divisor; my $remainder = $dividend % $divisor; return ( $quotient, $remainder ); } say quotient_remainder( 3, 2 ); [download] The integer pragma is lexically scoped, and can be a way of reducing your need to pepper your calculations with int. Dave Please refrain from misguided (premature) optimizations. This isn't 1986 any more. While. A foolish day Just another day Internet cleaning day The real first day of Spring The real first day of Autumn Wait a second, ... is this poll a joke? Results (417 votes), past polls
http://www.perlmonks.org/?node_id=981240
CC-MAIN-2014-15
refinedweb
266
57.81
16 November 2011 16:41 [Source: ICIS news] HOUSTON (ICIS)--Praxair plans to build a plant in ?xml:namespace> Praxair said it expects to start up the plant with a capacity of 126 tonnes/day in early 2013. Praxair will supply the pulp mill under a 15-year deal, it added. The pulp mill, which is currently under construction at Punta Pereira, is expected to produce 1.3m tonnes/year cellulose pulp, beginning in early 2013. The mill, a joint venture between forestry companies Arauco of Chile and StoraEnso of Finland, is the largest-ever privately executed investment in ($1 = €0.74) For more on Prax
http://www.icis.com/Articles/2011/11/16/9509023/us-praxair-to-supply-uruguay-pulp-mill-with-industrial.html
CC-MAIN-2015-11
refinedweb
106
65.83
The Internet of Things. For far too long humans having been hogging all the internet to themselves. It is time to change that. Now that the future is here we can start connecting everything we own, allowing the world of buggy software to permeate deeper into our lives. circuit diagram symbol for transistors is shown below:. You can see this ground connection in the finished photo below. Now all we have to do is connect a GPIO pin from the Pi to the base of each transistor. Here I am using GPIO pins 18 and 23. You can see a photo of this whole setup below. Software The next step is to use Flask to expose our new circuit to the internet. I will be using my hardware control library RobotBrain to simplify the code. Here I'll show the code in its entirety and then point out the important bits. There are only two files. lamp_control.py and templates/main.html (note that main.html needs to be in a directory called templates) If you'd rather git pull than copy/paste you can find all the code on github. lamp_control.py import time from itertools import cycle from flask import Flask, render_template from robot_brain.gpio_pin import GPIOPin app = Flask(__name__) on_pin = GPIOPin(18) off_pin = GPIOPin(23) state_cycle = cycle(['on', 'off']) @app.route("/") @app.route("/<state>") def update_lamp(state=None): if state == 'on': on_pin.set(1) time.sleep(.2) on_pin.set(0) if state == 'off': off_pin.set(1) time.sleep(.2) off_pin.set(0) if state == 'toggle': state = next(state_cycle) update_lamp(state) template_data = { 'title' : state, } return render_template('main.html', **template_data) if __name__ == "__main__": app.run(host='0.0.0.0', port=80) Here we are using Flask to respond to HTTP requests. Whenever the root URL or an immediate subdirectory of root is requested, the update_lamp() function is called. If any subdirectory is requested, the name of that subdirectory is fed as an argument to the function. For example, if <my-ip>/foo is requested, Flask will call update_lamp('foo') and respond with whatever the function returns. The update_lamp() function checks for one of three states ( on, off, or toggle) and performs the desired behavior. templates/main.html <!DOCTYPE html> <head> <title>{{ title }}</title> <style type="text/css"> body { padding: 0; margin: 0; } .large_button { position: absolute; width: 100%; height: 50%; text-align: center; text-decoration: none; font-size: 1000%; } #on { background-color: #fbf09a; color: rgb(223, 204, 103); text-shadow: 1px 1px 10px #5C4E17; } #off { background-color: #1e170b; top: 50%; color: rgb(83, 71, 48); text-shadow: 1px 1px 10px #000000; } </style> </head> <body> <h1> <a href="/on" id="on" class="large_button">ON</a> </h1> <h1> <a href="/off" id="off" class="large_button">OFF</a> </h1> </body> </html> This is the template that is rendered by the above Flask function. When rendered it looks like this: To start the server simply run the script with root privileges (GPIO access needs root): sudo python lamp_control.py Now just navigate to your Pi's IP address and you should be able to control the lamp! NOTE: I am not a Flask or web design expert, so I might not be doing things the correct way. But it wouldn't be hacking if we knew what we was doing all the time, would it? Conclusion I usually run the script with screen so I can reconnect later. I've also added an Android homescreen shortcut that links to the toggle URL so I can easily control the light from my homescreen. In the end I was pretty happy with how simple this turned out to be. If you follow these instructions and connect one of your devices to the internet, I'd love to hear about it! You can reach me on twitter @jackminardi.
http://jack.minardi.org/raspberry_pi/make-an-internet-controlled-lamp-with-a-raspberry-pi-and-flask/
CC-MAIN-2016-22
refinedweb
632
65.01
tag:blogger.com,1999:blog-46380092765830253522017-07-29T10:34:30.908+02:00Wouter Devinck - BlogWouter Data Binding to physical objects (updated)<p>I had some spare time tonight, so I thought I'd have a go at controlling a small servo I had lying around using an <a href="">Arduino Uno</a>. That was pretty easy (it is explained on the Arduino website over <a href="">here</a>), so I decided to take it a step further. What about writing a .NET application that can control the servo? Right, Windows Forms? Nah... boring... WPF! And to make the code nice and shiny, let's use data binding.</p>Here is a picture: <p><a href="" imageanchor="1" style="margin-bottom: 1em; margin-right: 1em;"><img border="0" src="" /></a></p>And a video! <p><iframe width="420" height="315" src="" frameborder="0" allowfullscreen></iframe></p><p>What does this take?</p><ul><li><p>A little bit of code on the Arduino that listens for commands to change the servo position on the serial interface.</p></li><li><p>A .NET class that represents the physical servo, which has a "Position" property (to which we can data bind) and which sends out a command on the serial port when the position changes.</p></li></ul>The Arduino sketch: <script src=""></script>The servo class in C#: <script src=""></script><p>Let's now use this class to data bind the position of a slider control to the position of the physical servo:</p>The XAML: <script src=""></script><p><em>Side note: for some reason my little servo does not like to go below 30 degrees, that is why the minimum of my slider is 30, you might want to set that to 0.</em></p>The C# code: <script src=""></script><p>Of course there are a million other ways to do this and there is a lot of room for improvement, but I find it quite remarkable that it can be done in such an elegant way and with so little code.</p><hr /><p><em>Update 14/06: </em> After posting this yesterday, fellow MSP <a href="">François Remy</a>.</p>Here is a video: <p><iframe width="420" height="315" src="" frameborder="0" allowfullscreen></iframe></p>The code for the Arduino: <script src=""></script>And the C# Servo class: <script src=""></script><p>As you can see, I have implemented <em>INotifyPropertyChanged</em> (refer to <a href="">this</a>) and used async/await instead of having to deal with threads (refer to <a href="">this</a>). Although this adds some complexity, the Servo class is still fairly straightforward.</p><p><em <a href="">this forum thread</a>.</em></p><img src="" height="1" width="1" alt=""/>Wouter: "An introduction to Windows Azure"<p><em <!--series of--> blog post<!--s-->. It has been a while, I have been quite busy (exams, thesis, work...), so sorry for the delay in posting this.</em></p> <!--<p><em>This is part one: a web role, a worker role, a queue, some blob storage a a lot of fun.</em></p>--> <p style="margin-top:20px;margin-bottom:20px;"><a href="" target="_blank"><img style="border:0;" src="" /></a></p> <p>The Azure poster displayed above is a nice overview of what Azure has to offer (you can find a full size version <a href="" target="_blank">over here</a>).! </p> <p. </p> <p style="margin-top:20px;margin-bottom:20px;"><a href="" target="_blank"><img style="border:0;" src="" /></a></p> <p>Azure Cloud Services are pretty open: you can use the technology of your choice to write applications. On the <a href="" target="_blank">Azure website</a> (pictured above) you can find pretty good documentation for .net, node.js, java, php and python. All APIs are <a href="" target="_blank">RESTful</a>, so using another language or technology should not be a problem either. In this post I will only discuss .net technologies. Of course, the integration of Azure with .net and Visual Studio is pretty good. </p> <img border="0" height="240" width="300" src="" style="float:left;margin-right:30px;margin-top:20px;margin-bottom:20px;" /> <p style="margin-top:30px;margin-bottom:20px;">Okay, so let's build a fun application. In this example we will build a web app that generates images like this one. A picture is shown on a black background in white frame with two sentences underneath it (let us call them "title" and "description" for clarity).</p><p>Let's call our application "Memeify". </p><br style="clear:both;" /> <img border="0" height="338" width="300" src="" style="float:left;margin-right:30px;margin-top:20px;" /> <p style="margin-top:30px;". </p> <p. </p> <p>Azure offers two queuing mechanisms: Storage Queues and Service Bus Queues. For a comprehensive comparison between the two I refer to <a href="" target="_blank">this msdn page</a>. Besides the technical comparison it is also a good idea to take a look at the pricing differences between the two systems, depending on the intended/predicted load (use the <a href="" target="_blank">online pricing calculator</a>). </p> <p>We will use Service Bus Queues, but it would be trivial to do the same with Storage Queues. </p> <p>Let's get started! We will use Visual Studio 2012, with all the right tools installed. I would advise you to use the <a href="">Web Platform Installer</a> to find and install the latest Azure tools and SDKs. We will also be using ASP.NET MVC 4 to build the website, you will find that in WPI as well. </p> <p>I always like to start with a Blank solution and then add projects to that empty solution. (File » New » Project...) </p> <p style="margin-top:20px;margin-bottom:20px;"><img border="0" src="" /></p> <p>The first project we add to this solution is a an MVC web application. (Right click on solution name in the Solution Explorer » Add » New Project...). We could call this project "Memeify.Web". </p> <p style="margin-top:20px;margin-bottom:20px;"><img border="0" src="" /></p> <p>As this is about Azure, I won't go into to much details about ASP.NET MVC 4 (watch <a href="">this</a> or start <a href="">here</a>). I'll start with a basic ASP.NET MVC 4 project and will not bother with unit tests (but you should!). I will use <a href="">the Razor view engine</a>, because it is awesome. </p> <p style="margin-top:20px;margin-bottom:20px;"><img border="0" src="" /></p> <p>At this point we can add an Azure project to the solution. This is nothing more than some configuration files that define a cloud service. We could call this project "Memeify.Azure".</p> <p style="margin-top:20px;margin-bottom:20px;"><img border="0" src="" /></p> <p>We then add the existing web project as a web role to the cloud service.</p> <p style="margin-top:20px;margin-bottom:20px;"><img border="0" src="" /></p> <p style="margin-top:20px;margin-bottom:20px;"><img border="0" src="" /></p> <p>By right clicking the role we can get to its settings. These settings are stored in XML files (with a .cscfg extension) in the project which, alternatively, we can edit manually as well.</p> <p style="margin-top:20px;margin-bottom:20px;"><img border="0" src="" /></p> <p><em>Pro tip</em>: while experimenting and testing or even deploying to a limited number of users, set the VM size to "Extra small". Extra small instances are charged at 1/6th of the rate of a small instance. See <a href="">this page</a> for more information.</p> <p style="margin-top:20px;margin-bottom:20px;"><img border="0" src="" /></p> <p>Let's now do some work on the website.</p> <p>We will need a model to represent a meme. <em>Models/MemeModel.cs</em> Let's keep it simple: a <a href="">POCO</a> that has properties for the image, the title and the description. The image is a file and title and description are strings. </p> <p style="margin-top:20px;margin-bottom:20px;"><script src=""></script></p> <p>We also create a view. <em>Views/Home/Index.cshtml</em>.</p> <p style="margin-top:20px;margin-bottom:20px;"><script src=""></script></p> <p>Next, we will need a controller. <em>Controllers/HomeController.cs</em> On a GET, we simply want to show the form, so we return the view. When the form is POSTed, we need to create the image and somehow return it to the user.<p> <p style="margin-top:20px;margin-bottom:20px;"><script src=""></script></p> <p>At this point we could just write some code to create the image right in this action of the controller (the line in the above marked with a <em style="color: gray;">TODO</em>).</p> <p>The Azure documentation provides very clear step-by-step instructions on how to use all these services. <a href="">Here is the how-to on using blob storage in .net</a>. Because this documentation is very good, I will skip ahead to the code here. In summary, what you have to do is create a blob storage account using <a href="">the online portal</a> and add the "connection string" to the settings of the role.</p> <p style="margin-top:20px;margin-bottom:20px;"><img border="0" src="" /></p> <p: <a href="">this is a good read</a>.</p> <p <em>"Images"</em>.</p> <p style="margin-top:20px;margin-bottom:20px;"><script src=""></script></p> <p>We can create this container first using <a href="">the online portal</a> or using a third party tool (e.g. <a href="">CloudXplorer</a>).</p> <p style="margin-top:20px;margin-bottom:20px;"><script src=""></script></p> <p <a href="">Steve Marx has written a nice extension method</a>.</p> <p style="margin-top:20px;margin-bottom:20px;"><script src=""></script></p> <p>And then we can upload the blob.</p> <p style="margin-top:20px;margin-bottom:20px;"><script src=""></script></p> <p>Once the image is in blob storage, the only thing that is left to do in the web role is to add the task to a queue. Queues work in a very similar way: we first create a storage account (<a href="">storage queues</a>) or a namespace (<a href="">service bus queues</a>) in the online portal, we then add the connection string to the settings of the role and use the .net implementation of the REST API to access the queue. In the following we will use service bus queues.</p> <p style="margin-top:20px;margin-bottom:20px;"><script src=""></script></p> <p>On to the worker role! Let's add the project and call it "Memeify.ImageServer".</p> <p style="margin-top:20px;margin-bottom:20px;"><img border="0" src="" /></p> <p style="margin-top:20px;margin-bottom:20px;"><img border="0" src="" /></p> <p>This project contains a template called "WorkerRole.cs", this file has a method "OnStart", this is were we will put our code.</p> <p!</p> <p style="margin-top:20px;margin-bottom:20px;"><script src=""></script></p> <p>The CreateMeme method pulls the image from blob storage, adds the background, frame and text using GDI and saves the result back to blob storage. The bulk of it has little to do with Azure, so here is the code without further ado.</p> <p style="margin-top:20px;margin-bottom:20px;"><script src=""></script></p> <p>One thing that I am not addressing here is how to get the result back to the user after the worker role is done with it. We could for example use websockets or a library like <a href="">SignalR</a> (<em>http://{storageaccountname}.blob.core.windows.net/{containername}/{result-blobname}</em>) and tell them to wait a bit and refresh the page. Not very nice, but good enough for now. One can easily see that designing a good, loosely coupled, cloud architecture requires some thought.</p> <p><em>I am making the source available on <a href="">GitHub</a>,!</em></p> <p style="margin-top:20px;margin-bottom:20px;"><a href="" imageanchor="1" style=""><img border="0" height="70" width="158" src="" /></a></p><img src="" height="1" width="1" alt=""/>Wouter Bundle Transform for ASP.NETLast week, Microsoft announced TypeScript, a superset of Javascript that adds strong typing, interfaces, classes, modules and lambda expressions. If you have not heard of it, <a href="">their website</a> has a tutorial and playground. If you have some more time, there is a very good video overview by Anders Hejlsberg on <a href="">Channel 9</a> (embedded below).<br /><br /><iframe style="height:288px;width:512px" src="" frameBorder="0" scrolling="no" ></iframe><br /><br />The response to this new language seems to be mixed. I largely agree with the opinions expressed in this article: <a href="">Thoughts on typescript</a>.<br /><br />An interested fact about the <a href="">open source</a> TypeScript compiler is that it is written in TypeScript. This compiler translates TypeScript to plain Javascript.<br /><br />When I first read about TypeScript (yesterday), I immediately started looking for an <a href="">IBundleTransform</a> implementation that runs the TypeScript compiler. I did not find any implementations, so I decided to write one myself and put it on <a href="">GitHub</a> and <a href="">NuGet</a>.<br /><br /.<br /><br />Enjoy!<img src="" height="1" width="1" alt=""/>Wouter place at AppsForFlanders hackathon<a href="" imageanchor="1"><img border="0" height="428" src="" width="640" /></a><br /><br />Last week, I went to the AppForFlanders hackathon with some friends. At this event, students were invited to build apps with government data.<br /><br />More info about the event: <br /><ul><li><a href="">The event website</a></li><li><a href="">The IBBT blog</a> - and a little nod to the author for providing me with the pictures in this post</li></ul>Alexander, Tom, Nicolas and I have build a little online game (or rather quiz) about biodiversity. We called it "berenleren!", which is Dutch and could be translated as "bear teaching". I take no responsibility for this name whatsoever (<a href="">Miet</a> takes the blame).<br /><br />Berenleren combines biodiversity data with images and descriptions from Wikipedia and book titles from boek.be.<br /><br />The application, built in a couple of hours, is buggy at best (and ugly at worst), but available at <a href=""></a> (it is written fully in HTML/JS/CSS, so feel free to grab the source).<br /><br />And oh, forgot to mention: it got us a third place (500 euros and a ticket for <a href="">iMinds</a>), which is nice.<br /><br />Some more pictures:<br /><br /><a href="" imageanchor="1"><img border="0" height="268" src="" width="400" /></a><br />Brainstorming<br /><br /><a href="" imageanchor="1"><img border="0" height="268" src="" width="400" /></a><br />Designing<br /><br /><a href="" imageanchor="1"><img border="0" height="268" src="" width="400" /></a><br />Coding<br /><br /><a href="" imageanchor="1"><img border="0" height="268" src="" width="400" /></a><br />The jury<br /><br /><a href="" imageanchor="1"><img border="0" height="268" src="" width="400" /></a> <br />The presentation<br /><br /><i>No animals were harmed in the making of this software.</i><img src="" height="1" width="1" alt=""/>Wouter week of student entrepreneurship events in Ghent<i>I am a bit late to blog about this, sorry for that!</i><br /><br />Last week I was invited to two events for student entrepreneurs. Not that I would call myself an entrepreneur, but apparently I match some people's definition of the phrase.<br /><br / <a href="">vikingapps.be< <em>real</em> companies led by students that are doing really well, alright? I ended up leaving the event a bit disgusted by all the (false?) hyper-optimism of all those students who think they are going to change the world.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1"><img border="0" height="640" src="" width="446" /></a></div><br />More info: <a href=""></a><br /><br / <a href="">yelper</a> in an online newspaper and part of <a href="">my resume</a>..<br /><br /><div style="width:510px" id="__ss_12595152"><iframe src="" width="510" height="426" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe></div><br />More info: <a href=""></a><br />Pictures: <a href=""></a><img src="" height="1" width="1" alt=""/>Wouter at Students to Business Day 2012My presentation at the Students to Business day 2012 in Braine-l'Alleud, Belgium.<br /><br />Keywords: RIA development, client, HTML5, Javascript, CSS, jQuery, jQuery UI, jQuery mobile, Twitter Bootstrap, KnockoutJS, SignalR.<br /> <ul><li><a href="">jquery.com</a></li><li><a href="">jqueryui.com</a></li><li><a href="">jquerymobile.com</a></li><li><a href="">twitter.github.com/bootstrap</a></li><li><a href="">knockoutjs.com</a></li><li><a href="">signalr.net</a></li></ul> <object id="__sse11640235" width="550" height="355"><param name="movie" value="" /><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><param name="wmode" value="transparent"/><embed name="__sse11640235" src="" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" wmode="transparent" width="550" height="355"></embed></object><img src="" height="1" width="1" alt=""/>Wouter review of the Nokia Lumia 800Click <a href="" target="_blank">here</a> to get a PDF version of this review.<br /><br /><i>A couple of weeks ago, Nokia has given me a Lumia 800 device to try. The only condition was that I had to share some feedback. So here it goes…</i><br /><br /><a href="" target="_blank"><img src="" style="float: left; margin-right: 10px;" /></a>The Lumia 800 is Nokia’s new flagship smartphone running Windows Phone 7 Mango. It has been almost a year since Microsoft and Nokia announced their <a href="" target="_blank">partnership</a>. Nokia still is the largest manufacturer of mobile phones, but their smartphone department was not doing well. The Lumia 800 has been available for a couple of months in <a href="" target="_blank">several countries</a> and seems to be doing quite good so far. In Belgium it is available since February 1st for 499 euro.<br /><br />Reviewing this device was not an easy task. I have done my very best to do it as good and as complete as possible. Should you buy it? Is Windows Phone mature enough? Does it work properly? Read on to find out what my opinion is.<br /><br /><i><b>Disclaimer</b>: I am writing this as an independent consumer, gadget-enthusiast and app developer, not a Microsoft or Nokia poster boy. Some of my thoughts about this device might surprise you.</i><br /><br /><br /><h1 style="font-weight: normal; color: #4A6C97">Hardware</h1>The <i>curved</i> <a href="" target="_blank">Gorilla glass</a> with a capacitive touchscreen and three buttons: back, home and search (as required by Microsoft).<br /><br />The body is crafted out of a single piece of <a href="" target="_blank">polycarbonate<.<br /><h3 style="font-weight: normal; color: #4A6C97">Screen and buttons</h3>The 3,7 inch AMOLED screen has Nokia’s ClearBlack technology, which is big plus, it makes the dark colors really dark <a href="" target="_blank">by being less reflective</a>..<br /><br />The three buttons under the screen are capacitive and while that is <i>really</i>.<br /><br /><a href="" target="_blank"><img src="" style="float: right; margin-left: 20px; margin-top: 10px;" /></a>On the right, it has some buttons: a volume rocker, a power/sleep button and a dedicated camera button. Sadly, there are a few problems with these buttons. The power button is placed terribly, right under the volume rocker. I often lock the device when trying to lower the volume, very annoying. The camera button on my device sits a bit loose, when shaking the device you hear the button make a ticking sound. I have read reports of other people having this issue with the power button. Also, the camera button doesn’t feel as good as it should. You can press it half way down to focus, but that stop half-way down is a bit too soft and easy to miss.<br /><h3 style="font-weight: normal; color: #4A6C97">Audio</h3><div style="float: right; margin-left: 20px; margin-top: 10px;"><a href="" target="_blank"><img src="" style="margin-bottom: 10px;" /></a><br /><a href="" target="_blank"><img src="" style="margin-bottom: 10px;" /></a><br /><a href="" target="_blank"><img src="" /></a></div>On the top you’ll find a standard 3,5 mm audio jack, a USB port (under a stupid hatch) and a Micro-SIM slot. That is right, the Lumia 800 is one of only three devices that uses Micro-SIM. The iPhone 4 and the Nokia N9 are the other two. It shouldn’t be too hard or expensive to get a Micro-SIM card (the Belgian provider Mobile Vikings charged me 5 euros), but this may cause some inconvenience. The holder for the SIM card is made of aluminum and should be solid enough. The hatch is a bit wiggly, but should be fairly strong as well.<br /><br /><i>Edited 9 feb 2012: A reader pointed out that the Nokia Lumia 710 uses Micro-SIM as well. I stand corrected.</i><br /><br /.<br /><h3 style="font-weight: normal; color: #4A6C97">Camera</h3><a href="" target="_blank"><img src="" style="float: right; margin-left: 20px; margin-top: 10px;" /></a>On the back: an 8 megapixels camera with a wide-angle Carl Zeiss lens that can do 720p video and dual LED flash, which is very, very bright. A front facing camera would have been nice, especially with Skype coming soon to Windows Phone, but I don’t consider the lack of it that much of an issue. Video calls on a mobile phone still are not very commonplace anyway. The quality of the rear camera is alright: the colors are good, the flash is bright but it adjusts well to the lighting of the scene and the autofocus is speedy (considering it is a phone and not a DSLR, of course). I have made some test shots (most are taken inside, sorry for that):<br /><br /><a href="" target="_blank"><img src="" style="margin-right: 8px;" /></a><a href="" target="_blank"><img src="" style="margin-right: 8px;" /></a><a href="" target="_blank"><img src="" style="margin-right: 8px;" /></a><a href="" target="_blank"><img src="" style="margin-right: 8px;" /></a><a href="" target="_blank"><img src=""/></a><br /><br /><div style="float: left; margin-right: 20px;"><a href="" target="_blank"><img src="" style="margin-right: 10px;" /></a><a href="" target="_blank"><img src="" /></a></div>A problem I have with the camera is a reddish mist in the middle of pictures. It really shows when taking a picture of a white sheet of paper. I don’t know if this problem is isolated to my device and whether it is a hardware or software issue, but it is unfortunate. <br /><br /><i>And yes, I already had this issue before putting the device on a red background for the photos.</i><br /><br /.<br /><h3 style="font-weight: normal; color: #4A6C97">Inside</h3>Inside, <strike>a gyroscope</strike>, a GPS (which is pretty good, but more about that later), a compass, proximity sensor, light sensor and an FM radio. The expected 3G, WiFi and Bluetooth are available as well. Also locked inside is the battery, which is not user replaceable, sadly. There has been some buzz about the battery running out to fast and Nokia has pushed out some updates to address this issue. I had no problems though, the battery drains just as fast as on any other smartphone I have: very fast. My golden rule of thumb is that it has to make the end of a long busy day and the Lumia does that.<br /><h3 style="font-weight: normal; color: #4A6C97">Durability</h3>The.<br /><h3 style="font-weight: normal; color: #4A6C97">Accessories</h3><a href="" target="_blank"><img src="" style="float: right; margin-left: 20px; margin-top: -50px;" /></a>In the box you will also find a very cute USB charger, a USB cable, headphones (which, frankly, I haven’t even tested) and a silicone cover, matching the color of your phone. Whether you like silicone covers or not, it is nice to have one included that perfectly fits your phone.<br /><blockquote style="color: #4A6C97; font-style: italic; font-size: x-large;">In general, the hardware is pretty standard these days, but the design is simply stunning and the build quality is excellent.</blockquote> <h1 style="font-weight: normal; color: #4A6C97">Software</h1><h3 style="font-weight: normal; color: #4A6C97">Windows Phone 7</h3>Windows.<br /><br /><a href="" target="_blank"><img src="" style="margin-right: 5px;" /></a><a href="" target="_blank"><img src="" style="margin-right: 5px;" /></a><a href="" target="_blank"><img src="" style="margin-right: 5px;" /></a><a href="" target="_blank"><img src="" /></a><br /><br /.<br /><br / <a href="" target="_blank">Mobile Vikings app</a> showing my account balance and Niels’ <a href="" target="_blank">UGent Resto app</a>, showing todays menu in the university restaurants.<br /><br />Swiping to the right brings you to the full list of installed apps, where you can also pin them by pressing and holding for a couple of seconds (this is the equivalent of a right click on Windows).<br /><br /><a href="" target="_blank"><img src="" style="margin-right: 5px;" /></a><a href="" target="_blank"><img src="" style="margin-right: 5px;" /></a><a href="" target="_blank"><img src="" style="margin-right: 5px;" /></a><a href="" target="_blank"><img src="" /></a><br /><br />The build-in messages app is very interesting. It combines text messages with Facebook chat and Live Messenger. You can, for example, start a conversation on Facebook and continue via text messages. There is a button at the bottom of each conversation that allows you to switch.<br /><br /><a href="" target="_blank"><img src="" style="margin-right: 5px;" /></a><a href="" target="_blank"><img src="" style="margin-right: 5px;" /></a><a href="" target="_blank"><img src="" style="margin-right: 5px;" /></a><a href="" target="_blank"><img src="" /></a><br /><br /.<br /><br /><a href="" target="_blank"><img src="" style="margin-right: 5px;" /></a><a href="" target="_blank"><img src="" style="margin-right: 5px;" /></a><a href="" target="_blank"><img src="" style="margin-right: 5px;" /></a><a href="" target="_blank"><img src="" /></a><br /><br /!<br /><br /><a href="" target="_blank"><img src="" style="margin-right: 5px;" /></a><a href="" target="_blank"><img src="" style="margin-right: 5px;" /></a><a href="" target="_blank"><img src="" style="margin-right: 5px;" /></a><a href="" target="_blank"><img src="" /></a><br /><br /).<br /><br /> This is all I wanted to share about the Windows Phone 7.5 (a.k.a. Mango) operating system, but of course there is a lot more to tell about it. <i><a href="" target="_blank">The Verge</a></i> has a well-balanced and more elaborate review of Mango.<br /><h3 style="font-weight: normal; color: #4A6C97">Nokia apps</h3>Nokia has made some little tweaks to the OS, they have added some ringtones and the Nokia blue color, nothing very shocking. Let’s hope that because of the partnership between both companies, someday, some of the user interface of the N9 makes into Windows Phone.<br /><br /><a href="" target="_blank"><img src="" style="margin-right: 5px;" /></a><a href="" target="_blank"><img src="" style="margin-right: 5px;" /></a><a href="" target="_blank"><img src="" style="margin-right: 5px;" /></a><a href="" target="_blank"><img src="" /></a><br /><br />They have added some extremely nice apps though. Bluetooth contacts transfer allows you to transfer contact from your previous phone over Bluetooth. Handy! Nokia Music sells music.<br /><br /.<br /> <h3 style="font-weight: normal; color: #4A6C97">About third party apps, adoption and maturity</h3><div style="float: left; margin-top: 6px; margin-right: 20px;"><a href="" target="_blank"><img src="" style="margin-right: 5px;" /></a><a href="" target="_blank"><img src="" style="margin-right: 5px;" /></a><a href="" target="_blank"><img src="" /></a></div>Just like the other two big mobile platforms, Windows Phone 7 has an application store, which they call Market-place.<br /><br /.<br /><br />Of course, this is easy to explain: Windows Phone has virtually no market share. According to <a href="" target="_blank">Gartner</a>, Windows Phone has 1,5% market share (based on sales third quarter 2011). Compared to Android (52,5%) and iOS (15%) that is a bit low. So the platform is not very attractive for app developers (or at least their companies) and few apps are built.<br /><br /.<br /><br /.<br /> <h1 style="font-weight: normal; color: #4A6C97">Conclusion</h1>The.<br /><br /><i>Does it work properly?</i><br />Yes, both the software and hardware work well, only the audio quality is disappointing.<br /><br /><i>Is Windows Phone mature enough?</i><br />The operating system feels a lot more “finished” than the first version of Windows Phone 7. Having said that, the Marketplace still is a bit disappointing compared to the competition.<br /><br /><i>Should I buy it?</i><br />If you want to buy a Windows Phone, buy this one. It is the best one I have seen. If you want to buy a smartphone, well…, you might like Windows Phone, it is something different, but there are some downsides.<br /><blockquote style="color: #4A6C97; font-style: italic; font-size: x-large;">The Lumia hardware may even be so good that it makes you forget some of the problems with Windows Phone and ultimately allows the platform to grow and prosper.</blockquote><h1 style="font-weight: normal; color: #4A6C97">Acknowledgements</h1>I would like to thank Nokia Belgium for giving me the opportunity to review this device and Microsoft Belgium for recommending me to Nokia.<br /><br /><i>I have done my best to add some good quality photos to this review. For a more complete photographic overview I refer to <i><a href="" target="_blank">The Verge</a></i>.</i><img src="" height="1" width="1" alt=""/>Wouter place in VRT mashup competition<div class="separator" style="clear: both; text-align: left;"><a href="" imageanchor="1"><img border="0" height="406" src="" width="640" /></a></div><br />Over, ...<br /><br / <a href=""></a><br /><br />I used a few technologies and services I had never tried before and learned a lot: SignalR, HTML 5 audio, KnockoutJS, ...<br /><br /><div class="separator" style="clear: both; text-align: left;"><a href="" imageanchor="1"><img border="0" height="577" src="" width="640" /></a></div><br />The winners were announced during VRT Barcamp last Saturday, I couldn't be there but @greyscarlet on Twitter was kind enough to share a video of the announcement:<br /><br /><blockquote class="twitter-tweet" lang="nl"><p>Bekendmaking winnaars <a href="">#vrtmashup</a> staat online: <a href="" title="">ow.ly/1EuDVY</a>. Proficiat@<a href="">wouterdevinck</a>, @<a href="">MatthiasDVr</a> en @<a href="">ikbenmartijn</a>! <a href="">#bcvrt</a></p>— Karen (@greystarlet) <a href="" data-januari 21, 2012</a></blockquote><script src="//platform.twitter.com/widgets.js" charset="utf-8"></script><br />And this is the video:<br /><br /><iframe width="480" height="378" src="" scrolling="no" frameborder="0" style="border: 0px none transparent;"> </iframe><br /><br />I got a third place and won an iPad, <a href="">vrtwebradio.be</a> is second and the winner is <a href="">@hoeishetverkeer</a>. I especially liked hoeishetverkeer, a deserved winner!<br /><br />Honorable mentions (the few I have seen on Twitter): <a href="">Radiofy</a> and <a href="">Stubrify</a>. If there are any others that deserve a mention: let me know.<img src="" height="1" width="1" alt=""/>Wouter Lumia 800 launched in BrusselsFriday night I was invited to an exclusive event in Brussels: the Belgian launch of the Lumia 800, Nokia's new flagship smartphone. <br /> <img src="" /><br />About a hundred bloggers and other "influential" people from the community were invited to come take a look at this new device. I already knew most of what they had to say, because of course the Lumia 800 has launched in several countries over the past few months and because I have been using Windows Phone 7 devices since before they were released in Belgium (over a year ago). Nevertheless, it was a fun and interesting evening. Nokia has given me a Lumia 800 device to review, so stay tuned! I am still in the middle of the exam period, so I will post my full review in about two weeks, but I promise that it will be a very thorough one. By then the device will be available in Belgium for 499 euros (release date: February 1st).<br /><br />Earlier that day the press was invited, this is the television news report (VRT - Het Journaal 19u 20/01/2012):<br /><br /><iframe allowfullscreen="" frameborder="0" height="315" src="" width="560"></iframe><img src="" height="1" width="1" alt=""/>Wouter lecture at KHBO Oostende about Windows Phone development<div class="separator" style="clear: both; text-align: left;"><a href="" imageanchor="1" style=""><img border="0" height="169" width="643" src="" /></a></div><br />Another one in our series of guest lectures: this morning Sebastiaan, Alexander and I are doing a guest lecture at KHBO Oostende. I am posting this while Alexander is still giving his XNA demo, so far so good! <br /><br />The content: <ul> <li><strong>Introduction</strong> (slides below): <em>me talking about the phone for 30 minutes</em></li><li><strong>Silverlight demos</strong>: <em>I did the first, Sebastiaan the others< lecture at KATHO about Windows Phone developmentThis morning I did a guest lecture / workshop about WP7 development with two fellow MSPs: Alexander Dooms and Sebastiaan Polfliet. It was well received and we would like to thank the audience for being so great. <br /><br />The content: <ul> <li><strong>Introduction</strong> (slides below): <em>me talking about the phone for 30 minutes</em></li><li><strong>Silverlight demos</strong>: <em>I did the first three, Sebastiaan the fourth< Timeline privacy<div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style=""><img border="0" width="690" src="" /></a></div><br />I have been testing the <a href="">new profile page</a> that Facebook will start rolling out next week for a couple of days now and I really like it. However, I have some privacy concerns. Of course there is the obvious concern: on the classic profile page it takes quite an effort to click the "show more button" half a million times to see what a certain person was doing back in 2006, while on the new profile page -called Timeline- the same takes, well... a single click. But technically, nothing is exposed that wasn't exposed before.<br /><br />However, there is a more hidden privacy concern. Facebook has algorithms that determine how much you "like" someone, based on your interactions, both private and public. It uses this information to determine which posts to show in the news overview and who to give a prominent place in the sidebar. That is okay as long as they don't share this information with anyone. <br /><br />(or is it? <a href=""></a>)<br /><br />Unfortunately, timeline seems to use some of this information out in the open:<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style=""><img border="0" height="225" width="320" src="" /></a></div><br /><br />Note that one picture is bigger than the others. Why? Well, lengthy private conversations seems to be the answer in this case.<br /><br />Suppose I don't want anyone to know (this blog post kind'a defeats that point). I went on a quest to figure out how to hide this and it took me surprisingly long to figure it out.<br /><br />On top of your "Timeline" profile page you'll find the following buttons:<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style=""><img border="0" height="53" width="272" src="" /></a></div><br />On the next page you can go back in time to the year and month of your choice and hide (or give even more attention to) whatever you want, including new friends.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style=""><img border="0" height="104" width="168" src="" /></a></div><br />So, the key takeaway from this story: if you want to hide something and there is no hide button directly next to it, go looking for it in the activity log. <img src="" height="1" width="1" alt=""/>Wouter! 2.0Today, I have pushed a major update for my Mobile Vikings application for WP7 to the marketplace. Version two is a complete rewrite from the ground up and is supposed to be more robust, more secure and above all: more feature complete. It uses OAuth for authentication. New features: live tile (experimental, as this is quite challenging), multi sim support, usage history, top-up history, vikingpoints, sim details, ... <br /><br /><strike>It may take a couple of days/weeks for this update to appear in the marketplace.</strike><br />Update 14 sept: Viking! 2.0 has successfully passed the marketplace certification procedure and will appear soon.<br />Update 15 sept: Viking! 2.0 is available<br />Update 17 sept: Viking! 2.1 submitted to the marketplace. This update fixes a few minor bugs and one major bug that prevented users from logging in if their password contained any non-alphanumerical characters.<br /><b>Update 21 sept: Viking! 2.1 is available</b> <br />><img src="" height="1" width="1" alt=""/>Wouter lecture at KAHO Sint-LievenThis morning I did a guest lecture about Silverlight and Windows Phone 7 at KAHO Sint-Lieven, a university college in Ghent.<br /><br />Here are my slides:<br /><div style="width:425px" id="__ss_7797187"><iframe src="" width="425" height="355" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe> <div style="padding:5px 0 12px"></div></div><br />The PDC10 samples (links to the other samples are on the slides):<br /><ul><li><a href="">Photobooth</a></li><li><a href="">Barcode scanner</a></li><li><a href="">HTML puzzle</a></li><li><a href="">Rich notepad</a></li></ul><br />The source code:<br /><ul><li><a href="">FlickrLight</a></li><li><a href="">FlickrPhone</a></li></ul><img src="" height="1" width="1" alt=""/>Wouter Yelper<img border="0" height="99" src="" width="320" /><br /><br />A lot of demos on conferences feature Twitter these days. <a href="">Jeroen</a> and I noticed that and decided to do better, what about showing the 700 hundred students attending the developers track on the <a href="">Students to Business day</a> how to build the entire Twitter ecosystem using Microsoft technology? We brought in <a href="">Niels</a> -all the way from <a href="">Keiem</a>- to take care of the WCF stuff.<br /><br /><img border="0" height="426" src="" width="640" /><br /><em>The audience entering the room on the S2B day.</em><br /><br />We named our Twitter clone "Yelper" and built it using C#, ASP.NET MVC 3, Razor, jQuery, WCF, OData, Silverlight (on the phone), ...<br /><br />The website is available on <a href="">yelper.eu</a> and <a href="">yelper.be</a><br />The source code is available on <a href="">yelper.codeplex.com</a><br />The WP7 is available on <a href="">windowsphone.yelper.eu</a> and in the marketplace.<br /><br />The slides of our three sessions are available on <a href="">Slideshare</a> and below:<br /><br /><strong>Session 1</strong> <em>The basic features of the website</em><br /><iframe frameborder="0" height="355" marginheight="0" marginwidth="0" scrolling="no" src="" width="425"></iframe> <br /><br /><strong>Session 2</strong> <em>Adding some more features to the website and building the API</em><br /><iframe frameborder="0" height="355" marginheight="0" marginwidth="0" scrolling="no" src="" width="425"></iframe> <br /><br /><strong>Session 3</strong> <em>The Windows Phone application</em><br /><iframe frameborder="0" height="355" marginheight="0" marginwidth="0" scrolling="no" src="" width="425"></iframe><br /><br /.<img src="" height="1" width="1" alt=""/>Wouter with Scott HanselmanAt PDC 2010 Jeroen and I <a href="">were planning</a> to interview <a href="">Scott Hanselman</a>, but time didn't allow. But no worries! One of our new MSPs, <a href="">Dirk</a>, interviewed Scott this week while he was in Belgium for Web Camp 2011. <br /><br />Here is the video:<br /><br /><iframe title="YouTube video player" class="youtube-player" type="text/html" width="640" height="390" src="" frameborder="0" allowFullScreen></iframe><br /><br />The full list of all interviews (15 to date) is now available on <a href="">interviews.wouterdevinck.be</a>, for your convenience.<br /><br />Thanks to Scott for spending some time with students, to Katrien for helping and to of course to Dirk for doing this.<img src="" height="1" width="1" alt=""/>Wouter vikingapps.be - Apps for vikings on the move<a href="" target="_blank"><img border="0" height="369" width="680" src="" /></a><br /><br />Today I am announcing a website I have built over the past couple of months. <a href="" target="_blank">vikingapps.be</a> is a gallery for applications build on the <a href="">Mobile Vikings</a> API. You can already find quite some apps on this website, but I'm hoping some more will be added over the next couple of days/weeks.<br /><br />This website was built using ASP.NET MVC 2. If you would run into any bugs or find language errors, feel free let me know in the comments or via email.<img src="" height="1" width="1" alt=""/>Wouter some time with the stars at PDC10 and TEE10At the <a href="">Professional Developers Conference 2010</a> and at <a href="">TechEd Europe 2010</a> <a href="">Jeroen</a>, <a href="">Kurt</a> and I have been interviewing some technology rock-stars. <br /><br /><b>Update</b> (28 jan): at PDC we were planning to interview Scott Hanselman too, but time didn't allow. But no worries! One of our new MSPs, <a href="">Dirk</a>, interviewed Scott this week while he was in Belgium for Web Camp 2011. <a href="#scott">I have added the video to this list</a>.<br /><br />This is the complete list, in alphabetical order.<br /><br /><b>Anders Hejlsberg</b><.<br /><br />Part />Part />As Senior Technical Evangelist for Visual Studio Application Lifecycle Management, <b>Brian Keller</b> is all passionate about testing. We sat down with him and tested his knowledge of test-driven development, code contracts and how development is done within the past two years we’ve known <b>Caroline Phillips</b> as the Western Europe academic lead. Since she had recently switched roles, it was the perfect timing to get to know more about her new job, how she ended up working at Microsoft and her vision towards>Don Syme</b> (working on F# at Microsoft Research) and <b>Talbott Crowell</b> (a cofounder of one of the F# usergroups) tell us what F# exactly is and some real life applications. Furthermore we asked him about the future and heading of>Gill Cleeren</b> we find out what is means to be a ‘Regional Director’. His vision on the HTML5 vs Silverlight debate and we end with a rather tricky>Giorgio Sardo</b> is a Senior Developer Evangelist working Microsoft Corporation with a strong focus on Internet Explorer 9 and HTML5. In this interview we’ll find out what exactly HTML5 is, how Internet Explorer 9 is positioned competitors and their work on HTML5>Jacqueline Russell</b> is the new Western Europe academic lead since one month. We learn more about her professional history and whether she manages to keep up with the technical aspects in her new role. What are her plans for students? Is it easy to work with an international’ve already seen <b>Jonathan Carter< have talked to <b>Katrien De Graeve</b> about her job as an evangelist and TechEd track owner, about what students should learn and about what it is like to be a woman at>Mark Russinovich</b>, also a technical fellow at Microsoft, we explored the possibility of cloudinternals or phoneinternals, the difference between his previous job and his new job. We also ask him about the new Windows Internals>Michelle Fleming</b> is the worldwide Microsoft Student Partner program lead. We actually learn what being an MSP is all about and learn more about the new MSP platform. now we all know that <b>Rob Miles</b> /><a name="scott"></a>At Web Camp Belgium 2011 one of our new MSPs, Dirk Schuermans, interviewed <b>Scott Hanselman</b>. Topics: Razor, WebMatrix. Blog: <a href="">< />Thanks to Jennifer Perret for providing us the Flip cameras and to everyone who took place in front of our camera!<img src="" height="1" width="1" alt=""/>Wouter and Donkey on another worldwide adventure<i>Some heroic tales about TechEd Europe 2010…</i><br /><br />Last week I have been at <a href="">TechEd Europe</a> in Berlin. I was there together with <a href="">Jan Potemans</a> and four other Belgian student partners: <a href="">Jeroen</a>, <a href="">Kurt</a>, Julien and Raphaël. It was my third time at TechEd Europe, but once again I had the time of my life.<br /><br /><img border="0" src="" width="340" /> <img border="0" src="" width="340" /><br /><br />I have to admit that the past three weeks have been crazy, I've <a href="">traveled about 19000 km</a>,!<br /><br />We flew to Berlin in a cozy <a href="">Avro RJ100 airplane</a> with Brussels Airlines. After the short flight from Brussels to Berlin we hurried to our hotel, dropped off our bags and then hurried to the Messe conference center. Despites our efforts we arrived <i>fashionably late</i> at the MSP Summit. Over there, we had some interesting discussions, followed by some presentations, including a presentation about the cloud -because of course that’s obligatory these days- and the usual Microsoft recruitment talk by Holly Peterson.<br /><br />At TechEd we also met “the new Caroline” and “the new Leandro”. Jacqueline Russell is the new Academic Lead for Western Europe and Michelle Fleming is now worldwide in charge of the MSP program.<br /><br />This year we didn’t see that much of Berlin. We went to a nice restaurant on Tuesday night, where I had <i>Blutwurst</i> and after that we went for a walk in the city.<br /><br /><img border="0" src="" width="340" /> <img border="0" src="" width="340" /><br /><br /! <strike>We will publish ‘em all in a jiffy</strike>. <i><b>Update</b>: watch our interviews <a href="">over here</a>.</i> Special thanks to Jennifer Perret for equipping us with Flip cameras for these interviews.<br /><br /><img src="" border="0" width="340" /> <img src="" border="0" width="340" /><br /><br />At the Belgian county drink on Wednesday we had a good time too, we had some interesting conversations and met some great people. Good thing Luc Van de Velde introduced his team, I already knew most of them, but the new MSPs didn’t.<br /><br /…<br /><br />Friday was a sad day. In the morning we went to a last session, said goodbye to the nice folks at U2U and left the conference center. It was time to fly back home. <i>The end of another great adventure!<br /><br /><b>PS</b>: Donkey is Jeroen<br /><br /><b>Disclosure</b>: I attended TechEd as a guest of Microsoft. Special thanks to Caroline Phillips, Jan Potemans, Jacqueline Russell and Michelle Fleming.</i><img src="" height="1" width="1" alt=""/>Wouter about flying halfway around the world for a two day conference<i>You should try that too. Seriously.</i><br /><br />Last week, <a href="">Jeroen Verhulst</a> and I flew to <b>Seattle</b> to attend the <b>Microsoft Professional Developers Conference</b>..<br /><br /><img src="" /><br /><br />On Wednesday, the day before the conference, <a href="">Bart De Smet</a> showed us around in Seattle. Bart is a young Belgian who currently lives in Bellevue and works for Microsoft. We visited the classic tourist spots: the first Starbucks, the Space Needle, the monorail… <a href="">Click here for some more pictures</a>.<br /><br /><img src="" /><img src="" style="float: right;" /><br /><br />After this quick visit we headed to campus. After a quick tour we headed to building one, where we had a meeting with <a href="">Jennifer Perret</a>. Jennifer gave us both a flip camera and a mission: we had to go interview some speakers. Later that week we have interviewed <a href="">Anders Hejlsberg</a>, <a href="">Don Syme</a> and Bart De Smet and we plan to interview some more speakers at TechEd Europe next week. <strike>I am still busy processing and uploading the videos, but I will make sure to post the links on this blog when they are available.</strike> <i><b>Update</b>: watch our interviews <a href="">over here</a>.</i><br /><br />Thursday was day one of the conference. The keynote was delivered by Steve Ballmer and Bob Muglia. The main topics of the keynote were IE9, HTML5, WP7 and a lot about Windows Azure.<br /><br />You can find some more info about the announcements <a href="">here</a> and on the <a href="">SQL Azure Team Blog</a>.<br /><br /><img src="" /><br /><br /. <a href="">Long Zheng</a> and <a href="">Nick Eaton</a> also blogged about this.<br /><br /><img src="" /><img src="" style="float: right;" /><br /><br /><b>The recordings of the keynote and all sessions are available <a href="">here</a>.</b><br /><br />We also expected Microsoft to announce the next version of Silverlight. Apparently we weren’t the only ones who were expecting this. Microsoft however barely mentioned Silverlight in the keynote. Then, Mary Jo Foley published <a href=";content">a blog post</a>, based on an interview with Bob Muglia who said that Microsoft’s strategy with Silverlight has shifted. Bob did not announce the end of Silverlight, however, on the internet a storm broke loose.<br /><br /><img src="" width="300" /><br /><br />I regret Microsoft is didn’t make any Silverlight announcements at the PDC, but here is why I think the rumors of Silverlight’s death are greatly exaggerated:<br /><ul><li>Releases are slowing down, that’s true, but isn’t that normal as a product matures? Furthermore, the Silverlight team must have spent a lot of time on Windows Phone 7.</li><li>Microsoft is hosting a <a href="">Silverlight Firestarter event</a>, keynoted by Scott Guthrie, December 2.</li><li><a href="">This</a> interview with Scott Guthrie.</li><li><a href="">This blogpost</a> by Bob Muglia and <a href="">this one</a> by Tim Heuer. Update: <a href="">this one</a> by Scott Guthrie.</li></ul><br /><img src="" /><br /><br />Lunch was in a tent outside, where you had to choose a table by discussion topic. I don’t know who came up with that idea, but it was rather annoying to have to talk to people working on product X about their product while having lunch.<br /><br /).<br /><br /><img src="" /><br /><br /! <br /><br />After lunch we had to choose between <a href="">Bart’s session</a> and <a href="">Ander Hejlsberg’s session</a> <a href="">over here</a>. I won’t discuss the other sessions I have attended this first day and the second day.<br /><br />On Saturday we attended a workshop about Windows Phone 7 at the Microsoft Platform Adoption Center (building 20). It was okay, but way too crowded. On Sunday we flew home.<br /><br /><i>Disclosure: Microsoft Belgium sponsored this trip by paying for our flights. Special thanks to Jan Potemans for making this possible.</i><img src="" height="1" width="1" alt=""/>Wouter Cup 2010 worldwide finals in Poland<i>What an amazing week we had…</i><br /><br /><img border="0" height="104" src="" width="320" /><br /><br />I’m just back from the Imagine Cup worldwide finals in Warsaw, Poland. <a href="">Jan Potemans</a>, our awesome Belgian ADE -the person at Microsoft Belgium who takes care of the relations with the academic world- took two teams to the finals of this huge technology contest. I led the Belgian Software Design team (Niels Derdaele, <a href="">Jeroen Verhulst<.<br /><br / <i>cup</i>) and USD 25 000. A total of about 325 000 students participated in the Imagine Cup 2010, about 400 of them made it to the worldwide finals. It was our honor to represent Belgium.<br /><br /.<br /><br /><a href=""><img src="" /></a><br /><br />The opening ceremony on Saturday evening took place on a stage in front of the Palace of Culture and Science. <a href="">Jon Perera</a> -GM of Microsoft Education- did most of the talking, together with <a href="">Waldemar Pawlak</a> -Polish Deputy Prime Minister and Minister of Economy- and <a href="">Jacek Murawski</a> –GM of Microsoft Poland. <a href="">Zakopower</a>, a Polish folk music group, added some music to the opening. Video below, courtesy of Microsoft (yes, I have seen me />Sunday morning we had a few briefings by awesome people like <a href="">Lisa Harper</a> and <a href="">Rob Miles</a> (our captain). Something that was immediately clear during these briefings was that the event was very well organized. Picture courtesy of Niels Derdaele.<br /><br /><a href=""><img border="0" src="" width="400" /></a><br /><br /.<br /><br />Then it was time to present. We checked in at the Palace of Culture and Science and were escorted to the Intercontinental hotel by a Polish <a href="">MSP</a>..<br /><br /><a href=""><img src="" /></a><br /><br /.<br /><br /><a href=""><img src="" /></a><br /><br />Monday, we decided to explore Warsaw. We did a little walk and found a war museum; they were closed but had an impressive collection of planes, helicopters and tanks in their “garden”. Just one of many pictures I took, so you get the idea.<br /><br /><a href=""><img src="" /></a><br /><br /).<br /><br /><a href=""><img src="" /></a><br /><br />Monday night the other Belgian team -the gaming team- was selected top three. From then on it was up to them to defend the Belgian honor -something they’ve done great, but more on that later.<br /><br /><a href=""><img src="" /></a><br /><br /…<br /><br /><a href=""><img height="267" src="" /></a> <a href=""><img src="" /></a><br /><br />Living picture with Daniel van Soest; Tom Verhoeff –the mentor of the Dutch team, in orange– and some people of Kenyan and Ugandan national TV.<br /><br / <i>can</i> change the world and that technology really <i>can</i> help solve the world’s toughest problems.<br /><br /><a href=""><img src="" /></a><br /><br /.<br /><br /><a href=""><img border="0" src="" width="400" /></a><br /><br /.<br /><br /><a href=""><img src="" /></a><br /><br / <a href="">here</a>.<br /><br />Message from Michelle Ob /><b>The winners</b><br /><br /><i>Software Design</i><br /><br /><b>1st</b> Place: Skeek, Thailand<br />They film a lesson using a webcam, do facial detection and speech recognition and translate what is being said to sign language. The text is displayed in a speech bubble on the video and the signs are shown on a 3D model. <i>Impressive!</i><br /><br /><b>2nd</b> Place: TFZR Team, Serbia<br />An interface to control the PC with your brain: send text messages, use Facebook… This team told the story of how they enabled someone who had never been able to communicate before to use a PC to do just that, communicating. <i>Wow</i><br /><br /><b>3rd</b> Place: OneBeep, New Zealand<br />Developed a protocol to broadcast files (for example applications for <a href="">OLPC</a>) over AM radio. <i>How is it possible no one has thought of that before?</i><br /><br /><i>Embedded Development</i><br /><br /><b>1st</b> Place: SmarterME, Taiwan<br /”. <i>Amazing.</i><br /><br /><b>2nd</b> Place: MCPU, Russia<br />A robot, talking Russian, driving around and moving arms up and down. Supposed to teach children exercises and stories/songs. <i>Not that enthusiastic about this one…</i><br /><br /><b>3rd</b> Place: GERAS, France<br />An intelligent floor. The system automatically calls the emergency service if the (elderly) occupant falls on the floor and is unable to get up again. <i>Good idea, but I see some deal-breaking issues with their solution.</i><br /><br /><i>Game Design</i><br /><br /><b>1st</b> Place: By Implication, Philippines<br /><i>Best presentation. Ever.</i><br /><br /><b>2nd</b> Place: NomNom Productions, Belgium<br /><i>Well done guys! And M’Boko.</i><br /><br /><b>3rd</b> Place: Gears Studio, France<br /><i>Maybe try to avoid the shooting next time? I liked the level editor.</i><br /><br />At the same time of the Imagine Cup –the world cup for technology-, the football world cup was happening is South Africa. A video: />Oh, are you wondering what we’ve built? We’ve built a social network for partnerships. Learn more on <a href=""></a>. Here are the slides of our presentation: <br /><br /><div id="__ss_4731301" style="width: 425px;"><object height="355" id="__sse4731301" width="425"><param name="movie" value="" /><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><embed name="__sse4731301" src="" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"></embed></object></div><br />My pictures are available <a href="">here</a> and below.<br /><br /><object data="data:application/x-silverlight-2," height="450" type="application/x-silverlight-2" width="680"> <param name="initParams" value="username=wouter.devinck,album=5490480260430748801" /><param name="source" value=""/><param name="onError" value="javascript:void(0);" />="border: 0px; height: 0px; visibility: hidden; width: 0px;"></iframe><br /><br /. <br /><br />Keep changing the world!<img src="" height="1" width="1" alt=""/>Wouter lecture at KAHO Sint-LievenToday I was invited to do a guest lecture at <a href="">KAHO Sint-Lieven</a>, a school in Ghent.<br /><br />My lecture consisted of two parts: the presentation I did at the Students to Business day and an overview of some real-world Silverlight applications and some demos.<br /><br />For the slides and demos of the first part: please refer to <a href="">this blogpost</a>.<br /><br />And here are the links to everything I showed during the second part:<br /><br /><i>Real-world apps</i><br /><ul><li><a href="">Eye on earth</a></li><li><a href="">Hardrock cafe memorabilia</a></li><li><a href="">Sobees</a></li><li><a href="">Barcode builder</a></li><li><a href="">Facebook client</a></li></ul><i>Siverlight Toolkit</i><br /><ul><li><a href="">Source code on Codeplex</a></li><li><a href="">Demos</a></li></ul><i>Demos from the PDC</i><br /><ul><li><a href="">Photobooth</a></li><li><a href="">Barcode scanner</a></li><li><a href="">HTML puzzle</a></li><li><a href="">Rich notepad</a></li></ul><img src="" height="1" width="1" alt=""/>Wouter 2010: Wrap-up (part 3)<i>Looking for <a href="">part 1</a> or <a href="">part 2</a>? Or maybe just looking for <a href="">my Silverlight demo</a>?</i><br /><br />Thursday April 1st, last day in this three day story.<br /><br />First up, <a href="">Scott Hanselman</a>.<br /><br /><a href="">Bart De Smet<.<br /><br />During the lunch the same problem as Wednesday, not one, but two talks I wanted to see. Blogging tips by Scott Hanselman or WP7 development by <a href="">Charlie Kindel</a>. I chose Scott, but I should have chosen Charlie. Gimme that video!<br /><br />After the lunch I joined a huge crowd to see Sara Ford giving some <a href="">VS2010 tips</a>. The talk was even delayed a few minutes because they could get everyone in the room in time. The tips were useful, but unfortunately Sara was very nervous. So Sara, no reason to be nervous, you did great!<br /><br />Then Peli the Halleux tried to bore us to death with a session about <a href="">Moles and Pex</a>. No offence, the speaker was fine and his subject interesting, only I was really tired and I already knew most he talked about from <a href="">TechEd</a>.<br /><br />After that I decided to take a break in the speakers’ room and start writing this series of blog posts. That's where <a href="">Arlindo</a> introduced Jeroen and I to <a href="">Julie</a>. That’s all I’m going to write about that… <i>ever</i><br /><br />John R. Durant closed the conference with a few words about developing on top of Office 2010. Good presentation, but I would have liked to see some more code (e.g. the code of the “backstage” example)<br /><br /><i>This was the last post in this series about the Techdays, I hope you enjoyed it!</i><img src="" height="1" width="1" alt=""/>Wouter 2010: Wrap-up (part 2)<em>Find part 1 of this post, about the Students to Business day <a href="">here</a>.</em><br /><br />Now something about the actual Techdays. Wednesday and Thursday, while the other students were back at school, we attended the Techdays. This year’s Techdays where really, really good. Look at the list of speakers: <a href="">Anders Hejlsberg</a>, <a href="">Scott Hanselman</a>, <a href="">Sara Ford</a>, Rafal Lukawiecki, <a href="">Charlie Kindel</a>, our own <a href="">Bart De Smet</a>, …<br /><br />Anders Hejlsberg kicked off the developer part of the conference with a keynote about trends in (and the future of) programming languages. He talked about things like dynamic and functional programming. The video is already available on <a href="">Channel 9</a> and I’ve embedded it below. Definitely worth an hour of your time!<br /><br /><object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="512" height="384"> <param name="source" value="" /><param name="initParams" value="deferredLoad=true,duration=0,m=, thumbnail=, postid=540293" /><param name="background" value="#00FFFFFF" /><a href="" style="text-decoration: none;"> <img src="" alt="Get Microsoft Silverlight" style="border-style: none"/> </a> </object><br /><br />After the keynote I’ve seen <a href="">Katrien De Graeve</a> and <a href="">Gill Cleeren</a>.<br /><br />During the lunch I had to choose between two sessions I liked to see. Something about XNA by a former <a href="">Imagine Cup</a> winner, <a href="">Timothy Vanherberghen</a> and something about the Surface application in Belgian TV show “<a href="">De Kinderpuzzel<!<br /><br />Then I went to <a href="">Giorgio Sardo</a>’s session about HTML5 and IE9. He didn’t show anything really shocking, check out the <a href="">platform preview</a> and you’re back up to date. One thing I really liked was Giorgio’s opinion about the <a href="">Acid 3</a> <i>the current version of</i> Opera can do the trick just as fast as <i>the preview of</i> IE9, take a look at the screenshot or <a href="">try it yourself</a>).<br /><br /><a href=""><img src="" border="0" /></a><br /><br />What I do care about, is how fast a browser <b>feels</b>..<br /><br /, <i>a calculator</i> and <i>some rulers</i>. <i>designers</i>…)”.<br /><br /><a href="">Scott Hanselman</a> then tried to teach us some “ASP.NET MVC 2 ninja blank belt tips”. Good tips, great speaker. Loved it. Giorgio Sardo took the last session slot with a talk about Windows Phone 7 <strike>Series</strike> (<a href="">why you can drop that last word</a>). This was (correct me if I’m wrong) the first public WP7 demo in Belgium. It’s pretty hard not to like that.<br /><br />Then I had Chinese food with <a href="">Jeroen</a>. (many people told me not write about the food, so I <i>really</i> had to write that…)<br /><br /><i><strike>Part three coming soon …</strike> <a href="">Move on to part 3</a></i><img src="" height="1" width="1" alt=""/>Wouter 2010: Wrap-up (part 1)This week I’ve been attending two Microsoft events in Antwerp: the Students to Business day on Tuesday and the Techdays on Wednesday and Thursday. At the Students to Business day I was a speaker (if you are looking for my demos: <a href="">over here</a>).<br /><br />Let’s start with the Students to Business day. I was very much involved in this event so please forgive me if I’m a bit biased, feel free to comment or mail me if you have any feedback on this event and/or on my talk.<br /><br /: <a href="">The Power of Students</a>.<br /><br /.<br /><br /><img src="" style="float:left;margin-right:10px;" />After the students to Business day we were invited by Microsoft to go to the Sportpaleis to watch Starwars in concert. I’m not exactly a Starwars fan, but still an impressive show!<br /><br /><em>Wednesday and Thursday we attended the Techdays. <strike>I’ll post about the Techdays later.</strike> <a href="">Go to part 2</a></em><br /><br style="clear:both;" /><br /><br /><embed type="application/x-shockwave-flash" src="" width="600" height="400" flashvars="host=picasaweb.google.be&hl=nl&feat=flashalbum&RGB=0x000000&feed=http%3A%2F%2Fpicasaweb.google.be%2Fdata%2Ffeed%2Fapi%2Fuser%2Fwouter.devinck%2Falbumid%2F5455274718302225345%3Falt%3Drss%26kind%3Dphoto%26hl%3Dnl" pluginspage=""></embed><img src="" height="1" width="1" alt=""/>Wouter
http://feeds.feedburner.com/wouterdevinck
CC-MAIN-2017-34
refinedweb
11,170
61.56
Greetings Gentle Reader; I'm thrilled that you've come back to visit! As you might imagine, we're still working very hard on Mustang, aiming to make it the best Java SE release in history. And now with the Mustang Beta release live on the web, we eagerly await your questions, feedback and more of the excellent code contributions you've been sending in. While we wait, of course, we're still deeply involved in resolving our own bug lists and polishing off the features we've released, and we're already fixing things in post-beta builds. With all of this going on, I'm truly happy for the opportunity to bring you up to date with one of my little corners of Java SE. In this new world, where you can read blogs about and download Java SE changes as fast as we can make them, an interesting scenario arises: You have access to code that is evolving; stuff that has the potential to change (for the better). This is an extremely positive thing! We want the code in your hands as quickly as possible, allowing you to test drive it, provide feedback, and to help us improve. But this implies a certain obligation for those of us who blog about our evolving technology - we need to keep you current with any changes to what we've already shared. It's only fair :-) Which brings me to the purpose of this particular blog entry. I'd like to introduce you to the new support for choosing the drop action with Swing Drag and Drop, and narrate how the addition of this support prompted positive change to one aspect of the API I've already spoken of. The story begins with drop actions... Every drag source (Java based or otherwise) advertises the set of actions it supports when exporting data. If it supports data being copied, it advertises the copy action; if it supports data being moved from it, then it advertises the move action; etc. (With Swing components, source actions are advertised via the TransferHandler's getSourceActions method.) When a drag is initiated, the user has some control over which of the source actions is chosen for the transfer, by way of keyboard modifiers used in conjunction with their drag gesture. Typically, an ordinary drag indicates a preference for moving, holding control while dragging indicates a preference for copying, and holding both shift and control gives a preference to linking. The so-called user action is determined by the system by choosing an appropriate value from the source actions based on this preference. TransferHandler getSourceActions control shift Prior to Mustang, this nifty little system could only get you so far with Swing Drag and Drop. When accepting a transfer, TransferHandler would always choose the user action as the action for the transfer. This would result in a copy being performed for a user copy action, a move of the data for a move action, and so on. But two things were missing. The first was a way to accept or reject transfers based on the drop action. As I explained in my previous blog entry on First Class Drag and Drop Support in Mustang, this ability was added with the introduction of the TransferInfo class in Mustang. Excellent! The second thing missing was the ability for the developer to explicitly choose an action; for why should the developer be limited to importing solely with the action chosen by the user? TransferInfo Consider a component that wants to accept copied data, but doesn't want the responsibility that goes with allowing data to be moved to it. And consider a drag source that advertises supporting copy as one of its actions. Shouldn't the developer be able to support dragging from this source to our copy-to-only component, regardless of what the user prefers with their drag gesture? Of course they should! I discovered this limitation while composing an upcoming blog entry, and immediately filed bug number 6379813 (TransferHandler should allow the developer to choose the drop action) on the issue. With the fix for this bug comes the changes I'm about to share with you. In order to support choosing the drop action, we determined that the following were needed: Where to add the first three methods was immediately obvious - we already had TransferInfo to hold this kind of information. So we added getSourceDropActions and getUserDropAction for the first two items respectively, and then updated the existing getDropAction to reflect the actual drop action. Now, where to add the ability to choose the drop action required some thinking. An initial thought was to provide a new protected method on TransferHandler that developers could override to return their choice of drop action. But when a use case was considered, this seemed less than ideal: Developer overrides canImport to determine the suitability of a transfer; inspecting the source actions for the action they want, and returning true only if that action is supported. Developer also must override our new method to choose and return the action they want, possibly inspecting the source actions again. Yuck! Not very tidy: A need to override two separate methods, and potentially write the same logic twice. No, it became clear that the right solution would allow the developer to do everything in one place. getSourceDropActions getUserDropAction getDropAction canImport true Knowing that every TransferHandler supporting drop must implement the workhorse canImport method, and that it's the place where developers are already inspecting details of the transfer, it made sense to us that it is also the ideal place for any logic dealing with configuring the drop action. As such, providing support for choosing the drop action became as simple as adding one additional method to TransferInfo, to be called by the developer from canImport. Gentle Reader, it was the addition of this new setDropAction method that began the chain of events leading to the API changes I'm here to update you on. setDropAction You see, with this one tiny change, it came about that TransferInfo was no longer just an informational class - it had suddenly gained behavior. As such, referring to it as an "Info" no longer felt appropriate. And so the name TransferSupport was born. With a quick search and replace in our source base, the TransferInfo name has gone to the recycling bin, and the apt TransferSupport name has taken its place. Same little helper, just a little more power and three extra letters to type ;-) TransferSupport Considering what I've discussed so far, let's see how one implementation of canImport might look in terms of the updated API. This implementation, which uses the new TransferSupport name, accepts drops of Strings and explicitly chooses the COPY action if it's supported by the source; it rejects the transfer otherwise: String public boolean canImport(TransferSupport support) { // for the demo, we'll COPY is supported, choose COPY and accept the transfer if (copySupported) { support.setDropAction(COPY); return true; } // COPY isn't supported, so reject the transfer return false; } As I mentioned, this implementation rejects the transfer if COPY isn't a supported action of the drag source. Alternatively, the last line could instead return true, in which case the drop is accepted with the user drop action (the default if an action isn't explicitly chosen) if the COPY action isn't available. Let's try this out with a demo. As these are up to the minute changes that I'm discussing, you'll need to wait until build 76 or later of Mustang is available to run the demo. At the time of this writing, the current weekly build available for download is 71. Once you have the correct build, click here to launch the demo. When it launches, you're presented with a frame containing three JList components. The larger list on the left, labelled "Drag from here" acts as a drag source for the demo, supporting both copying and moving of its data, and advertising this via its TransferHandler's getSourceActions method. On the right side are two smaller lists that act as targets for drops. The top one, labelled "Drop to COPY here", has a TransferHandler that always chooses a copy action, with a canImport implementation exactly the same as the code snippet I've shown above. Similarly, the bottom one, labelled "Drop to MOVE here", always chooses a move action, with the same code, but using MOVE in place of COPY. JList Go ahead and initiate a drag from the source list and drag into the upper target list. Notice while you're dragging over the target that the use of the copy action is indicated by the copy-drop mouse cursor, which shows a little plus sign. This can be seen in Screen Shot 1 below. Screen Shot 2 illustrates the effect of dropping into this list: The dragged item is inserted into the target, but not removed from the source - a perfect copy drop. Now drag again from the source list, and into the lower target list. While you're dragging over this target, notice that the mouse cursor indicates a drag action without the plus sign - indicating that the move action is in use (see Note below - a known, and soon to be fixed, bug may cause a no-drop cursor to be shown instead). This is shown in Screen Shot 3 below. When you drop into this list, notice that the dragged item is inserted, and removed from the source - the effect of a move drop. The result is illustrated in Screen Shot 4 below. For a little bit of added fun, try dragging a snippet of text from your favorite native text editor into the target lists to see the same results. Most text editors support dragging text as both copy and move, and the support I've discussed works for both Java and non-Java components alike! Note: Before we move on, one final note on behavior you may encounter while trying out this demo, depending on what build you are using to run it. I've just discovered a small bug in the underlying drag and drop subsystem, such that explicitly choosing an action other than the user action causes the no-drop mouse cursor to be shown when the drag source is Java based. Until this bug is fixed, you'll unfortunately see the no-drop cursor instead of the copy-drop cursor when dragging into the bottom target list. This does not affect the functionality of the demo, or the ability to actually drop into the component. I've filed this as a high priority bug and expect to see it fixed shortly. For your reference, the bug number is 6385534 (For Java drag source, choosing an action other than the user action shows a no-drop cursor). Okay, so now you've learned about choosing the drop action, and the name change from TransferInfo to TransferSupport. Recalling what I mentioned earlier about upcoming changes to API that has already been released, you may be wondering if I've already covered it - and if a search and replace of the term TransferInfo in your code will bring you up to date. Well, the answer is "it depends". If you happen to have read my blog entry on Location-Sensitive Drag and Drop in Mustang, and have already started taking advantage of the new shouldIndicate method in TransferHandler, to specify whether or not the drop location should be indicated by the target of a transfer, you'll need to prepare for another small change. shouldIndicate You see, the line of thought that saw setDropAction added to TransferSupport, rather than providing another overridable method to TransferHandler for choosing the drop action, led to a re-evaluation of our placement of the recently added shouldIndicate method. Like choosing a drop action, deciding whether or not to show the drop location likely involves inspecting many of the same things that a developer would already be looking at in canImport. With a fresh look, it now seemed silly to force the developer to override a separate method for the purpose of changing the drop location indication. Do you see where I'm going? TransferHandler.shouldIndicate has been removed and in its place a new method, setShowDropLocation(boolean), has been added to TransferSupport. This new method is to be called from TransferHandler.canImport any time the developer wishes to change the default displayability of the drop location. Let's look at an example of how this simplifies things by contrasting the code for a TransferHandler under the old API and the new API. Consider a TransferHandler implemented to accept drops into a JList only when the data is a String and the drop location is on top of items 0 through 5. Furthermore, let's say that it also wishes to always indicate the drop location, regardless of whether or not it accepts the transfer. Here's the code with the old API: TransferHandler.shouldIndicate setShowDropLocation(boolean) TransferHandler.canImport public boolean canImport(TransferInfo info) { // for the demo, we'll only support drops (not clipboard paste) if (!info.isDrop()) { return false; } // we only import Strings if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) { return false; } // fetch the drop location (it's a JList.DropLocation for JList) JList.DropLocation dl = (JList.DropLocation)info.getDropLocation(); // return true for index 0 through 5, and false otherwise return (dl.getIndex() >= 0 && dl.getIndex() <= 5) { } public boolean shouldIndicate(TransferInfo info, boolean canImport) { // always show the drop location return true; } It's not too bad in this case, but remember that in reality shouldIndicate and canImport will likely have more in common, such as conditionalizing on the drop location or the data flavors available. This makes the following new approach much more appealing: public boolean canImport(TransferSupport support) { // for the demo, we'll only support drops (not clipboard paste) if (!support.isDrop()) { return false; } // always show the drop location support.setShowDropLocation(true); // we only import Strings if (!support.isDataFlavorSupported(DataFlavor.stringFlavor)) { return false; } // fetch the drop location (it's a JList.DropLocation for JList) JList.DropLocation dl = (JList.DropLocation)support.getDropLocation(); // return true for index 0 through, 5 and false otherwise return (dl.getIndex() >= 0 && dl.getIndex() <= 5) { } Simplicity - removing an override and keeping associated logic together. I like it and I like it a lot! One of the benefits to regular blogging about ongoing Java SE development is that it keeps me constantly re-evaluating and using our new features. Hopefully, it also keeps you excited, so you can help do the same. The end result being a more feature-complete, bug free API. And of course, the best release in history. For your reference, the updated TransferSupport API: Component getComponent() DataFlavor[] getDataFlavors() boolean isDataFlavorSupported(DataFlavor) Transferable getTransferable() Transferable boolean isDrop() IllegalStateException TransferHandler.DropLocation getDropLocation() void setShowDropLocation(boolean) int getUserDropAction() int getSourceDropActions() int getDropAction() void setDropAction(int) IllegalArgumentException Good article. I am happy to see these improvement in the new JSE 6. I wonder if a feature I was long wish to be able to use was that when I drag something from my application, and drop on the desktop, that would be a file drop then. However, I don't want to do a file copy, but I want to write the file to where the user drops at. A work around would be to write to a temp directory, then when drop, I would move it from there to the drop place. However, this is hack at best, and there's many issue with it including security (if the file content is sensitive), etc. I am really disappointed if this is not addressed in the new release. Posted by: st946tbf_3 on February 15, 2006 at 12:41 PM st946tbf_3, thanks for posting your comment and asking this question, one that we've actually received quite often. I'm really sorry to answer that support for what you wish to accomplish is not yet available or targeted for Mustang. Implementing this requires the addition of new API in the underlying AWT drag and drop system (which Swing sits on top of), and unfortunately this feature hasn't made the cut for the upcoming release. If it's any consolation, please know that both the Swing and AWT teams know the importance of this issue and it's been tabled to be considered as a feature for the Dolphin release. Please help show your support by voting for the associated RFE, 4808793. Also, if you're interested, someone recently initiated a conversation with the AWT drag and drop owner on this exact issue, in this forum thread. Thanks! Posted by: shan_man on February 15, 2006 at 08:06 PM Thank you for the reply and the links. Please don't be offended by my comment althought it's frank. I write this not to offend anyone, but point out a serious problem at Sun and Java. I think Sun has to reconsider their priority here. Waiting 2 years for Mustang and another 2 years for Dolphin would mean 4 years of waiting for a simple problem like this (think Winzip type application). 4 years often equals to a rise a fall of many platforms, technology. With the bug filed in Jan 2003 (ofcourse, people having problem with this since 1997, 1998), I think someone at Sun need to resign for the benefit of Sun and Java community. This is not a developer problem, it's the manager's who is managing the Java development. Posted by: st946tbf_3 on February 16, 2006 at 09:45 AM Nice. One note regarding D&D on Linux. I've observed that when dropping files from Nautilus (Gnome file mananger) on Java app only accesible flavor is DataFlavor.stringFlavor (not DataFlavor.javaFileListFlavor...). That mean that you can get only string like ''. For example when running app posted by RomainGuy here D&D don't work on my Ubuntu (funny thing that RomainGuy tested it on Ubuntu under VMWare and according to his words everything was ok). This behavior was observed on Java <= 1.5 and previous snapshots of Mustang. Not sure about current state, I will test it and post message if it works or not... Posted by: spk on February 17, 2006 at 03:36 AM Thanks for the note on this Linux behavior, spk. I've passed this along to the engineers responsible for the AWT Drag and Drop subsystem, and asked them to either follow-up here directly, or fill me in so I can post a response to you concern. Posted by: shan_man on February 20, 2006 at 10:40 AM Let me answer the above-mentioned question concerning javaFileListFlavor on Gnome. It's a known issue, for which I proposed a solid workaround; refer to bug 4899516 and also see my advice at. Hope this helps. Posted by: alexander1 on March 01, 2006 at 08:22 AM I spent a lot of time getting this sort of behavior to work under 1.4. The behaviors I was looking for were the following: * if no modifier keys are pressed, choose an action based on the intersection of source and target actions * if a modifier key is pressed, set the action to NONE if the user-requested action is not allowed The only thing I couldn't do with the existing classes was change the drop target's acceptance if the modifier keys were changed during a drag (the source has access to this info, the drop target does not -- once the drop target says "no", it stops getting messages). With the addition of a global flag from the source drag handler, the drop target could adjust on the fly. I also tricked out the drag handler to automatically paint a drag image on any frame in the same VM, but that was just for fun. Posted by: twalljava on April 15, 2006 at 07:08 AM br/ is the code of this demo available for download ? Posted by: kaba on May 10, 2006 at 03:26 AM I've just been perusing the 1.6 source, specifically around customizing drop support when using a TransferHandler. It strikes me a bit odd that "dropLocationForPoint" is package-protected, and that the notes for TransferHandler.DropLocation suggest that it wouldn't be used by developers. Those seem the likely extension points if I'm writing a custom component with drop support. Don't I need to create a custom DropLocation that adequately translates a Point into something meaningful for my new drop target? Every time DnD gets changed to make things "simpler", it seems a chunk of the original DnD extensibility/customizability gets made inaccessible. With TransferHandler, it was the ability to customize the DragSourceListener (or even to add one). Why can't the DnD support be extensible rather than requiring total replacement? Why aren't TransferHandler.DragHandler and TransferHandler.DropHandler extensible? Granted, I can add global listsners to DragSource, and suppress the default drop support, but then I'm back to square one, and all this DnD "simplification" has bought me nothing. Posted by: twalljava on July 17, 2006 at 04:03 AM kaba: The code for this demo has not been posted. However, I'm looking into how I can make it available. Thanks! Posted by: shan_man on November 22, 2006 at 12:45 PM twalljava: We're always cautious about adding new public/protected API. We don't want to accidentally release something that is overly confusing, or not extensible, or limits future enhancements. Some of the enhancements we've been able to do for Java SE 6 were possible because we don't expose too much implementation. However, we know there's need for balance. And I agree with you about "dropLocationForPoint". We currently have an RFE tracking this issue: 6448332 (allow custom components to support drop location exchange). As always with the Swing API, if you have other areas that you think need to be opened up, please file RFEs and we'll address them. Thanks! Posted by: shan_man on November 22, 2006 at 12:56 PM I am VERY confused by all of this. I think I'm missing a very important article that describes all of these various "actions." I do not understand how to get any drag and drop to work with the old or new API. It seems like there is always a circular reference that is created to support this. (TransferHandler knows about JPanel which knows about the TransferHandler) Can anyone point me to any tutorial anywhere that fully describes Drag and Drop in Java 1.6? Posted by: ronak2121 on December 08, 2006 at 07:44 PM Can anyone please describe what a "linking" action is? Posted by: ronak2121 on December 08, 2006 at 07:46 PM Clipboard Actions in Mustang Hi all. I am working on an extensible framework for drag and drop in Swing which uses the new enhancements brought in by Mustang. Firstly, a huge thanks to all you guys who fixed the drag and drop system for Mustang - it was a right pain to get location-sensitive drop authorisation in Java 5. Now it is a considerably more pleasant experience. Thanks for making things so much easier. However I have a question regarding the clipboard actions in Mustang. I don't want to file this as a bug, because I feel I may be missing the point. So if anyone can help me out, I'd be much obliged. It seems that when one is performing a CUT clipboard operation, Swing wants you to remove the CUTted data before allowing you to paste it. This is due to two factors: firstly, the default implementation of TransferHandler.exportToClipboard() places the data on the clipboard, then immediately calls TransferHandler.exportDone(comp, tr, CUT). This is then the queue for the transfer data to be removed. When the user requests the paste opration later, all that happens is that TransferHandler.importData(support) is called, which will import the data, but no subsequent call to exportDone is made. The obvious problem with this is that if the user cuts some data to the clipboard and then changes their mind, the data is gone (it's already been removed from the component). Secondly, it is illegal to ask the TransferSupport which action is being performed during a clipboard data transfer operation. This means that all the nice action-sensitive "authorisation" (for lack of a better word) that Mustang provides for drag and drop is unavailable for clipboard operations. In fact, it seems that Mustang views clipboard operations as fundamentally different to drag and drop operations, and doesn't treat them with the same respect. Is this summary correct, or have I missed the aim of the implementation. I'd appreciate any help. As it is, this issue (or non-issue as the case may be) is fairly easy to fix, even with a TransferSupport which has been made final ;-p I would propose that clipboard transfer operations and drag and drop transfer operations are essentailly the same thing, and should be (as far as possible) treated as the same. The main issue seems to be that while there is a (very useful !!) DropLocation, there is no ClipboardInsertLocation ... Posted by: jacquesdutoit on March 12, 2007 at 02:30 AM I'd like to reiterate kaba's request. Is the demo source available as a training aid ? Thanks. Posted by: namestka on March 14, 2007 at 08:38 AM
http://weblogs.java.net/blog/shan_man/archive/2006/02/choosing_the_dr.html
crawl-002
refinedweb
4,254
60.14
...one of the most highly regarded and expertly designed C++ library projects in the world. — Herb Sutter and Andrei Alexandrescu, C++ Coding Standards If you plan to insert a class in an intrusive container, you have to make some decisions influencing the class definition itself. Each class that will be used in an intrusive container needs some appropriate data members storing the information needed by the container. We will take a simple intrusive container, the intrusive list ( boost::intrusive::list), for the following examples, but all Boost.Intrusive containers are very similar. To compile the example using boost::intrusive::list, just include: #include <boost/intrusive/list.hpp> Every class to be inserted in an intrusive container, needs to contain a hook that will offer the necessary data and resources to be insertable in the container. With Boost.Intrusive you just choose the hook to be a public base class or a public member of the class to be inserted. Boost.Intrusive also offers more flexible hooks for advanced users, as explained in the chapter Using function hooks, but usually base or member hooks are good enough for most users. For list, you can publicly derive from list_base_hook. template <class ...Options> class list_base_hook; The class can take several options. Boost.Intrusive classes receive arguments in the form option_name<option_value>. You can specify the following options: tag<class Tag>: this argument serves as a tag, so you can derive from more than one list_base_hookand hence put an object in multiple intrusive lists at the same time. An incomplete type can serve as a tag. If you specify two base hooks, you must specify a different tag for each one. Example: list_base_hook< tag<tag1> >. If no tag is specified a default one will be used (more on default tags later). link_mode<link_mode_type LinkMode>: The second template argument controls the linking policy. Boost.Intrusive currently supports 3 modes: normal_link, safe_linkand auto_unlink. By default, safe_linkmode is used. More about these in sections Safe hooks and Auto-unlink hooks. Example: list_base_hook< link_mode<auto_unlink> > void_pointer<class VoidPointer>: this option is the pointer type to be used internally in the hook. The default value is void *, which means that raw pointers will be used in the hook. More about this in the section titled Using smart pointers with Boost.Intrusive containers. Example: list_base_hook< void_pointer< my_smart_ptr<void> > For the following examples, let's forget the options and use the default values: #include <boost/intrusive/list.hpp> using namespace boost::intrusive; class Foo //Base hook with default tag, raw pointers and safe_link mode : public list_base_hook<> { /**/ }; After that, we can define the intrusive list: template <class T, class ...Options> class list; list receives the type to be inserted in the container ( T) as the first parameter and optionally, the user can specify options. We have 3 option types: base_hook<class Hook>/ member_hook<class T, class Hook, Hook T::* PtrToMember>/ value_traits<class ValueTraits>: All these options specify the relationship between the type Tto be inserted in the list and the hook (since we can have several hooks in the same Ttype). member_hookwill be explained a bit later and value_traitswill be explained in the Containers with custom ValueTraits section. If no option is specified, the container will be configured to use the base hook with the default tag. Some options configured for the hook (the type of the pointers, link mode, etc.) will be propagated to the container. constant_time_size<bool Enabled>: Specifies if a constant time size()function is demanded for the container. This will instruct the intrusive container to store an additional member to keep track of the current size of the container. By default, constant-time size is activated. size_type<class SizeType>: Specifies an unsigned type that can hold the size of the container. This type will be the type returned by list.size()and the type stored in the intrusive container if constant_time_size<true>is requested. The user normally will not need to change this type, but some containers can have a size_typethat might be different from std::size_t(for example, STL-like containers use the size_typedefined by their allocator). Boost.Intrusive can be used to implement such containers specifying the the type of the size. By default the type is std::size_t. Example of a constant-time size intrusive list that will store Foo objects, using the base hook with the default tag: typedef list<Foo> FooList; Example of an intrusive list with non constant-time size that will store Foo objects: typedef list<Foo, constant_time_size<false> > FooList; Remember that the user must specify the base hook in the container declaration if the base hook has no default tag, because that usually means that the type has more than one base hook, and a container shall know which hook will be using: #include <boost/intrusive/list.hpp> using namespace boost::intrusive; struct my_tag1; struct my_tag2; typedef list_base_hook< tag<my_tag> > BaseHook; typedef list_base_hook< tag<my_tag2> > BaseHook2; class Foo : public BaseHook, public BaseHook2 { /**/ }; typedef list< Foo, base_hook<BaseHook> > FooList; typedef list< Foo, base_hook<BaseHook2> > FooList2; Once the list is defined, we can use it: //An object to be inserted in the list Foo foo_object; FooList list; list.push_back(object); assert(&list.front() == &foo_object); Sometimes an 'is-a' relationship between list hooks and the list value types is not desirable. In this case, using a member hook as a data member instead of 'disturbing' the hierarchy might be the right way: you can add a public data member list_member_hook<...> to your class. This class can be configured with the same options as list_base_hook except the option tag: template <class ...Options> class list_member_hook; Example: #include <boost/intrusive/list.hpp> class Foo { public: list_member_hook<> hook_; //... }; When member hooks are used, the member_hook option is used to configure the list: //This option will configure "list" to use the member hook typedef member_hook<Foo, list_member_hook<>, &Foo::hook_> MemberHookOption; //This list will use the member hook typedef list<Foo, MemberHookOption> FooList; Now we can use the container: //An object to be inserted in the list Foo foo_object; FooList list; list.push_back(object); assert(&list.front() == &foo_object); You can insert the same object in several intrusive containers at the same time, using one hook per container. This is a full example using base and member hooks: #include <boost/intrusive/list.hpp> #include <vector> using namespace boost::intrusive; class MyClass : public list_base_hook<> { int int_; public: list_member_hook<> member_hook_; MyClass(int i) : int_(i) {} }; //Define a list that will store MyClass using the base hook typedef list<MyClass> BaseList; //Define a list that will store MyClass using the member hook typedef member_hook < MyClass, list_member_hook<>, &MyClass::member_hook_> MemberOption; typedef list(VectIt it(values.begin()), itend(values.end()); it != itend; ++it) memberlist.push_back(*it); //Now test lists { BaseList::reverse_iterator rbit(baselist.rbegin()), rbitend(baselist.rend()); MemberList::iterator mit(memberlist.begin()), mitend(memberlist.end()); VectIt it(values.begin()), itend(values.end()); //Test the objects inserted in the base hook list for(; it != itend; ++it, ++rbit) if(&*rbit != &*it) return 1; //Test the objects inserted in the member hook list for(it = values.begin(); it != itend; ++it, ++mit) if(&*mit != &*it) return 1; } return 0; } Even if the interface of list is similar to std::list, its usage is a bit different: You always have to keep in mind that you directly store objects in intrusive containers, not copies. The lifetime of a stored object is not bound to or managed by the container:
http://www.boost.org/doc/libs/1_52_0/doc/html/intrusive/usage.html
CC-MAIN-2014-10
refinedweb
1,229
53.31
Set the current file position at the operating-system level #include <sys/types.h> #include <unistd.h> off_t lseek( int filedes, off_t offset, int whence ); off64_t lseek64( int filedes, off64_t offset, int whence ); libc Use the -l c option to qcc to link against this library. This library is usually included automatically. These functions set the current file position for the file descriptor specified by filedes at the operating system level.()). The current file position, with 0 indicating the start of the file, or -1 if an error occurs (errno is set).. lseek() is POSIX 1003.1; lseek64() is Large-file support chsize(), close(), creat(), dup(), dup2(), eof(), errno, execl(), execle(), execlp(), execlpe(), execv(), execve(), execvp(), execvpe(), fcntl(), fileno(), fstat(), isatty(), open(), read(), sopen(), stat(), tell(), umask(), write()
http://www.qnx.com/developers/docs/6.5.0/topic/com.qnx.doc.neutrino_lib_ref/l/lseek.html
CC-MAIN-2013-48
refinedweb
128
55.95
Hello, Im Antoine and I try to create a cool site for my service society. I'm french, 30 yo, no develloper. On one page I have 3 repeaters. The container of each repeater consists of an image and a title. Repeater 1 is visible and the other 2 are hidden. I wish that: - when the visitor clicks on the container 1 of the repeater 1, the repeater 2 is displayed and the 1 is hidden. - when the visitor clicks on the container 2 of the repeater 1, the repeater 3 is displayed and the 1 is hidden. This code is not good because he affect all containers. export function container1_click(event) { $w('#group1').hide() $w('#group2').show() } Thank's for your help. #repeater #container #Item1 #Item2 I guess you meant to say: "when the visitor clicks on the container 2 of the repeater 1, the repeater 3 is displayed and the 2 is hidden. " Anyway I'm not sure if you meant that clicking the any container in repeater1 will display repeater 2, or just clicking the first item in repeater1 (index=0) will display repeater 2. please clarify. There will be on the page a parent repeater and 6 other children repeaters(hidden at loading). The goal is that when a visitor clicks on a container (Item1, Item2 ...) it hides the parent repeater and displays the child repeater. @Ant" Je vous dirai qu'en avoir six fera une grande difference en chargeant la page. Ca serait mieux de faire vos connexions avec WixCode pour que ca peut charger assez vite. En fait, vous avez juste besoin de deux repeaters, l'un a gauche connecte en utilisant le GUI et l'autre connecte avec code dynamique. Ca dependrait du numero de databases que vous voulez connecter. @David , ok je vais essayer de me lancer dans cette mission. Merci pour ce conseil. I searched all day, very complicated to find the info, I regret not having studied computer science at school. Please, can you give me at least the beginning of the code? So now I have On one page 2 repeaters. The first is displayed on loading and the second hidden. The first repeater is not connected to a database, it has 2 fields: a title, an image. The second repeater is connected to a database that contains 3 fields: a title, an image, a category. I am looking for the method to: -a visitor clicks on image1 of repeater1, then data of the "delivery" category are displayed in repeater 2. -a visitor clicks on image 2 of repeater 1, then the data corresponding to the "transport" category are displayed in repeater 2 I try this but it's not the good result : export function container1_click(event) { $w("#repeater1").forItems( ["item1"], ($item, itemData, index) => { $w('#group1').hide() $w('#group2').show() }); } Si le seconde repeater est juste connecte a un dataset, voici: @David Thank you for opening the road to success, unfortunately the code does not work ... I continue my search import wixData from 'wix-data'; $w.onReady(function () { $w('#repeater1').onItemReady( ($item, itemData, index) => { let thisCategorie = $item('#title').text; $item('#title').onClick(() => { $w('#dataset1').setFilter(wixData.filter() .eq( 'categorie', thisCategorie) ) ; } ) ; } ) ; } ) ; @Ant" It should work as long as a couple other things are true: 1. You have to go to your repeater 1's properties panel and check onItemReady. 2. You have to make sure it says onItemReady in the properties panel text, and not onItemReady_1. 3. You need to make sure if the title isn't exactly the same letter for letter in your title text as it is in your categorie field, that you play with the code a bit. Check out the wixFilter API. 4. Last, you may have to refresh the dataset1 after the filter is set. I think that should do it! It doesn't work. Yes the collection field has more than one category per item. In the code we filter the dataset1 data but it is not mentioned repeater2, normal? Now in my editor, there is only one category that appears in the repeater2 We agree that I do not have to replace '#title' in the code by the title of each category ? Voici mon email. It should make things faster and easier haha. Bonjour, voici la solution à mon problème, résolu grâce à David.
https://www.wix.com/corvid/forum/community-discussion/resolved-apply-a-different-code-for-each-container-onclick-in-a-repeater
CC-MAIN-2020-05
refinedweb
722
73.58
15 June 2012 23:59 [Source: ICIS news] LONDON (ICIS)--European bisphenol A (BPA) June freely negotiated contract prices have declined by €50-60/tonne ($63-76/tonne) because of weaker demand and competitive offers from Asia, sources said on Friday. ?xml:namespace> June contracts settled at €1,550-1,620/tonne free delivered (FD) northwest Europe (NWE). Although feedstock costs largely increased, most European producers were forced to give discounts to maintain sales volumes and because demand is weak. European BPA plant utilisation rates are at 70% on average and some sources expect these may be further cut if demand does not improve. ($1 = €0.79) Follow Janos Gal on Twitter for tweets on the BPA
http://www.icis.com/Articles/2012/06/15/9570212/europe-bpa-june-contracts-decline-by-50-60tonne.html
CC-MAIN-2014-49
refinedweb
117
58.62
Arch Pipe Arch CompPipe Arch CompPipe Next: Pipe Connector Description This tool allows to create pipes from scratch, or from selected objects. The selected objects must be Part-based (Draft, Sketch, etc..) and contain one and only one open Wire. Usage - Optionally, select a linear Part shape such as a Draft Line, a Draft Wire or an open Sketch. - Invoke this command using several methods: Options - Pipes share the common properties and behaviours of all Arch Components Properties - DataLength: Sets the length of this pipe, when it is not based on a wire - DataDiameter: The diameter of this pipe, when it is not based on a profile - DataBase: The base wire of this pipe, if any - DataProfile: The base profile of this pipe. If not given, the pipe is cylindrical. Typical workflow - Start by placing sanitary/hydraulic appliance Draft Special snap button is turned on. Currently that property is only available to python, though. In the case above I added a new snap point at the exit of the wc appliance. The vectors inside SnapPoints appear on the model as white dots: FreeCAD.ActiveDocument.Equipment.SnapPoints=[FreeCAD.Vector(0,0,100)] - With the new "Snap Special" Draft Snap, you can now snap to these custom points: - Now we can draw our piping using Draft Lines, Draft Wires, or Sketches. The best way, though, is using only Draft Lines: - There is now a new Draft. Scripting See also: Arch API and FreeCAD Scripting Basics. The Pipe tool can be used in macros and from the Python console by using the following function: Pipe = makePipe(baseobj=None, diameter=0, length=0, placement=None, name="Pipe") - Creates a Pipeobject from the given baseobjand diameter. baseobjis a Draft Line or Draft Wire. - If baseobjis omitted, a straight pipe can be created with just the diameterand the lengthin the Z direction. - If a placementis given, it is used. import Draft, Arch p1 = FreeCAD.Vector(1000, 0, 0) p2 = FreeCAD.Vector(2500, 200, 0) p3 = FreeCAD.Vector(3100, 1000, 0) p4 = FreeCAD.Vector(3500, 500, 0) Line = Draft.makeWire([p1, p2, p3, p4]) Pipe = Arch.makePipe(Line, 200) FreeCAD.ActiveDocument.recompute() Pipe2 = Arch.makePipe(diameter=120, length=3000) FreeCAD.ActiveDocument.recompute() Next: Pipe Connector Template:Arch Tools navi/en
https://wiki.freecadweb.org/Arch_Pipe/en
CC-MAIN-2020-24
refinedweb
373
67.35
#include <sys/auxv.h>. When you compile the kernel, it will automatically compile and link the vDSO code for you. You will frequently find it under the architecture-specific directory: find arch/$ARCH/ -name '*vdso*.so*' -o -name '*gate*.so*' The name of the vDSO varies across architectures. It will often show up in things like glibc's ldd(1) output. The exact name should not matter to any code, so do not hardcode it. When tracing systems calls with strace(1), symbols (system calls) that are exported by the vDSO will not appear in the trace output. Those system calls will likewise not be visible to seccomp(2) filters.. The table below lists the symbols exported by the vDSO.:−kernel:fixed−code The table below lists the symbols exported by the vD) The table below lists the symbols exported by the vDSO. The functions marked with a * are available only when the kernel is a PowerPC64 (64-bit) kernel. The CLOCK_REALTIME_COARSE and CLOCK_MONOTONIC_COARSE clocks are not supported by the __kernel_clock_getres and __kernel_clock_gettime interfaces; the kernel falls back to the real system call. The table below lists the symbols exported by the vDSO. The CLOCK_REALTIME_COARSE and CLOCK_MONOTONIC_COARSE clocks are not supported by the __kernel_clock_getres and __kernel_clock_gettime interfaces; the kernel falls back to the real system call. The table below lists the symbols exported by the vDSO. All of these symbols are also available without the "__vdso_" prefix, but you should ignore those and stick to the names*'
http://manpages.courier-mta.org/htmlman7/vdso.7.html
CC-MAIN-2019-18
refinedweb
247
56.66
User talk:O. Support request I have a LINUX machine with the OpenNao distro (based on GENTOO). This machine has Python 2.7.3. I do not have root permissions. You can download an executable image in Virtualbox (OpenNAO OS VirtualBox 2.1.2) from the following link (you will probably have to create an account): My problem is that I am trying to make a call request to an AZURE server that has TLS 1.2, with the following code: import requests url = "" # it is not a real url querystring = {"key":"value",} headers = {'token': "4bfd740f482d48a3a894445eb6a85a83",'Username': "user",'Password':"password"} - response = requests.request("GET", url, headers=headers, params=querystring) response = requests.get(url, headers=headers, params=querystring, timeout=30) and I get the following error: /var/persistent/home/nao/.local/lib/python2.7/site-packages/persistent/home/nao/.local/lib/python2.7/site-packages/urllib3/util/ssl_.py:137: Traceback (most recent call last): File "heathrowFI-3.py", line 33, in <module> response = requests.get(url, headers=headers, params=querystring, timeout=30) File "/var/persistent/home/nao/.local/lib/python2.7/site-packages/requests/api.py", line 72, in get return request('get', url, params=params, **kwargs) File "/var/persistent/home/nao/.local/lib/python2.7/site-packages/requests/api.py", line 58, in request return session.request(method=method, url=url, **kwargs) File "/var/persistent/home/nao/.local/lib/python2.7/site-packages/requests/sessions.py", line 508, in request resp = self.send(prep, **send_kwargs) File "/var/persistent/home/nao/.local/lib/python2.7/site-packages/requests/sessions.py", line 618, in send r = adapter.send(request, **kwargs) File "/var/persistent/home/nao/.local/lib/python2.7/site-packages/requests/adapters.py", line 490, in send raise ConnectionError(err, request=request) requests.exceptions.ConnectionError: ('Connection aborted.', error(104, 'Connection reset by peer')) I have tried to make the request on other machines (Windows, Ubuntu) with TLS 1.2 and the result is OK. To get the TLS version of each machine I used the following command python -c "import json, urllib2; print json.load (urllib2.urlopen ('')) ['tls_version']" WINDOWS machine with python 2.7 and TLS 1.2 : The result of the request was OK. UBUNTU machine with python 2.7 and TLS 1.2 : The result of the request was OK. I think the error is caused by the TLS 1.0 version of the SSL used by NaoQi. The server to which I make the request is Azure and only supports TLS 1.2. I have checked its TLS in the browser: TLS FROM THE SERVER I have no possibility to update Python (I do not have root permissions). Please, do you know how I can make the request work to the server? Should I update the TLS 1.0 to TLS 1.2 on the NAOQI machine? Do you know how to update it?. Any help or suggestion would be welcome. Thanks in advance, regards. — The preceding unsigned comment was added by Oga (talk • contribs)
https://wiki.gentoo.org/wiki/User_talk:Oga
CC-MAIN-2022-05
refinedweb
498
53.98
iOS UI Testing with KIF Testing UI in iOS apps is an important topic, especially as apps become more complex. Learn how to do iOS UI testing with KIF in this tutorial. Version - Other, Other, Other Users expect a high level of polish from iOS apps, so it’s up to you to design, develop and test your apps to meet ever-rising expectations. Think about it for just a moment: How much time have you poured into conducting basic manual user interface testing? You know the drill…launching your app from Xcode, and incessantly tapping the same series of buttons to make sure no regressions slipped into your design. Surely, there are other things you’d rather do? Instead, consider that the enhanced test UI in Xcode 5 and continuous integration support in OS X Server demonstrate Apple’s commitment to provide developers the best tools. That’s great, you might say, but how do you automate testing simple user actions, like ensuring a double-tap or swipe at the right spot brings up the correct view? Even test scripts and bots don’t have capacitive touch fingers to swipe across the screen…or…do they? In this tutorial, you’ll learn all about KIF (“Keep it Functional”), an open-source user interface testing framework. With KIF, and by leveraging the Accessibility APIs in iOS, you’ll be able to write tests that simulate user input, like touches, swipes and text entry. These tests give your apps an automated, real-world user interface workout, and help keep your mind at ease so you can just focus on developing that killer app – not spending half a lifetime on UI testing. Let’s get testing! Getting Started The sample project is a timer app called Solanum (named after the tomato plant species) based on the Pomodoro time-boxing method. Here’s how it works: you work for a defined number of minutes, take a break, then repeat. After several of these cycles, you take a longer break. The app is a just a simple timer that keeps track of time periods. Feel free to use the app afterwards to help make you more productive during your own development! Download and unzip the starter project archive here. Note that KIF is a separate project, and its role is to build a library for Solanum’s test target. You’ll need to double-click solanum.xcworkspace to open the project in Xcode rather than solanum.xcodeproj. Look for two projects to open in the in the project navigator, it should like the example below. Set the app target to solanum, and select either the 3.5-inch or 4-inch iPhone Simulator target. Don’t use the 64-bit build; at the time of writing this tutorial KIF didn’t appear to be fully compatible. Build and run the app. Look around, then switch to the Settings tab. The app has a debug mode that accelerates time, so you can set a 20-minute timer and it will help with testing by ticking by in 10 seconds. This is just to aid testing the app. You wouldn’t want each test run to take 20 minutes! Turn on Debug Mode switch to speed up the timer. Next, tap the Clear History button, and then tap Clear on the confirmation alert view. These steps will ensure you’re starting out in a clean, test-friendly environment. Return to Xcode and stop the app. Pre-Test Actions In the Project Navigator, expand the solanum project. Right-click the UI Tests folder and click New File… to add your first test case. Select iOS\Cocoa Touch\Objective-C class and click Next. Name the class UITests and make it a subclass of KIFTestCase. Click Next and make sure the files are be added to the UI Tests target, not the solanum target. Finally, click Create on the following screen to save the files. KIFTestCase is a subclass of SenTestCase. That means you have most of the standard OCUnit testing methods and mechanisms available, in case you’re already familiar with unit testing. Open UITests.m and add the following method after the @implementation line: - (void)beforeAll { [tester tapViewWithAccessibilityLabel:@"Settings"]; [tester setOn:YES forSwitchWithAccessibilityLabel:@"Debug Mode"]; [tester tapViewWithAccessibilityLabel:@"Clear History"]; [tester tapViewWithAccessibilityLabel:@"Clear"]; } beforeAll is a special method that is called exactly once, before all of the tests run. You can set up any instance variables or initial conditions for the rest of your tests here. The tester object is a special shortcut to an instance of the KIFUITestActor class. That class includes the methods that will simulate user activity, including tapping and swiping on views. tapViewWithAccessibilityLabel: might be the most common test action method. As the name suggests, it simulates tapping the view with the given accessibility label. In most cases, such as for buttons, the accessibility label matches the visible text label. If not, as you’ll see in the next section, you’ll need to set the accessibility label manually. Some controls, such as UISwitch, are more complicated and need more than just simple taps. KIF provides a specific setOn:forSwitchWithAccessibilityLabel: method to change the state of a switch. In summary, this method has four steps for the test actor: - Tap the “Settings” tab bar button. - Set the “Debug Mode” switch to its “On” state. - Tap the “Clear History” button. - Tap the “Clear” button on the UIAlertView. Do these steps seem familiar? They should be! They’re what you did manually in the previous section! Run the tests by going to Product\Test or hitting Command-U on the keyboard. You should see the app launch; then you’ll see KIF take over, automatically enable debug mode and clear the history. If you have notifications enabled, Xcode will also tell you the test status: Sometimes the test runner, or KIF, can get a little finicky and will refuse to run your tests, in which case you’ll just see a blank simulator screen. If this happens: - Clean the project (Product\Clean) - Build and run - Wait for the app to launch - Stop the app in Xcode This process ensures the Simulator is running and that you’re working with the latest build. After going through the above steps, try running the tests again. The problems should be gone. If you continue to have trouble, check out the KIF troubleshooting steps. Now that you have a pre-test action in beforeAll, it’s time to add your first test! A Simple Test: Tapping Around The app has a standard tab bar controller layout with a UINavigationController inside each of the three tabs. To warm up for the next exercise, you’ll determine if: - The storyboard is wired up properly - The tabs display the correct views. Tab bar buttons automatically set accessibility labels to be the same as their text label, so KIF will be able to find the History, Timer, and Settings tab bar buttons with the labels “History”, “Timer”, and “Settings”. The History tab has a table view that shows all the tasks performed with the timer. Open HistoryViewController.m from the solanum group and add these lines to the end of viewDidLoad: [self.tableView setAccessibilityLabel:@"History List"]; [self.tableView setIsAccessibilityElement:YES]; This will set the table view’s accessibility label, so that KIF can find it. Usually, a table view is only accessible if it’s empty. If there are table view cells they’re a more likely target, so the table view itself will hide from the accessibility API. Essentially, the accessibility API assumes, by default, that the table view isn’t important. This is likely the case in terms of accessibility, but if you want to reference the table view in KIF then it needs to be accessible as well. The setIsAccessibilityElement: call ensures the table view is always accessible, regardless of its contents. Depending on the app, accessible non-empty table views can actually make things more difficult if for users who use the accessibility features (e.g. VoiceOver). In your own apps, you can wrap lines of code between #ifdef DEBUG and #endif directives so they’re only compiled into your debug builds. The DEBUG preprocessor macro is pre-defined in Xcode’s project templates. The Timer tab has several controls you could look for, but the “Task Name” text field is conveniently at the top of the view. Rather than set the label through code, open Main.storyboard and find the Timer View Controller view. Select the task name text field. Open the Utilities panel if it isn’t already up — and select the Identity Inspector. Hint: it’s the third icon from the left, or use the keyboard shortcut ‘⌥ ⌘ 3’. Under Accessibility in the inspector, enter “Task Name” in the Label field. Stay sharp now, because accessibility labels are case-sensitive. Be sure to enter that exactly as shown with a capital T and N! The Settings tab has already been set up the views with accessibility labels, so you’re all set to move to the next step! In your own projects, you’ll need to continue to fill in the accessibility labels from code or in Interface Builder as you’ve done here. For your convenience, the rest of sample app’s accessibility labels are already set. Back in UITests.m, add this method after beforeAll: - (void)test00TabBarButtons { // 1 [tester tapViewWithAccessibilityLabel:@"History"]; [tester waitForViewWithAccessibilityLabel:@"History List"]; // 2 [tester tapViewWithAccessibilityLabel:@"Timer"]; [tester waitForViewWithAccessibilityLabel:@"Task Name"]; // 3 [tester tapViewWithAccessibilityLabel:@"Settings"]; [tester waitForViewWithAccessibilityLabel:@"Debug Mode"]; } The test runner will look for all methods that start with the word “test” at runtime, and then run them in alphabetical order. This method starts with the name “test00” so that it will run before the tests you’ll add later, because those names will start with “test10”, “test20”, etc. Each of the three parts of the method will perform a similar set of actions: tap on a tab bar button, and check for the expected view to show on the screen. 10 seconds is the default timeout for waitForViewWithAccessibilityLabel:. If the view with the specified accessibility label doesn’t show itself during that timeframe, the test will fail. Run the tests by going to Product\Test or hitting Command-U. You’ll see the beforeAll steps which will clear the History, and then test00TabBarButtons will take over and switch to the History, Timer and Settings tabs in sequence. Well, what do you know? You just wrote and ran an interface test, and saw your little app “drive” itself! Congrats! You’re on your way to mastering automated UI testing. User Input Sure, switching tabs is nifty, but it’s time to move on to more realistic actions: entering text, triggering modal dialogs and selecting a table view row. The test app has some built-in presets that will change the work time, break time and number of repetitions to a set of recommended values. If you’re curious to see their definitions, have a look at presetItems in PresetsViewController.m. Selecting a preset could be a test of its own, but that action is more efficient when it is a part of other tests. In this case, it’s worth splitting it out into a helper method. Add the following method to the implementation block of UITests.m: - (void)selectPresetAtIndex:(NSInteger)index { [tester tapViewWithAccessibilityLabel:@"Timer"]; [tester tapViewWithAccessibilityLabel:@"Presets"]; [tester tapRowInTableViewWithAccessibilityLabel:@"Presets List" atIndexPath:[NSIndexPath indexPathForRow:index inSection:0]]; [tester waitForAbsenceOfViewWithAccessibilityLabel:@"Presets List"]; } The first step here is to switch to the Timer tab so that you’re in the right place. Then tap the Presets button in the navigation bar. When the “Presets List” table view appears, tap on the row at the specified index. Tapping on the row will dismiss the view controller, so use waitForAbsenceOfViewWithAccessibilityLabel: to ensure it vanishes before you continue. Did you notice that this method doesn’t start with the word test? The test runner won’t automatically run it. Instead, you’ll manually call the method from within your own tests. Now, add the following test method to UITests.m: - (void)test10PresetTimer { // 1 [tester tapViewWithAccessibilityLabel:@"Timer"]; // 2 [tester enterText:@"Set up a test" intoViewWithAccessibilityLabel:@"Task Name"]; [tester tapViewWithAccessibilityLabel:@"done"]; // 3 [self selectPresetAtIndex:1]; // 4 UISlider *slider = (UISlider *)[tester waitForViewWithAccessibilityLabel:@"Work Time Slider"]; STAssertEqualsWithAccuracy([slider value], 15.0f, 0.1, @"Work time slider was not set!"); } KIF test actions have very readable names; see if you can figure out what’s going on here. Think of it as a…test! Yes, of course the pun is intentional. :] OK, here’s what’s happening section by section: - Switch to the Timer tab. - Enter “Set up a test” into the text field with the “Task Name” accessibility label (remember, you added this label to the storyboard earlier). Tap the “Done” button to close the keyboard. - Call the helper method to select the second preset. - Selecting the preset should change the slider values, so make sure it has indeed changed to the correct value. In the final section of code, you’ll find a handy trick: waitForViewWithAccessibilityLabel:. Not only will it wait for the view to appear, but it actually returns a pointer to the view itself! Here, you cast the return value to UISlider to match up the proper type. Since KIF test cases are also regular OCUnit test cases, you can call the standard STAssert assertion macros. Assertions are run-time checks that cause the test to fail if some condition isn’t met. The simplest assertion is STAssertTrue, which will pass if the parameter passed in is true. STAssertEquals will check that the first two parameters are equal. The slider value is a float, so be careful about matching up types. Thus, the 15.0f appears in the assertion. You also need to be careful about small inaccuracies in floating point representations. This is because floating point values cannot necessarily be stored 100% accurately. 15.0 might end up actually being stored as 15.000000000000001 for example. So STAssertEqualsWithAccuracy is a better choice; its third parameter is the allowed variance. In this case, if the values are within +/- 0.1 of each other, the assertion will still pass. Run the tests using Command-U. You should now see three sequences: beforeAll clears the history, test00TabBarButtons switches through each tab, and then your latest masterpiece in test10PresetTimer will enter a task name and select a preset. Another successful test! At this point, your test mimics users by tapping all kind of things and even typing on the keyboard, but there’s even more to come! Time to Start the Timer Here’s an example timer cycle a user of the app might choose: work for 8 minutes, take a 2 minute break, work for 8 minutes, take a 2 minute break, then work a final 8 minutes. At this point, you take a longer break and then restart the app when you’re ready. The parameters for the above example are: - Work time: 8 minutes - Break time: 2 minutes - Repetitions: 3 The next KIF test will enter these parameters, and then tap the “Start Working” button to start the timer. Add the following method to UITests.m, directly below the previous tests you added: - (void)test20StartTimerAndWaitForFinish { [tester tapViewWithAccessibilityLabel:@"Timer"]; [tester clearTextFromAndThenEnterText:@"Test the timer" intoViewWithAccessibilityLabel:@"Task Name"]; [tester tapViewWithAccessibilityLabel:@"done"]; [tester setValue:1 forSliderWithAccessibilityLabel:@"Work Time Slider"]; [tester setValue:50 forSliderWithAccessibilityLabel:@"Work Time Slider"]; [tester setValue:1 forSliderWithAccessibilityLabel:@"Work Time Slider"]; [tester setValue:8 forSliderWithAccessibilityLabel:@"Work Time Slider"]; [tester setValue:1 forSliderWithAccessibilityLabel:@"Break Time Slider"]; [tester setValue:25 forSliderWithAccessibilityLabel:@"Break Time Slider"]; [tester setValue:2 forSliderWithAccessibilityLabel:@"Break Time Slider"]; } Because this test will run immediately after test10PresetTimer (which sets the task name), you can use the clearTextFromAndThenEnterText:intoViewWithAccessibilityLabel: variant rather than plain old enterText:intoViewWithAccessibilityLabel: to clear out any existing text first. Finally, there are several calls to setValue:forSliderWithAccessibilityLabel:. This is the UISlider specific method to set the new value. Note that the accuracy isn’t always very good. KIF actually simulates the touch event and swipes to set the new value; sometimes the pixel calculations are a little off. But that’s okay, because fingers aren’t all that accurate either! You only need to set each slider’s value once. The multiple calls are just for kicks, and so you can see KIF changing the value over and over. Run the tests using Command-U. The remaining things to test in the UI are the UIStepper control to set the number of repetitions, and the “Start Working” button. The “Start Working” button is easy – you can use tapViewWithAccessibilityLabel: to simulate a tap. But for the UIStepper, we need to take a little detour. Custom Taps The UIStepper control has two halves, as shown below, so at this point it’s unclear what will happen if you just call tapViewWithAccessibilityLabel:. KIF will start out by trying to tap the center of the control. If it’s not a tappable area, it then tries points at the top-left, top-right, bottom-left, and then bottom-right. It turns out that tapping that center border between the plus and minus triggers the plus, so it will increment the stepper. But what if you wanted to decrement the stepper? There are some workarounds, such as digging into the subviews to find the minus button. The other alternative is to use KIF’s tapScreenAtPoint: test action, which will simulate a tap at any arbitrary point on the screen. How’s your CGGeometry knowledge? Can you figure out how to calculate the window coordinates of the plus and minus buttons? Ready to prove you’re awesome? Why not try this challenge? It is totally optional, and you can skip ahead to the code with the calculations below. But if you want to test your skills, try to code the calculations before peeking at the answer. By the way, the answer and full explanation are in the solution box. [Note that you’re going to add this code to the test shortly. This task is just to test your math and CGGeometry skills!] [spoiler title=”UIStepper Geometry”] First, you need a reference to the UIStepper: UIStepper *repsStepper = (UIStepper*)[tester waitForViewWithAccessibilityLabel:@"Reps Stepper"]; Then you can find the center point: CGPoint stepperCenter = [repsStepper.window convertPoint:repsStepper.center fromView:repsStepper.superview]; The UIStepper could be inside any number of nested superviews, and what you really want is the center coordinates of the UIStepper relative to the window as a whole, thus the call to convertPoint:fromView:. Now that you have the center point relative to the window, you can decrease the x-coordinate to get the minus button, or increase it to get the plus button. CGPoint minusButton = stepperCenter; minusButton.x -= CGRectGetWidth(repsStepper.frame) / 4; CGPoint plusButton = stepperCenter; plusButton.x += CGRectGetWidth(repsStepper.frame) / 4; If you increase or decrease by one-fourth the width of the UIStepper, that should land you right in the middle of the plus and minus buttons. Voilà! Two points, representing the center of the plus and minus buttons inside a UIStepper control. [/spoiler] Tapping the screen at an arbitrary point is sort of a last resort, but sometimes it is the only way to test your UI. For example, you might have your own custom controls that don’t implement the UIAccessibility Protocol. Finalizing the Timer OK, so now you’re at the last steps of this Timer test. Are you realizing the awesome potential of UI testing with KIF? Good! The final steps are to set the number of repetitions, and then start the timer. Add the following code to the end of test20StartTimerAndWaitForFinish in UITests.m: // 1 UIStepper *repsStepper = (UIStepper*)[tester waitForViewWithAccessibilityLabel:@"Reps Stepper"]; CGPoint stepperCenter = [repsStepper.window convertPoint:repsStepper.center fromView:repsStepper.superview]; CGPoint minusButton = stepperCenter; minusButton.x -= CGRectGetWidth(repsStepper.frame) / 4; CGPoint plusButton = stepperCenter; plusButton.x += CGRectGetWidth(repsStepper.frame) / 4; // 2 [tester waitForTimeInterval:1]; // 3 for (int i = 0; i < 20; i++) { [tester tapScreenAtPoint:minusButton]; } [tester waitForTimeInterval:1]; [tester tapScreenAtPoint:plusButton]; [tester waitForTimeInterval:1]; [tester tapScreenAtPoint:plusButton]; [tester waitForTimeInterval:1]; // 4 [KIFUITestActor setDefaultTimeout:60]; // 5 [tester tapViewWithAccessibilityLabel:@"Start Working"]; // the timer is ticking away in the modal view... [tester waitForViewWithAccessibilityLabel:@"Start Working"]; // 6 [KIFUITestActor setDefaultTimeout:10]; Here's what's going to happen in this final phase: - The above code finds coordinates for the plus and minus buttons inside the UIStepper. The explanation for this code is contained in the spoiler box above. - The calls to waitForTimeInterval:add a delay so you can see the stepper value change – otherwise it goes by too fast for human eyes. - The stepper has a maximum value of 20, so tap the minus button 20 times to bring the value back to 1. Then, tap the plus button 2 times (interleaved with more small delays) to bring the number of repetitions to 3, the desired value. - The default timeout for a test step is 10 seconds. Even in accelerated debug mode it's possible for the 20+ minutes of "work" to take longer than 10 seconds, so set the timeout to a more generous number, 60 seconds. - Tap the "Start Working" button, which will bring up the modal view controller. When all the repetitions have passed, the modal view controller will be dismissed. That means you'll be back at the Timer view controller, so waiting for the "Start Working" button to appear again is effectively waiting for the modal view controller to go away. - Reset the timeout back to 10 seconds to clean up. Once you save the file, you'll see a little diamond-shaped icon next to the method declaration: This is a button to run a single test. So rather than firing up the entire test suite, you can run this one method in the test environment. Neat! Click on the diamond to run the test; you should see the simulator start up and then see the test run. Sit back and watch as it enters the task name, the sliders move and the timer ticks away. Without lifting a finger, you're testing the UI. Success! Now you can add successfully setting up tests to manipulate a variety of UI controls to your list of accomplishments. If you run a single test with the diamond button, it only runs the single method and doesn't call beforeAll at the beginning. If your test depends on beforeAll, you'll still need to run the full test suite. Ending Early The "Get to Work!" modal view controller has a Give Up button that lets the user cancel the timer cycle. You'll still be able to measure the number of minutes worked, even if you pull the plug on the test early. This data still gets logged in the history, but marked with a flag to indicate the full cycle didn't finish. But you don't have to take my word for it, you can test it for yourself. Just do something very similar to the previous test. Set the timer parameters, tap the Start Working button, and then tap the Give Up button. Don't tap "Give Up" right away – the timer needs to tick for a bit so the app can create the history. So you can either hover over the test and kill it manually, or, you can program it to stop at a time and place of your choosing. If you enjoy hovering, feel free to skip this challenge. However, if you like to program apps to do the dirty work for you, try it out! Do you know how would add a little delay in between "Start Working" and "Give Up"? [spoiler title="Adding a little delay"] You can call your friend waitForTimeInterval: to add a delay in your test. [/spoiler] Add the following test method to UITests.m directly below your other tests: - (void)test30StartTimerAndGiveUp { [tester tapViewWithAccessibilityLabel:@"Timer"]; [tester clearTextFromAndThenEnterText:@"Give Up" intoViewWithAccessibilityLabel:@"Task Name"]; [tester tapViewWithAccessibilityLabel:@"done"]; [self selectPresetAtIndex:2]; [tester tapViewWithAccessibilityLabel:@"Start Working"]; [tester waitForTimeInterval:3]; [tester tapViewWithAccessibilityLabel:@"Give Up"]; [[tester usingTimeout:1] waitForViewWithAccessibilityLabel:@"Start Working"]; } After making sure you're on the right tab, set the task name and select a preset. Then, start the timer and wait 3 seconds before giving up. The final line of the method waits for the modal view controller to go away and for the main interface to return. Remember, the default timeout is 10 seconds, but it really shouldn't take that long – tapping the "Give Up" button should dismiss the modal view controller immediately. In the previous test, you used the class method setDefaultTimeout: to set the timeout value globally for all test actions. Here, you're calling usingTimeout: to set a custom timeout for just this single step. Save the file and click on the test's diamond icon to run only this test. When the timer starts, you'll see it tick for three seconds before it gives up and returns to the main screen. History and Swiping The History tab has not received much attention yet, but its time in the limelight is now. If you've worked through the exercises, you should have at least one entry in the history. Build and run the app, and switch to the History tab. The History table view implements the new iOS 7 delete gesture -- the one where you swipe the row to the left, and then tap on the "Delete" button that appears. There's your next test! This requires at least one item in the History, so you need to be careful about running this one test individually. You need to ensure there is something in the history, otherwise there would be nothing to test! To be safe, you'll run the entire test suite, since the earlier tests will create some history items for you to play around with. Remember the tests will run in alphabetical order. So you can be assured that the previous tests will create something to test the history screen with. If you take a peek at tableView:cellForRowAtIndexPath: in HistoryViewController.m, you'll see that each cell gets an accessibility label such as "Section 0 Row 3". This just helps KIF find the row. It is a poor label for real-world accessibility, so don't use this in a real app. In this sample project, this has been #ifdef'd to debug builds only. You should do similar if you use this technique in your own apps. Be sure in release builds to set the accessibility label to something useful for users of accessibility features. Now, open UITests.m and add the following test method: - (void)test40SwipeToDeleteHistoryItem { // 1 [tester tapViewWithAccessibilityLabel:@"History"]; // 2 UITableView *tableView = (UITableView *)[tester waitForViewWithAccessibilityLabel:@"History List"]; NSInteger originalHistoryCount = [tableView numberOfRowsInSection:0]; STAssertTrue(originalHistoryCount > 0, @"There should be at least 1 history item!"); // 3 [tester swipeViewWithAccessibilityLabel:@"Section 0 Row 0" inDirection:KIFSwipeDirectionLeft]; [tester tapViewWithAccessibilityLabel:@"Delete"]; // 4 [tester waitForTimeInterval:1]; NSInteger currentHistoryCount = [tableView numberOfRowsInSection:0]; STAssertTrue(currentHistoryCount == originalHistoryCount - 1, @"The history item was not deleted :["); } Here's what's going on in the above method: - Switch to the History tab. - Get a reference to the table view and keep track of how many rows are present. The test will fail if there isn't at least one row. - Swipe the table view cell to the left. When the Delete button appears, tap it. - The table view performs an animation when it deletes a cell, so add a short delay before continuing. Check the number of rows in the table view again; there should be one less row than before. Run the entire test suite using Command-U to see everything run in sequence. Swipe to delete Your tests now cover the basic flow of the app – from resetting data to running the timer a few times, to verifying and deleting history. If you were to continue developing the app, these tests would be a good baseline to ensure there are no regressions in the interface. That means you also need to update the tests every time the interface changes – tests are like specifications for your app and they need to stay up-to-date to be useful. Where To Go From Here? By now, you should have a good sense of the possibilities of KIF and your mind should be racing with ideas about how to utilize this highly functional testing for your own apps. To get started with adding KIF to your project, check out the documentation. You can add KIF manually or use the very convenient CocoaPods dependency manager. What's cool about KIF is that it is an open-source project and new features are constantly in development. For example, at the time of writing this tutorial, the next release will likely include a feature to take a screenshot of your app programmatically and save it to disk. This means you should be able to run the tests and review key points in the process by reviewing screenshots at your leisure. Doesn't that sound a million times better than hovering and watching KIF tap and swipe its way through your app? KIF just keeps getting better and better, so learning how to use it is a wise investment in yourself. Finally, since KIF test cases are subclasses of OCUnit and run within the standard Xcode 5 test framework, you can run the tests through your continuous integration process. Then you can truly have bots with quasi-touch fingers testing your app while you do other things! Woo-hoo! You can download the final project archive here. If you have any questions or comments, please join the forum discussion below. Happy testing!
https://www.raywenderlich.com/2512-ios-ui-testing-with-kif
CC-MAIN-2021-04
refinedweb
4,929
54.93
I have a degree in mathematics and computer science, but still I don't know why different programming languages evaluate Integer/Integer differently. On any calculator if you divide one integer with another you get a decimal number (of course not if the numerator is a factor of the denominator). Python for example returns a integer number: >>> print 3/10 0 >>> print 3/10.0 0.3 Perl on the other hand returns a decimal number: print 3/10; print "\n"; print 3/10.0; ...gives... 0.3 0.3 PostgreSQL is like Python: database=# SELECT 3/10 AS quotient1, 3/10.0 As quotient2; quotient1 | quotient2 -----------+------------------------ 0 | 0.30000000000000000000 And good old MS Excel gives: =3/10 <=> 0.3 Why is it so? Follow @peterbe on Twitter For Python, the reasons are historical. When it was designed, mathematics and arithmetic were not exactly the focus of attention, and Guido decided to follow how things were done in C when he didn't particularly care one way or the other. That is why division in Python works as in C. In C, the choice is a more natural one, since it was designed to be a low-level language focused on efficiency. In the early days, this efficiency was achieved largely by providing a close mapping between hardware functionality and language functionality. This meant that you could get good efficiency even with a simple compiler, by leveraging the programmer's intuitions and experience regarding hardware efficiency (with integer arithmetic being much more efficient than floating-point, provided that the latter was supported at all.) Following this principle, the compiler should not automatically slow down things without very good reasons, while automatically moving from fast integers to slow floating-point arithmetic could easily be seen as violating that principle. Also, integer division is sufficient in many cases, especially when used for data organization (subdivision of datasets) rather than mathematics. The creators of C were working on operating systems, compilers, and other kinds of system software were this was true to a large extent. Floating-point arithmetic was included in the language, but in later practice it was often made optional, if at all (especially on small micros and embedded systems.) For a high-level language focused on ease-of-use for the programmer, automatic conversion between integer and floating-point "where required" makes a lot of sense. So it is not strange that the other languages you mention work that way. Python is going in that direction as well (see e.g.) Hello Rickard, This is a great piece of information. I very much liked the way you have explained it. Thanks for answering a question which was very intriguing for me. Regards, Vishruth Well, there is "real division" and "integer division". They are different. Calculators do real division. They take a real number, divides it by another real number and return a real number. In number theory we only work with integers. So we have the integer division. When you divide two numbers, you have the quotient and the remainder. 10 div 3 = 3 (quotient) 10 mod 3 = 1 (remainder) 3 * 3 + 1 = 10 The definition of integer division is: given two numbers a and b, the quotient and remainder or the division of a and b are defined by the formulas: b*q+r=a and 0<=r<b (or 0<=|r|<|b| if dealing with negative numbers) Perl (as far as I know) does not have a integer division (quotient) operator, but it has a remainder operator. C, Pascal and Python have both operations. But they behave diffent when dealing with negative numbers. In the definition above, there are two possible values of r, one negative and one positive. In math we always take the positive one, but the languages sometimes take the negative. C and Pascal (gcc and freepascal to be more specific) truncate the division and then calculate the remainder. Python and Perl, on the other hand, use the floor function instead of truncating. This causes differences in the quotient and remainder when dealing with negative integer division. For example, dividing 3 by (-2): a = 3, b = -2 b*q+r=a (-2) * q + r = 3 0<=|r|<2 Two possible solutions: q=-2 r=-1 (-2) * (-2) + (-1) = 3 or q=-1 r=1 (-2) * (-1) + (1) = 3 Both are correct. In this case, Perl and Python choose the first one (negative remainder) but Pascal and C choose the second one (positive remainder). On the other hand, if you make a=-3 and b=2, Perl and Python choose the positive r, Pascal and C choose the negative r. Problem dividing variable of integers numbers in Python, for percentage. Solution: product between one variable by 0,1 : print(... ), SOLA/SOLB * 100 #being SOLA < SOLB Result: 0 # Solution print(... ), int(SOLA/(SOLB*1.0) *100, ("%") There are more than just 2 division operators: there's floor, ceil, real and and floating point. Floor and ceil division are both integer valued and differ only for negative results. Unsurprisingly, floor division is equivalent to real division rounded down and ceil to real division rounded up. As Rickard says, which division operator(s) a language supports depends on the language's purpose. These days (from version 2.2), Python supports both floor division & floating point division with the '//' and '/' operators, respectively. In python 2.X, you have to import the division feature from __future__ to get this behavior. from __future__ import division # prints '0.5 0' print 1/2, 1//2 In Python integer division why does -7/10 == -1 and not 0? That's a really good question. I honestly don't know the answer. If you do -7/float(10) what's the answer? That's very different. That's -7/10.0 which is something else. For beauty and symmetry. Observe: >>> [n/10 for n in range(-30, 30)] [-3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] The operation n/10 results, over the integers, in runs of exactly 10 identical results, followed by the next integer. If -7/10 had the terrible result of 0, then the above sequence would have 20 zeros in a row instead of 10, making that single number an anomaly in what is otherwise a perfectly symmetrical sequence. That's nice but a strangely beautiful and weird explanation. In general, when an integer n is divided by an integer d to obtain an integer quotient q and an integer remainder r, the numbers are related as follows: n = dq + r. Python requires the integer remainder of an integer division by a positive integer to be positive, which agrees with the mathematical definition of modulus in number theory. When -7 is divided by 10, the only way to achieve this is for the remainder to be 3 and the quotient to be -1 because -7 = (10)(-1) + 3. Thank you! Two integers from "Big Date" produce a rational quotient, but not immediately obvious: 11,427,680,865,484,800/948,109,639,680 where the denominator is the famous Jarvis No. (see:). The answer is 12,053.1216931. Fortran has a remainder out to 12 digits. My 1st thought was the ans. might be irrational (transcendental. that is), but my ancient, 21-year old HP 48GX calculator gave the correct result, confirming rationality. Also, I did find one correct web calculator, but most don't come close. There is a greatest common divisor, namely 5,016,453,120, which reduces the fraction to much lower terms: 2,278,040/189 = 12,053.1216931. Best regards, Bearcat Please allow me to clarify what I had to say in my post earlier this morning. In their Mathematics Dictionary, under “IRRATIONAL”, James & James say: “irrational number. A real number not expressible as an integer or quotient of integers; a nonrational number.” I’m sure I learned that somewhere in the past, but when I saw all of Fortran’s spurious digits following the decimal point I got carried away, forgot the fundamentals, and tended to think Fortran was correct. I hope you many programmers, in whatever language, who have had that experience, will give me a nanograin of sympathy for having expressed my earlier post so poorly. Of course I learned (mainly through trial and error) that my real quotient was required to terminate by virtue of its very existence as a "quotient of integers". However, I must confess, I failed to see that initially. Sorry about that. Incidentally, I would be interested to see how other languages, like Python, Perl, etc., would handle this "Big Data" fraction. Regards, Bearcat OK, I give up! I finally decided to work that big fraction out by hand (which I should have done in the 1st place ,instead of trying to subject it to some sort of crazy rationality!). The answer appears to be 12,053. [121693][121693][121693]...... with the 6-digit sequence [121693] going on forever (repeating indefinitely). Again I say: "sorry about that!" Regards, Bearcat Hi everyine I am trying to create a pic slideshoe in html5 with javascript. I thought that If I use the modulus and classes form number theory I can create a loop that automaticaly rotates the pics. Something like that. I have an array of 6 pics for example x = [0 1 2 3 ...6] and a counter i=0; then i++ etc. If the counter goes i = 8 then I want the function to understand that I want to display the pic from the class of 1. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14.... can be done with javascript? in c language the division of -3/2 is -2 but compiler is giving -1 why? Prior to the 1999 version of C, the result of division was considered compiler-dependent. This left the option to the compiler vendor to decide whether its customers would prefer fast division or consistent division. Division by a compile-time-known value of 2 could be done with an arithmetic right shift of one bit. On a 2s-complement machine, this would correspond to floor behavior; on a 1s complement machine it would correspond to truncation toward 0. Such a bit shift was much faster than actual division. If the divisor was not known to be 2 at compile time, the compiler would generate code to perform an actual division; if the divisor happened to be 2 for a particular division, the result would be truncated to 0. Thus, on a 2s-complement machine, one compiler would be allowed for dividing −7 by 2 to return −4 in some cases and −3 in other cases within one program. Starting with 1999, C required compilers to perform integer division as truncation toward 0 in order to achieve more predictable behavior. Another issue is that if one writes code with −7/2, it is treated as −(7/2) which would nearly always be evaluated as −3 regardless of compiler and hardware behavior. That is because in C, − is always a unary operator; there is no such thing as negative integer literals in C. People often forget this detail and are surprised. ahhhhh.............19 yrs old good old days
https://www.peterbe.com/plog/blogitem-040804-1
CC-MAIN-2021-17
refinedweb
1,923
63.39
Visual C++ 2005 comes with a bunch of helper classes that provide support for smart pointers, synchronization support, and COM wrappers. Most of them are very handy for interop scenarios, and this article will show examples on using these classes. auto_handleclass. void Demo1A() { StreamWriter^ sw; try { sw = File::CreateText("d:\\temp.txt"); sw->WriteLine("This is a line of text"); } finally { delete sw; } } This is where the auto_handle class comes in handy. Add the following #include declaration to your code. #include <msclr\auto_handle.h> Now, you can rewrite the previous method as follows. void Demo1B() { msclr::auto_handle<StreamWriter> sw = File::CreateText("d:\\temp.txt"); sw->WriteLine("This is a line of text"); }. sw.release(); Other operator overloads include those on =, !, and bool, so you can treat it like a pointer. And there's also a swap helper function that swaps handles between two auto_handle objects. gcrootand auto_gcrootclasses. class Demo2A { msclr::gcroot<StreamWriter^> m_sw; public: Demo2A() { m_sw = File::CreateText("d:\\temp.txt"); } ~Demo2A() { delete m_sw; } }; Notice how, I had to manually delete the StreamWriter object in the destructor. Using the auto_gcroot class, we can actually avoid having to do that on our own. Here's a modified class that uses auto_gcroot. class Demo2B { msclr::auto_gcroot<StreamWriter^> m_sw; public: Demo2B() { m_sw = File::CreateText("d:\\temp.txt"); } }; Well, now the destructor is gone. For most purposes, you should use the auto_gcroot class instead of the gcroot class, for obvious reasons. Remember to #include <msclr\gcroot.h> or <msclr\auto_gcroot.h> appropriately. _safe_boolclass _safe_bool is a value class that can be used in place of bool when providing an operator overload for bool. It prevents an implicit conversion to any integral type. Consider the following class. ref class Demo3A { public: operator bool() { return true; } }; Now the following code would compile fine, even when it may not have been intended to do so. Demo3A a; int y = a; Here's how you would rewrite the class using a _safe_bool. ref class Demo3B { public: operator msclr::_detail_class::_safe_bool() { return msclr::_detail_class::_safe_true; } }; Now the following code will not compile. Demo3B a; int y = a; You can also treat it like a bool, for most purposes. if(a == msclr::_detail_class::_safe_false) { } Both auto_handle and auto_gcroot use _safe_bool for their bool operator overloads. You need to #include <msclr\safebool.h> to use this class. ptrtemplate - a COM wrapper class This class is quite handy when you need to use a COM object as a member of a CLI class. The following #include is needed for this class. #include <msclr\com\ptr.h> The below code sample shows how to use the class. ref class ManLink { private: msclr::com::ptr<ILink> lnkptr; public: ManLink() { lnkptr.CreateInstance(__uuidof(Link)); // Create COM object } void Resolve() { lnkptr->ResolveLink(. . .); // Invoke COM method } };. lockclass. #include <msclr\lock.h> Now, here's a sample showing how the lock class can be used. ref class Demo4 { public: void DoSafeStuff() { msclr::lock lk(this); Console::WriteLine("Starting work on thread {0}", Thread::CurrentThread->ManagedThreadId); Thread::Sleep(300); // simulate complex task Console::WriteLine("Work ended on thread {0}", Thread::CurrentThread->ManagedThreadId); } };. int main(array<System::String ^> ^args) { Demo4 d; msclr::lock lk(%d,msclr::lock_later); // defers locking for(int i=0; i<5; i++,( gcnew Thread( gcnew ThreadStart(%d, &Demo4::DoSafeStuff)))->Start()); while(!lk.try_acquire(300)); Console::WriteLine("Exiting main"); return 0; }). class Demo5 { msclr::auto_gcroot<FileSystemWatcher^> m_fsw; public: // Step (1) // Declare the delegate map where you map // native method to specific event handlers BEGIN_DELEGATE_MAP(Demo5) EVENT_DELEGATE_ENTRY(OnRenamed, Object^, RenamedEventArgs^) END_DELEGATE_MAP() Demo5() { m_fsw = gcnew FileSystemWatcher("d:\\tmp"); // Step (2) // Setup event handlers using MAKE_DELEGATE m_fsw->Renamed += MAKE_DELEGATE(RenamedEventHandler, OnRenamed); m_fsw->EnableRaisingEvents = true; } // Step (3) // Implement the event handler method void OnRenamed(Object^, RenamedEventArgs^ e) { Console::WriteLine("{0} -> {1}",e->OldName, e->Name); } }; Essentially, these support library classes, make up for missing syntactic support in C++/CLI. Why add compiler overhead, when library implementations are trivial and equally effective? As usual, feedback (both critical and otherwise) is welcome. General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/mcpp/CppCliSupportLib.aspx
crawl-002
refinedweb
666
50.02
This is the criteria i am required to get my program to do. I have looked on google for help but I can't find any. Enhance / modify the program you created in the previous assignment. Create a class ScanArray. This class should have two methods FindMax and FindMin. Class ScanArray should have a constructor. Program processing should parallel these steps : main prompts the user for the grades of MidTerm1 and stores the data in an array. main prompts the user for the grades of MidTerm2 and stores the data in an array. main prompts the user for the grades of FinalExam and stores the data in an array. main adds the grades of the 3 tests and stores the totals in an array. main calls the constructor of ScanArray passing the array of totals to the constructor. main calls the FindMin method; not passing anything to it. FindMin will return to main the minimum value found in the total of the grades. main calls the FindMax method; not passing anything to it. FindMax will return to main the maximum value found in the total of the grades. main informs the Business User of the minimum grade and maximum grade. This is my code from the project which i need to modify. As you can tell I am not very good at java. I can do this in C++ but don't understand why i can't do this in java. Any help and or code samples are much appreciated. package assign6_sb; import java.util.Scanner; public class Assign6_SB { public static void main(String[] args) { //arrays Scanner SC = new Scanner(System.in); int[] midterm1 = new int[10]; int[] midterm2 = new int[10]; int[] fExam = new int[10]; int[] total = new int[10]; //collections int m1Collect; int m2Collect; int fexCollect; //counter for student int counter1 = 1; int counter2 = 1; int counter3 = 1; //fill midterm1 for(int index = 0; index < midterm1.length; index++) { System.out.println("Enter the grades for midterm 1: Student: "+counter1); m1Collect = SC.nextInt(); counter1++; midterm1[index] = m1Collect; } //fill midterm2 for(int index = 0; index < midterm2.length; index++) { System.out.println("Enter the grades for midterm 2: Student: "+counter2); m2Collect = SC.nextInt(); counter2++; midterm2[index]=m2Collect; } //fill fExam for(int index = 0; index < fExam.length; index++) { System.out.println("Enter the grades for the final exam: Student: "+counter3); fexCollect = SC.nextInt(); counter3++; fExam[index]=fexCollect; } //fill the total with the summed values for (int index = 0; index < total.length; index++) { total[index] = (midterm1[index] + midterm2[index] + fExam[index]); } //fill the min and max with the first index int max = total[0]; int min = total[0]; //find the min and max for (int index = 0; index < total.length; index++) { if(total[index] > max) max = total[index]; if(total[index] < min) min = total[index]; } System.out.println("The maximum grade is " + max); System.out.println("The minimum grade is " + min); } }
https://www.daniweb.com/programming/software-development/threads/419188/java-class-help
CC-MAIN-2017-09
refinedweb
479
59.5
VCard Converter 3.1.38 Sponsored Links VCard Converter 3.1.38 Ranking & Summary RankingClick at the star to rank Ranking Level User Review: 0 (0 times) File size: 3.2 MB Platform: Windows Vista, 2003, XP, 2000, 98, Me, NT License: Shareware Price: $24.95 Downloads: 341 Date added: 2008-11-19 Publisher: VCard Converter 3.1.38 description New! Imports multiple contacts contained in a single .vcf file New! Directly import contacts to any Outlook folder, not just your default Contacts folder New! Optionally merge existing contacts with those being imported New! Exports multiple contacts to a single .vcf file or individual vcf files New! Support for underlying technology means faster imports and exports than previous versions Works with Microsoft Outlook 2007, Outlook 2003, Outlook 2002, and Outlook 2000 Handy toolbar button for frequent exporting - just highlight the contacts and click the button Choose any contact folder to import/export, including those on an Exchange public folder Note: This software is buy before download. VCard Converter 3.1.38 Screenshot Advertisements VCard Converter 3.1.38 Keywords VCard VCard Converter 3.1.38 Outlook Add vcard converter vcard format One click easily convert convert all email contacts outlook format multiple converter email security email Exchange Bookmark VCard Converter 3.1.38 VCard Converter 3.1.38 Copyright WareSeeker periodically updates pricing and software information of VCard Converter 3.1.38 full version from the publisher, so some information may be slightly out-of-date. You should confirm all information before relying on it. Software piracy is theft, Using crack, password, serial numbers, registration codes, key generators is illegal and prevent future development of VCard Converter 3.1 multiple sclerosis multiple intelligences outlook web access outlook add ons multiple myeloma email search multiple listing service multiplex multiple sclerosis symptoms multiple personality disorder outlook address book email address converter mp3 vcards Related Software vCard ImportExport - Import and export vCard files to/from your Microsoft Outlook. Free Download Convert (import-export) Outlook Expres Contacts from/to Vcard format.. Free Download Export Outlook Contacts PST file to vCard VCF file using vCard file converter tool. Convert MS Outlook Contacts to Windows Address Book WAB file & MS Excel. Software successfully converts outlook cont. Free Download vcard converter for outlook express. Free Download import & export vcard files. Free Download vCard Converter to export PST contacts to VCF. Free Download Useful vCard converter to any document format. Free Download Useful tool that converts your VCF (vCard) files to many document formats (PDF, MS Word, HTML, RTF, TXT). All you have to do is select the contacts to convert, choose the desired format and click a bu. Free Download Useful tool that converts your VCF (vCard) files to many document formats (PDF, MS Word, HTML, RTF, TXT). All you have to do is select the contacts to convert, choose the desired format and click a bu. Free Download Top Popular Software Editor's Picks Software
http://wareseeker.com/Email-Tools/vcard-converter-3.1.38.zip/418311
crawl-002
refinedweb
489
50.02
My session beans call other bean methods within a transaction. Using bean-managed transactions, how should I take care of commit and rollback ? Created May 4, 2012 Siva Visveswaran There are two steps here: 1. Coding step: public class exBean implements SessionBean { EJBContext ec; javax.transaction.UserTransaction utxn; . . . utxn = ec.getUserTransaction(); utxn.begin(); // do all your txn stuff // getting DB connections, updates, other bean methods, etc. . . utxn.commit(); } Note you have to begin a txn before opening dB connections and close connections before committing. 2. Deployment step: - Your app server must support a JTS for distributed txns. Most do. - Verify there is no conflict with the bean transaction properties in calling beans.
https://www.jguru.com/faq/view.jsp?EID=62121
CC-MAIN-2021-04
refinedweb
112
57.98
Section 3.3 The while and do..while Statements STATEMENTS IN JAVA CAN BE either simple statements or compound statements. Simple statements, such as assignments statements and subroutine call statements, are the basic building blocks of a program. Compound statements, such as while loops and if statements, are used to organize simple statements into complex structures, which are called control structures because they control the order in which the statements are executed. The next four sections explore the details of all the control structures that are available in Java, starting with the while statement and the do..while statement in this section. At the same time, we'll look at examples of programming with each control structure and apply the techniques for designing algorithms that were introduced in the previous section. The while Statement The while statement was already introduced in Section 1. A while loop has the formwhile ( boolean-expression ) statement The statement can, of course, be a block statement consisting of several statements grouped together between a pair of braces. This statement is called the body of the loop. The body of the loop is repeated as long as the boolean-expression is true. This boolean expression is called the continuation condition, or more simply the test, of the loop. There are a few points that might need some clarification. What happens if the condition is false in the first place, before the body of the loop is executed even once? In that case, the body of the loop is never executed at all. The body of a while loop can be executed any number of times, including zero. What happens if the condition is true, but it becomes false somewhere in the middle of the loop body? Does the loop end as soon as this happens? It does not, because the computer continues executing the body of the loop until it gets to the end. Only then does it jump back to the beginning of the loop and test the condition, and only then can the loop end. Let's look at a typical problem that can be solved using a while loop: finding the average of a set of positive integers entered by the user. The average is the sum of the integers, divided by the number of integers. The program will ask the user to enter one integer at a time. It will keep count of the number of integers entered, and it will keep a running total of all the numbers it has read so far. Here is a pseudocode algorithm for the program:Let sum = 0 Let count = 0 while there are more integers to process: Read an integer Add it to the sum Count it Divide sum by count to get the average Print out the average But how can we test whether there are more integers to process? A typical solution is to tell the user to type in zero after all the data have been entered. This will work because we are assuming that all the data are positive numbers, so zero is not a legal data value. The zero is not itself part of the data to be averaged. It's just there to mark the end of the real data. A data value used in this way is sometimes called a sentinel value. So now the test in the while loop becomes "while the input integer is not zero". But there is another problem! The first time the test is evaluated, before the body of the loop has ever been executed, no integer has yet been read. There is no "input integer" yet, so testing whether the input integer is zero doesn't make sense. So, we have to do something before the while loop to make sure that the test makes sense. Setting things up so that the test in a while loop makes sense the first time it is executed is called priming the loop. In this case, we can simply read the first integer before the beginning of the loop. Here is a revised algorithm:Let sum = 0 Let count = 0 Read an integer while the integer is not zero: Add the integer to the sum Count it Read an integer Divide sum by count to get the average Print out the average Notice that I've rearranged the body of the loop. Since an integer is read before the loop, the loop has to begin by processing that integer. At the end of the loop, the computer reads a new integer. The computer then jumps back to the beginning of the loop and tests the integer that it has just read. Note that when the computer finally reads the sentinel value, the loop ends before the sentinel value is processed. It is not added to the sum, and it is not counted. This is the way it's supposed to work. The sentinel is not part of the data. The original algorithm, even if it could have been made to work without priming, was incorrect since it would have summed and counted all the integers, including the sentinel. (Since the sentinel is zero, the sum would still be correct, but the count would be off by one. Such so-called off-by-one errors are very common. Counting turns out to be harder than it looks!) We can easily turn the algorithm into a complete program. Note that the program cannot use the statement "average = sum/count;" to compute the average. Since sum and count are both variables of type int, the value of sum/count is an integer. The average should be a real number. We've seen this problem before: we have to convert one of the int values to a double to force the computer to compute the quotient as a real number. This can be done by type-casting one of the variables to type double. The type cast "(double)sum" converts the value of sum to a real number, so in the program the average is computed as "average = ((double)sum) / count;". Another solution in this case would have been to declare sum to be a variable of type double in the first place. One other issue is addressed by the program: If the user enters zero as the first input value, there are no data to process. We can test for this case by checking whether count is still equal to zero after the while loop. This might seem like a minor point, but a careful programmer should cover all the bases. Here is the program and an applet that simulates it:public class ComputeAverage { /* This program reads a sequence of positive integers input by the user, and it will print out the average of those integers. The user is prompted to enter one integer at a time. The user must enter a 0 to mark the end of the data. (The zero is not counted as part of the data to be averaged.) The program does not check whether the user's input is positive, so it will actually work for both positive and negative input values. */ public static void main(String[] args) { int inputNumber; // One of the integers input by the user. int sum; // The sum of the positive integers. int count; // The number of positive integers. double average; // The average of the positive integers. /* Initialize the summation and counting variables. */ sum = 0; count = 0; /* Read and process the user's input. */ TextIO.put("Enter your first positive integer: "); inputNumber = TextIO.getlnInt(); while (inputNumber != 0) { sum += inputNumber; // Add inputNumber to running sum. count++; // Count the input by adding 1 to count. TextIO.put("Enter your next positive integer, or 0 to end: "); inputNumber = TextIO.getlnInt(); } /* Display the result. */ if (count == 0) { TextIO.putln("You didn't enter any data!"); } else { average = ((double)sum) / count; TextIO.putln(); TextIO.putln("You entered " + count + " positive integers."); TextIO.putln("Their average is " + average + "."); } } // end main() } // end class ComputeAverage The do..while Statement Sometimes it is more convenient to test the continuation condition at the end of a loop, instead of at the beginning, as is done in the while loop. The do..while statement is very similar to the while statement, except that the word "while," along with the condition that it tests, has been moved to the end. The word "do" is added to mark the beginning of the loop. A do..while statement has the formdo statement while ( boolean-expression ); or, since, as usual, the statement can be a block,do { statements } while ( boolean-expression ); Note the semicolon, ';', at the end. This semicolon is part of the statement, just as the semicolon at the end of an assignment statement or declaration is part of the statement. Omitting it is a syntax error. (More generally, every statement in Java ends either with a semicolon or a right brace, '}'.) To execute a do loop, the computer first executes the body of the loop -- that is, the statement or statements inside the loop -- and then it evaluates the boolean expression. If the value of the expression is true, the computer returns to the beginning of the do loop and repeats the process; if the value is false, it ends the loop and continues with the next part of the program. Since the condition is not tested until the end of the loop, the body of a do loop is executed at least once. For example, consider the following pseudocode for a game-playing program. The do loop makes sense here instead of a while loop because with the do loop, you know there will be at least one game. Also, the test that is used at the end of the loop wouldn't even make sense at the beginning:do { Play a Game Ask user if he wants to play another game Read the user's response } while ( the user's response is yes ); Let's convert this into proper Java code. Since I don't want to talk about game playing at the moment, let's say that we have a class named Checkers, and that the Checkers class contains a static member subroutine named playGame() that plays one game of checkers against the user. Then, the pseudocode "Play a game" can be expressed as the subroutine call statement "Checkers.playGame();". We need a variable to store the user's response. The TextIO class makes it convenient to use a boolean variable to store the answer to a yes/no question. The input function TextIO.getlnBoolean() allows the user to enter the value as "yes" or "no". "Yes" is considered to be true, and "no" is considered to be false. So, the algorithm can be coded asboolean wantsToContinue; // True if user wants to play again. do { Checkers.playGame(); TextIO.put("Do you want to play again? "); wantsToContinue = TextIO.getlnBoolean(); } while (wantsToContinue == true); When the value of the boolean variable is set to true, it is a signal that the loop should end. When a boolean variable is used in this way -- as a signal that is set in one part of the program and tested in another part -- it is sometimes called a flag or flag variable (in the sense of a signal flag). By the way, a more-than-usually-pedantic programmer would sneer at the test "while (wantsToContinue == true)". This test is exactly equivalent to "while (wantsToContinue)". Testing whether "wantsToContinue == true" is true amounts to the same thing as testing whether "wantsToContinue" is true. A little less offensive is an expression of the form "flag == false", where flag is a boolean variable. The value of "flag == false" is exactly the same as the value of "!flag", where ! is the boolean negation operator. So you can write "while (!flag)" instead of "while (flag == false)", and you can write "if (!flag)" instead of "if (flag == false)". Although a do..while statement is sometimes more convenient than a while statement, having two kinds of loops does not make the language more powerful. Any problem that can be solved using do..while loops can also be solved using only while statements, and vice versa. In fact, if doSomething represents any block of program code, thendo { doSomething } while ( boolean-expression ); has exactly the same effect asdoSomething while ( boolean-expression ) { doSomething } Similarly,while ( boolean-expression ) { doSomething } can be replaced byif ( boolean-expression ) { do { doSomething } while ( boolean-expression ); } without changing the meaning of the program in any way. The break and continue Statements The syntax of the while and do..while loops allows you to test the continuation condition at either the beginning of a loop or at the end. Sometimes, it is more natural to have the test in the middle of the loop, or to have several tests at different places in the same loop. Java provides a general method for breaking out of the middle of any loop. It's called the break statement, which takes the form break; When the computer executes a break statement in a loop, it will immediately jump out of the loop. It then continues on to whatever follows the loop in the program. Consider for example:while (true) { // looks like it will run forever! TextIO.put("Enter a positive number: "); N = TextIO.getlnlnt(); if (N > 0) // input is OK; jump out of loop break; TextIO.putln("Your answer must be > 0."); } // continue here after break If the number entered by the user is greater than zero, the break statement will be executed and the computer will jump out of the loop. Otherwise, the computer will print out "Your answer must be > 0." and will jump back to the start of the loop to read another input value. (The first line of the loop, "while (true)" might look a bit strange, but it's perfectly legitimate. The condition in a while loop can be any boolean-valued expression. The computer evaluates this expression and checks whether the value is true or false. The boolean literal "true" is just a boolean expression that always evaluates to true. So "while (true)" can be used to write an infinite loop, or one that can be terminated only by a break statement.) A break statement terminates the loop that immediately encloses the break statement. It is possible to have nested loops, where one loop statement is contained inside another. If you use a break statement inside a nested loop, it will only break out of that loop, not out of the loop that contains the nested loop. There is something called a "labeled break" statement that allows you to specify which loop you want to break. I won't give the details here; you can look them up if you ever need them. The continue statement is related to break, but less commonly used. A continue statement tells the computer to skip the rest of the current iteration of the loop. However, instead of jumping out of the loop altogether, it jumps back to the beginning of the loop and continues with the next iteration (after evaluating the loop's continuation condition to see whether any further iterations are required). break and continue can be used in while loops and do..while loops. They can also be used in for loops, which are covered in the next section. In Section 6, we'll see that break can also be used to break out of a switch statement. Note that when a break occurs inside an if statement, it breaks out of the loop or switch statement that contains the if statement. If the if statement is not contained inside a loop or switch, then the if statement cannot legally contain a break statement. A similar consideration applies to continue statements. [ Next Section | Previous Section | Chapter Index | Main Index ]
http://www.faqs.org/docs/javap/c3/s3.html
CC-MAIN-2016-50
refinedweb
2,627
71.65
Halloween is great for makers and engineers. It's a chance to make something fun and show it off - usually with a lot of blinky LEDs. This Halloween, I decided to redo my costume from a few years ago: a traffic light! This is a fun and simple costume that everyone recognizes off-the-bat. My costume is not just a traffic light. It can be controlled 'manually', has a 'disco' mode with several speeds, and has adjustable brightness. Recreating this costume can be very easy. For this project, you'll need: - (2) gold tshirts Here - access to a 3D printer. Alternatively, you can make the parts with cardboard, paint, and other things easily found about the house - red, yellow and green LEDs. Alternatively, addressable LED strips could be used. I got my LEDs from here - an Arduino, or other microcontroller. Included in this Instructable are design files for a PCB for this project. It uses a ATMega328P, as found on the Arduino UNO. The Arduino Micro, Nano, Pro Mini, or basically any Arduino with 8 GPIO (at least 3 PWM, and 1 analog) should work. Of course, non Arduino microcontrollers will also work. NOTE: should be a 5V microcontroller - some buttons, and a potentiometer - some capacitors, resistors, and connectors (if using my designed PCB) - sewing needle and gold thread - glue - wire - perfboard (optional) - soldering iron and solder (optional) Step 1: Electronics The electronics controlling the traffic light costume are not that complicated. They consist of a microcontroller, a crystal oscillator, three MOSFETs, a potentiometer, some buttons, and various resistors and capacitors - all of which can be had in through-hole or SMD packages, and assembled on perfboard, or on a custom made PCB. Microcontroller My design uses an ATMega328P - the same microcontroller found on the Arduino UNO. However, there are literally thousands of microcontrollers that will work for this project. The ATMega328P comes in both SMD QFP package, and through-hole DIP package, so it's easy to use on perfboard. The 16MHz oscillator also comes in SMD and through-hole packages. The ATMega328P can also be found on the compact Arduino Mini, and eliminates having to deal with the oscillator. Note, however, that the Arduino Mini needs a serial to USB adapter to be programmed. An alternative to the ATMega328P is the ATMega32U4, as found on the Arduino Micro. In fact, I recommend using an Arduino Micro for beginners, as it takes care of the complex oscillator and other components. It can also be purchased online for very cheaply. The Arduino Micro, Nano, Pro Mini, or basically any Arduino with 8 GPIO (at least 3 PWM, and 1 analog) should work. Of course, non Arduino microcontrollers will also work. NOTE: should be a 5V microcontroller Other microcontrollers can be used as well, however, the Arduino ecosystem provides fast development, and even though a lot of the libraries aren't the fastest, the firmware for the traffic light costume is not demanding at all. Using an SBC, like the Raspberry Pi is possible, but the lack of ADC, and much higher power consumption make it not recommended. Output MOSFETs To be able to control the high current LEDs, the MOSFETs are used. The microcontroller alone cannot power the LEDs, as they draw too much current. The ATMega328P has a per pin current limit of about 40mA. When choosing a MOSFET, there are a few specifications that need to be met: - Gate Threshold Voltage (Vgs) Since the microcontroller runs off 5V, the MOSFETs need to be logic level MOSFETs - meaning the gate threshold needs to be 4.5V, and preferably less. SMD MOSFETs, in smaller packages tend to have a lower gate threshold - about 3.3V is ideal. Through-hole MOSFETs can have much higher gate thresholds, so be careful when choosing one. - On resistance (Rds On) Another important specification of the MOSFETs is the on resistance. The higher the on resistance, the more power it will dissipate, and the hotter it will get. For the LEDs I used (about 300mA max), an on resistance of 500mOhms or less was ideal, and keeps the MOSFETs cool to the touch. - Max Continuous Current (Id) Current handling of the MOSFETs depends on the LEDs you use. For the traffic light costume, the LEDs don't need to be extremely bright, so 500mA or less should be good enough. If, like me, you use individual LEDs, you can put them in parallel, so that the voltage drop does not exceed 5V. This is desirable, so that you don't need to boost the voltage from the battery. If, however, you use LEDs that require a higher voltage, or you use many LEDs in series, you need to choose a MOSFET with appropriately high voltage rating. Most MOSFETs having voltage rating well above 5V. Controls The controls for the traffic light costume are pretty simple - just four buttons and a potentiometer (pot). This could be simplified even more, with just a potentiometer, if preferred. Any momentary button will do for the controls. You may, however, find some have better or worse switch characteristics. Some buttons may 'bounce', and will activate functions more than once, even if the button was only pressed once. This is easily fixed in software by increasing the "debounce delay". My design uses SMD tactile buttons and a through-hole 'right angle' pot, as found in handheld radios, etc. The pot is such that is sits fairly flush with the PCB, while part of the wheel sticks out for easier control. Volume pots are too large, and most trimmers require a screw driver to adjust. Resistors and Capacitors There are some resistors and capacitors that are needed. If you use a pre-made microcrontroller, such as the Arduino Micro or Mini, a lot of these are already placed for you. Most crystal oscillators require load capacitors - typically around 18pF - placed as close as possible to the crystal. The microconrtoller should have at least a 100nF ceramic cap near its power pins, and a larger (47uF) electrolytic cap. If you are also powering the LED of the same supply as the microcontroller, 100-220uF is recommended. If using a separate supply for the LEDs (a boost converter, for example), at least a 100uF should be used. When choosing capacitors, a good rule of thumb is to choose a voltage rating 50%+ more than the max voltage it will see in the circuit. Connectors There are three types of connectors used. One is a USB micro connector. This was chosen for easy connection to a USB battery. The second is the hobbyists favorite 0.1" (2.54mm) dupont header pins. These are using to interface to the serial/USB adapter, the ICSP, and the control PCB. The last connector is the 3.5mm screw terminal. These are rated for higher current than the header pins, and used to interface to the LEDs. Step 2: Electronics: Custom PCB For the traffic light costume, I designed a custom PCB, and used mainly SMD components. I also had the PCB manufactured by OSH Park. Since I only needed one, I decided to design my PCB in such a way that I could be used for other purposes. This means that the PCB is a bit more complicated that it needs to be for controlling the traffic light. I will describe how the design works, the essential parts related to controlling the traffic light costume, and alternatives for both through-hole and SMD designs. I have included the schematic and PCB design in this Instructable, along with the specific parts I used. If you decide to use my design, you should be fairly confident in SMD soldering, otherwise, stick to through-hole parts on perfboard. The PCB has two parts - the microcontroller board, and the controls board. I put them together so that I could order them online, and not have to pay extra for two boards. I cut mine using a band saw, but this can also be done with a hack saw, or a sharp utility knife. Always use eye protection and a mask when cutting fiberglass PCBs! Here is a list of the parts i used for the PCB i designed. I have included the part name as it appears on the PCB - Microcontroller: ATMega328P/ATMega168P/ATMega88P (all pin-compatible) Found here - C1,C3-C6,C8,C10,C16,C17 0805 100nF Ceramic capacitor - C7,C15 220uF 6.3V or higher, 2.5-6mm Electrolytic capacitor Found here - C18,C19 18pF 0805 NP0/C0G Ceramic capacitor Found here - R1,R8-R11 10K Ohm 0805 resistor - R2-R4 0R 0805 Jumper - R12, R13 330R 0805 resistor - Crystal oscillator: 16MHz 2-SMD Found here - MOSFETs: N-chan, SOT223, Vgs <= 3.3V, Vdss > 24V, Cont. drain current >= 1A Found here - 5x5mm tactile momentary SMD button Found here - 6x3.8mm tactile momentary SMD button Found here - Micro USB SMD connector Found here - 3.5mm screw terminals Found here - LED1,LED2 1206 SMD LED Found here - Potentiometer Found here Soldering The microcontroller is probably the most difficult part to solder, so I suggest starting with it, then moving on to it's supporting components - oscillator, capacitors, ICSP header and reset circuit. Once you have these in place, you can test it with a program like AVRdude to make sure it's working correctly. If so, then the rest of the parts can be soldered. Start with the physically shortest parts, and work your way up. Use plenty of flux! Powering Up Make sure you have the polarity of your power supply correct! This PCB has no reverse polarity protection, or over-voltage protection, so the microcontroller can be very easily fried. Microcontroller My design uses an ATMega328P - the same microcontroller found on the Arduino UNO. I chose this microcontroller because, with the Arduino Optiboot bootloader, it works, and programs, just like an Arduino UNO with the Arduino IDE. This requires a 16MHz oscillator. Either a crystal oscillator, or a less accurate ceramic oscillator, will do, as there is no critical timing needed. The ATMega168P and ATMega88P are pin compatible with the 328P, and only differ in program memory. The provided sketch only uses about 2K, so using the 168P or 88P should be fine. Output MOSFETs I used the BUK98150 N-channel MOSFET. It is rated 55V, 5.5A, and has a 2V nominal gate threshold voltage. The PCB footprint provides extra exposed copper for added thermal dissapation, and should be flooded with solder. There are footprints for MIC4416 MOSFET drivers on the PCB. These aren't needed for the traffic light costume, and should be bypassed. To do this, you need to place 0 Ohm jumpers in the places for R2,R3 and R4, otherwise, it won't switch the MOSFETs. The 'VSEL' jumper, R5-R7, C2, and C11-C14 do not need to be populated. LEDs There are footprints for two 1206 SMD leds - one on the main board, and one on the controls board. I chose not to populate the one on the main board, as it would be hidden when wearing the costume. The LED on the controls board is meant to be bright enough to show through the shirt. A 220 Ohm current limiting resistor should be sufficiently bright. Bootloader I chose the ATMega328P so that I could use an Arduino bootloader, specifically Optiboot. This essentially makes this board an Arduino UNO, at least as far as the Arduino IDE is concerned. To program the bootloader, you'll need an AVR programmer. This can be a USBasp, ISP, or even another Arduino. The Optiboot bootloader comes with the Arduino IDE, and I used AVRdudess (the GUI version of AVRdude) to program it. First, select your programmer, and then hit the 'Detect' button. If your PCB is working, it should successfully detect the 328P micrcontroller. When programming the bootloader, you'll need to set the appropriate fuses. There are links to a fuse calculator in AVRdudess, but if you are using my PCB design with a 16MHz oscillator, these fuse settings should work: - Low: 0xFF - High: 0xD9 - Extended: 0xFD Programming After the bootloader is successfully programmed, you can use a USB Serial adapter to program the microcontroller using the Arduino IDE. Make sure to use the DTR signal, so that the microcontroller will automatically be reset during programming. Step 3: Electronics: LEDs There are several different options when it comes to LEDs for the traffic light costume. They don't need to be overly bright, like a real traffic light - you're most likely going to be using this costume at night, and within close proximity of other people, and you don't want to overwhelm them! 5mm Piranha/5mm Flat Top/5mm Straw Hat Such as these Piranha, Flat Top, and Straw Hat LEDs all have one thing in common: they all have a fairly large throw angle. Piranha have the largest, followed by straw hat and then flat top. A large angle of throw is important to get a good, even light. If using these types of LEDs, you need to use series resistors to limit current. Use an online calculator to get a current of about 20-30mA. For the red and orange LEDs, two (with a forward voltage of about 2-2.2V each) can be used in series per one resistor. For the green (with a forward voltage of about 3.2V each) one can be used in series with a resistor. This is assuming a 5V supply. 12V LED Strip With the use of a boost converter, 12V LED strips can be used. These typically have built in resistors. WS2812 LED Strip WS2812, or any other addressable LED strips can be used. The advantage to using addressable LED strips are that they do not require MOSFET drivers. NOTE: The firmware included in this Instructable is not programmed to drive these LED strips. Step 4: Electronics: USB Battery To power the traffic light costume, I chose to use a common USB battery for mobile phones. They provide the 5V for the microcontroller, high current for the LEDs, and an easy means of recharging. This eliminates need for dedicated battery charging circuitry, a boost converter for the 5V, and to handle potentially dangerous Li-ion cells. The battery I chose had a capacity of 5500mAh. To figure out a rough estimate of battery life, take the capacity of the battery, in mAh, and divide by the average LED current. For example, on the lowest brightness setting, my LEDs consumed an average of 50mA. 5500mAh / 50ma = ~110h. Thats a long time! At the highest brightness setting - 350mAh, it would last about 15h. Either way, it would certainly last the night. Other battery types can be used instead, each with their own advantages and disadvantages. - Four alkaline AA batteries (in series, for a combined voltage of ~6V), could power the traffic light costume for about 5.5 to 40 hours for a 2000mAh battery. However, as the batteries are used, the voltage drops, and the LEDs will get dimmer. The advantage is that alkaline batteries are readily available. Also, they are much safer than Li-ion cells. - Five NiCd AA batteries (in series, for a combined voltage of ~6V), could power the traffic light costume. Battery life, and voltage drop are the same as alkaline, but are generally rechargeable. They are also much safer than Li-ion cells. - Li-ion cells (not in a USB battery), such as 18650 cells, can be used as well. Make sure they have undervoltage protection, and only use a Li-ion charger, so as not to damage the cells. The Problem The only problem I encountered using a USB battery is they are 'smart'. When the battery detects that there isn't very much current being drawn, it assumes that the mobile devices battery is charged, and shuts down in order to save its battery. When the traffic light costume is at its lowest brightness, it consumes too little current for the battery to stay on. To remedy this, I built a small circuit that periodically draws about 130mA of current from the battery. For about 2ms, once every 500ms, the microcontroller turns on a 2n2222 NPN transistor. A 39Ohm resistor in series with the transistor limits the current to 130mA, and a 82Ohm resistor in series with the base limits the microcontroller current. Not every battery will require these settings. Some will require a longer on time - even has long as 50ms. Also, some batteries my not be able to source a lot of current very quickly, and this can show as flickering of the LEDs. Step 5: Firmware: Overview The nice thing about using an ATMega328P microcontroller is the ability to use the Arduino Optiboot bootloader and the Arduino IDE. This allows you to use all the libraries available to Arduino. Firmware, Simplified The firmware is very simple. There are only a few things that need to be done periodically, and the rest of the time, the Arduino basically waits. Like all Arduino sketches, the firmware is based on a main loop. Every time this loop runs, the firmware does four things: - checks if a button is pressed - checks the voltage from the potentiometer - calls the appropriate mode function - pulses the battery to keep it 'alive' That's it. The loop runs very fast - thousands of times a second. Timing There are multiple functions in the firmware that rely on time. The changing of colors, the pulsing of the battery, and the brightness of the LEDs all require accurate timing, and usually all at the same time. The brightness of the LEDs is handled by the microcontroller in hardware - called Pulse Width Modulation, or PWM. The rest relies on using the millis() function to keep track of the current time, when events happen, and when the next event needs to happen. Debugging When firmware doesn't work properly, you need to debug it. The classic way of debugging Arduino code is to output it to the Serial port, so you can view it on a computer. I have built in basic debugging code into the firmware to help with problems. One of the most important parts of programming is comments. These allow others (and also you, maybe after a few years!) to understand the code. Code is typically not easily read, especially the C++ language that Arduino is based on. Throughout the code are comments that should help you understand what is going on. This doesn't mean that a beginner can dive right in! You do need some experience with Arduino, C, and/or C++ to fully understand it. Step 6: Firmware: in Depth Look Now I'll go through the code in detail. /*------------------------------------------------------------- * Software Options * - DEBUG (serial output) * - Battery stay alive function * /#define DEBUG // debug mode; outputs debug messages to Serial port #define BATSA // Battery stay alive; enables hardware to keep 'smart' // USB batterys from turning off due to low current. // NOTE: Settings may have to be adjusted for specific // batteries. /*------------------------------------------------------------- * Macros */ #ifdef DEBUG #define DEBUG_PRINT(msg) Serial.println(msg) #else #define DEBUG_PRINT(msg) #endif This code defines options. The #define DEBUG activates debug code, and will output to the Serial port. This is useful if you are having problems. The #define BATSA activates the USB battery stay alive functionality. To disable any of these, put double slashes "//" in front. /*------------------------------------------------------------- * Pins * / LED pins const uint8_t redLight = 5; const uint8_t yellowLight = 6; const uint8_t greenLight = 9; // switch pins const uint8_t redBttn = A4; const uint8_t yellowBttn = A3; const uint8_t greenBttn = A2; const uint8_t modeBttn = A5; const uint8_t brightKnob = A0; // USB battery stay alive pins const uint8_t saDriver = 11; This code defines the pins for each function. The LED pins are the pins that drive the output MOSFETs. The switch pins are the pins of each button, and the potentiomiter. /*------------------------------------------------------------- * Variables * / brightness of LEDs uint8_t brightness = 255; // relative brightness of LEDs; used to make each color the same brightness // highly depends on LEDs used! float redComp = 0.85; float yellowComp = 1.0; float greenComp = 0.9; // poteniometer value int potVal; // mode; 0 - traffic light; 1 - manual; 2 - disco uint8_t mode = 0; // default mode is 0 // state - used for modes 0, 2 uint8_t state = 0; // button checking variables uint8_t modeBttnState = 0; // timing variables unsigned long timeStart = 0; unsigned long timeCurr = 0; unsigned long timeElapsed = 0; // normal mode timing (in ms) #define TGREEN 8000 #define TYELLOW 4000 #define TRED 8000 // manual mode switch variables uint8_t redBttnState = 0; uint8_t yellowBttnState = 0; uint8_t greenBttnState = 0; // disco mode timing variables short beats[4] = {600, 420, 210, 125}; unsigned short discoDelayIndex = 2; // change to new colour every 500ms unsigned long discoPrev = 0; // time of last disco color change // disco mode variables short discoLightMode = 0; // 0 - constant; 1 - pulse uint8_t currCol = 0; // current colour; 0 - green; 1 - yellow; 2 - red uint8_t newCol = 1; #define pulseDelay 75 // duration of pulse in pulse mode disco mode // USB battery stay alive variables uint8_t saState = 0; // on or off unsigned long saCurr = 0; unsigned long saNext = 0; // USB battery stay alive OPTIONS #define saTH 2 // time (ms) to draw current #define saTL 497 // time (ms) to wait (no current draw) This code defines variables needed for the various modes, along with their default values. There are a few #define statements that define things open to change, based on your preferences and hardware. #define TGREEN 8000 #define TYELLOW 4000 #define TRED 8000 These define the duration, in milliseconds, of the different colors. For example, TGREEN 8000 says that the green light will stay on for 8000 milliseconds, or 8 seconds. /*------------------------------------------------------------- * Arduino standard setup function */ void setup() { #ifdef DEBUG Serial.begin(115200); #endif #ifdef BATSA DEBUG_PRINT("Battery stay alive active"); // initialize digital pins for optional USB battery stay alive pinMode(saDriver, OUTPUT); digitalWrite(saDriver, LOW); // initialize values for USB stay alive saCurr = millis(); saNext = saCurr + saTL; #endif // initialize digital pins for LEDs pinMode(redLight, OUTPUT); pinMode(yellowLight, OUTPUT); pinMode(greenLight, OUTPUT); // initialize digital pins for switches pinMode(redBttn, INPUT); pinMode(yellowBttn, INPUT); pinMode(greenBttn, INPUT); pinMode(modeBttn, INPUT); // 'randomize' seed for random numbers randomSeed(analogRead(A0)); } The setup function initializes pins, the Serial port (if enabled by DEBUG) and the USB battery stay alive (if enabled by BATSA). The pins are initialized as INPUT (switch inputs) or OUTPUT (LEDs). void loop() { #ifdef BATSA stayAlive(); #endif getBrightness(); checkModeBttn(); // select mode if (mode == 1) { mode1(); // disco mode } else if (mode == 2) { mode2(); // manual mode } else { mode0(); // normal mode; default } } The loop is pretty simple. It does four things: activates the stay alive function, gets the value from the potentiometer, and converts it to a brightness value, checks if any buttons are pressed, and activates LEDs based on which mode is active. /*------------------------------------------------------------- * getBrightness function * calculates brightness from pot */ void getBrightness() { potVal = analogRead(brightKnob); // get analog reading brightness = (uint8_t)( ( (potVal/32)*(potVal/32) )/4 ); // convert pot value to brightness // using an exponential scale if (brightness < 4) { brightness = 0; } DEBUG_PRINT("Brightness:"); DEBUG_PRINT(brightness); } The getBrightness function reads the value of the potentiometer. The potentiometer uses a potential divider to put a variable voltage on an analog pin of the ATMega328P. This value is then converted to a brightness value. Since potVal is a float (meaning it had a fractional value), it needs to be converted to a non-fractional value. This is done using the (unit8_t). /*------------------------------------------------------------- * checkModeBttn function * checks for input from mode button * sets defaults for each mode */ void checkModeBttn() { // read mode button modeBttnState = digitalRead(modeBttn); if (modeBttnState) { // if mode button was pressed ++mode; // increment mode variable DEBUG_PRINT("Mode:"); DEBUG_PRINT(mode); // turn off all LEDs at mode change analogWrite(redLight, 0); analogWrite(greenLight, 0); analogWrite(yellowLight, 0); // if mode variable is greater then 2, reset to 0 if (mode > 2) { mode = 0; } // if mode is 2, initialize disco mode delay and reset to color 0 if (mode == 2) { discoDelayIndex = 2; currCol = 0; } // if mode is 0 or 1, reset timing variables & reset to color 0 if (mode < 2) { timeCurr = 0; timeStart = 0; currCol = 0; // if mode is 1, set color to red if (mode == 1) { analogWrite(redLight, brightness*redComp); } } // delay for a rough software debounce delay(200); } } The checkModeBttn function checks to see if the mode button has been pressed. If so, then it will increase the mode variable by one. When it gets to greater than 2, it will reset to 0. Remember, when coding, variables start at 0, not 1! The delay(200) is a rough debounce feature. this code also sets default values for each mode. /*------------------------------------------------------------- * mode0 function * normal traffic light mode */ void mode0() { timeCurr = millis(); // get curent millisecond timeElapsed = timeCurr - timeStart; // get elapsed time from previous color change if (state == 1) { // yellow analogWrite(yellowLight, brightness*yellowComp); // turn on yellow LED analogWrite(greenLight, 0); // turn off green LED DEBUG_PRINT("Yellow ON"); if (timeElapsed > TYELLOW) { // go to next color after so many milliseconds state = 2; // go to red next timeStart = millis(); // 'save' time of color change } } else if (state == 2) { // red analogWrite(redLight, brightness*redComp); // turn on red LED analogWrite(yellowLight, 0); // turn off yellow LED DEBUG_PRINT("Red ON"); if (timeElapsed > TRED) { // go to next color after so many milliseconds state = 0; // go to green next timeStart = millis(); // 'save' time of color change } } else { // green (state 0) analogWrite(greenLight, brightness*greenComp); // turn on green LED analogWrite(redLight, 0); // turn off red LED DEBUG_PRINT("Green ON"); if (timeElapsed > TGREEN) { // go to next color after so many milliseconds state = 1; // go to yellow next timeStart = millis(); // 'save' time of color change } } } mode0 is the normal traffic light function. It cycles through the colors based on the time elapsed. Each time the function is called, it updates the current millisecond value. The elapsed time triggers the next color change. /*------------------------------------------------------------- * mode2 function * manual traffic light mode */ void mode1() { redBttnState = digitalRead(redBttn); // read red button if (redBttnState) { // turn on red analogWrite(greenLight, 0); analogWrite(yellowLight, 0); analogWrite(redLight, brightness*redComp); DEBUG_PRINT("Red ON"); } else { yellowBttnState = digitalRead(yellowBttn); // read yellow button if (yellowBttnState) { // turn on yellow analogWrite(greenLight, 0); analogWrite(redLight, 0); analogWrite(yellowLight, brightness*yellowComp); DEBUG_PRINT("Yellow ON"); } else { greenBttnState = digitalRead(greenBttn); // read green button if (greenBttnState) { // turn on green analogWrite(yellowLight, 0); analogWrite(redLight, 0); analogWrite(greenLight, brightness*greenComp); DEBUG_PRINT("Green ON"); } } } } This code is for the 'manual' mode. All it does it wait for a button is pressed. When a button is pressed, it activates a color LED, and deactivates the others. /*------------------------------------------------------------- * mode3 function * disco traffic light mode */ void mode2() { timeCurr = millis(); // get curent millisecond timeElapsed = timeCurr - discoPrev; // get elapsed time from previous color change if (timeElapsed >= beats[discoDelayIndex]) { // get random color, but NOT the same as current do { newCol = (int)(random(1199)/400); // get random number between 0 and 2 (inclusive) } while (newCol == currCol); currCol = newCol; // change to new color, turn off all other colors if (currCol == 0) { analogWrite(yellowLight, 0); analogWrite(redLight, 0); analogWrite(greenLight, brightness*greenComp); } else if (currCol == 1) { analogWrite(greenLight, 0); analogWrite(redLight, 0); analogWrite(yellowLight, brightness*yellowComp); } else { analogWrite(greenLight, 0); analogWrite(yellowLight, 0); analogWrite(redLight, brightness*redComp); } // if in 'pulse' mode, pulse LED, then turn off if (discoLightMode == 1) { delay(pulseDelay); analogWrite(greenLight, 0); analogWrite(yellowLight, 0); analogWrite(redLight, 0); } // get current millisecond discoPrev = millis(); } // read all button states redBttnState = digitalRead(redBttn); yellowBttnState = digitalRead(yellowBttn); greenBttnState = digitalRead(greenBttn); // if red button pressed if (redBttnState) { // switch between pulse and constant disco mode if (discoLightMode == 0) { discoLightMode = 1; DEBUG_PRINT("Pulse Mode ON"); } else { discoLightMode = 0; DEBUG_PRINT("Pulse Mode OFF"); } delay(150); // debounce } // if yellow button pressed if (yellowBttnState) { // descrease disco speed --discoDelayIndex; if (discoDelayIndex < 1) { // limit to min 1 discoDelayIndex = 1; DEBUG_PRINT("More speed!"); } delay(250); // debounce } // if green button pressed if (greenBttnState) { // increase disco speed ++discoDelayIndex; if (discoDelayIndex > 3) { // limit to max 3 discoDelayIndex = 3; DEBUG_PRINT("Less speed"); } delay(250); // debounce } } This code is part of the 'disco' mode. There are a few options for the disco mode. One is the speed of the color change. When the red or yellow button is pressed, the speed of the color change is increased of decreased, respectively. When the green button is pressed, the pulse mode is changed. The default mode is 'constant mode'. In this mode, the LED will stay on until the next color change. In 'pulse mode' the light will stay on for a number of milliseconds, defined by pulseDelay. Step 7: 3D Printing: Overview When I made the first version of the traffic light costume, about 3 years ago, it was mainly made out of cardboard and duct tape! Since then, 3D printing as become common, and much more affordable. My second version is about 50% 3D printed. It is much more durable, and can now even stand up to some light rain. My 3D printed parts were printed on my personal printer - an Anet A8. However, there are many online services, and makerspaces available that have 3D printers. My local library even has one. 3D Printed Pieces There are fours 3D printed pieces for each color on the traffic light: - Base: The base does two things: it provides something to attach the LEDs to, and it provides something to attach the shirt to. It is meant to 'poke out' from the shirt, so that there is fabric stretched around it. The base has holes for sewing, so that the base is secure. I chose to print the base in white, so that the light from the LEDs will bounce around, adding to the diffusion - sort of like a softbox. - Tube: The tube is not only cosmetic, but when fitted over the base and glued, 'traps' the fabric, creating a very secure and durable fit. - Lens: The lens is covers the LEDs, and adds color when the LEDs are both on and off. The Lenses are printed with a transparent filament, which adds a diffusion effect, and takes away some of the hard glare of the LEDs. In conjunction with the tube and base, when glues, provides a water resistant seal. - Cap: The cap is purely cosmetic. It adds to the look of the traffic light. Each piece can be printed without supports. The lens is the only piece that has a specific requirement for layer height - a layer height of about 0.1 is recommended, so that the patterned side is as smooth as possible. You may also want to sand it a bit. Step 8: Fabric For the tshirt, I ordered two 'gold' tshirts on eBay. They are GILDAN brand, and fairly heavy. You need to buy two, as you need extra fabric for the caps and pockets for the PCBs. I bought one tshirt one size too big. Where I live, it can get very cold on Halloween, so the extra room allows me to where a sweater or jacket underneath. It's not too big, and I can still where it without anything else. The second tshirt, because I on'y needed a little extra fabric, and it was cheaper, was a small. A good thing to remember is that fabric stretches, so cutting the pieces a bit small is not a problem - just make sure when you glue it to stretch it and hold it. Step 9: Fitting It Together When all the pieces are printed, they should fit together a bit loosely. This is intended, especially with the base and tube, so that there is room for fabric and glue. Here are the steps I took to put it all together: Step 1 Mark three holes on the shirt, leaving about 10mm between the largest part of the base. Cut three hole, in the centre, about a 1/2 to 2/3 the diameter of the base. After that, the base can be inserted from inside the shirt, so they stick out. You can now sew the bases tot he shirt. Step 2 At this point, I attached the LEDs and made sure they had long enough wires. I bit of extra is recommended. I drilled some holes into the perfboard my LEDs were mounted on, and used zip ties to attach the perfboard to the cross pieces on the bases. Remember, after the lens is glued on, it will be very difficult to get at the LEDs to fix anything. Now is a good time to test the LEDs! Step 3 After sewing together the fabric for the cap, it can be glued on. Leave it for a few hours to dry. Step 4 Glue the cap to the tube. Use lots of glue, and one at a time. The cap and tube need to be pressed together while the glue dries. For this, I used some speaker wire and wrapped it around tight. Step 5 This is a big step. I advise you do it one color at a time, and let it all dry before doing the next. This step involves gluing the lens and tube together. Glue the lens first. If the lens isn't glued straight, the tube might not fit on, so be careful. After the lens, apply lots of glue to the base, and put on the tube. Get something with some weight to put on top of the lens. Allow lots of time for the glue to dry. Step 6 After the 3D printed parts are all glued together, I took a stiff piece of cardboard, and attached it to the bases of all three lights. This helped keep the lights spaced out, as they are a bit heavy. Step 7 Now it's time to sew a pocket for the main PCB, and for the controls. Do the controls first, so that you can space it and the main board the length of the wires connecting them. Any bend in the wires will mean a bend in the shirt. Step 8 Sew the main board and controls as tight as possible. The PCB file included with this Instructable has many holes for sewing. Finally, once secure, you can draw on some indication for the controls. I just used different colored sharpies. Final Steps Now, the costume should be done! There are a few more things that are optional. I used some spiral wire wrap to help protect the wires. I also ziptied the USB cable for the battery to the control wires, so it didn't accidentally come out. Step 10: Conslusion I hope you enjoyed my Instructable on my traffic light costume. If I were to make it over again, there are a few things I would change: USB battery stay alive circuit More complete testing would have caught this problem sooner than the day before Halloween. I only tested the electronics with a bench power supply. If I were to redesign the PCB, I would incorporate the USB keep alive circuit fix into the PCB. As it is, it is only needed for specific USB batteries, and I did not find it necessary to redesign the PCB yet. Less expensive microcontroller The ATMega328P is a great microcontroller, however, it is a bit expensive compared to others, such as the PIC. It also has more pins than is needed for this application. Improvements - With an unused SPI port, and serial port, there are a multitude of things that could easily be added. One interesting idea would be to add a Bluetooth module, so that the functions of the traffic light coul dbe controlled by phone. - Another idea, using the SPI or serial port, would be to add wireless communication. With two or more shirts, the light could be synced together. The nRF24L01+, an ultra low power, ISM-band wireless transceiver, would be perfect for this application, and have almost no impact on battery life. - More LEDs!! Pedestrian crosswalk signal could be added to gloves, or on the shoulders of the costume. Feel free to leave a comment or question below. I'm always happy to answer questions! 2 Discussions 1 year ago Nice costume! 1 year ago I like this a lot. Nicely done! Great costume idea.
https://www.instructables.com/id/LED-Traffic-Light-Halloween-Costume/
CC-MAIN-2019-13
refinedweb
5,976
70.63
Your browser does not seem to support JavaScript. As a result, your viewing experience will be diminished, and you have been placed in read-only mode. Please download a browser that supports JavaScript, or enable it if it's disabled (i.e. NoScript). On 04/08/2018 at 05:32, xxxxxxxx wrote: User Information: Cinema 4D Version: 19 Platform: Windows ; Language(s) : C++ ; --------- At first, I thought that it's a very simple task.. My mistake.:-/ What I tried to do is to create global storage and save link to plugin instance every time it's being created: < <<Main.cpp>>> def PLUGIN_ID = 1234321 class MyTagPlugin: TagData { ... ... MyTagPlugin::MyTagPlugin() { GePrint("---MyTag constructor---"); } Bool MyTagPlugin::Init(GeListNode *node) { GePrint("init..."); pluginStorage = GetActiveDocument()->GetDataInstance()->GetContainer(PLUGIN_ID); // ERROR SECTION /* index = bc.GetInt32(0,0)+1; pluginStorage.SetInt32(0,index); pluginStorage.SetLink(index, (BaseTag* )node); */ } Bool PluginMessage(Int32 id, void *data) { if(id==C4DPL_COMMANDLINEARGS) { GePrint("Creating plugin storage"); GetActiveDocument()->GetDataIstance()->SetContainer(PLUGIN_ID, BaseContainer()); } } < <<Output>>> Creating plugin storage ---MyTag constructor--- init... ---MyTag constructor--- init... Why Constructor and Init functions of my plugin are fired twice when each instance of it created and twice every time when I change any parameter of MyTag? What event or function should I use instead, to catch the moment of MyTag creation? On 06/08/2018 at 02:50, xxxxxxxx wrote: Hi, indeed you can not rely on Init() (or the constructor) being called just once. There are several reasons for this, one for example is related to the undo system. The correct way to be informed about the creation of your tag is to listen to the (admittedly strangely named) message MSG_MENUPREPARE. This message is sent, when the user creates a new tag from the menu (and is meant to do additional preparational work, thus its name). May I ask, why you are trying to set up such a global directory of tag instances? In that regard also you use of PluginMessage(C4DPL_COMMANDLINEARGS) looks a bit strange to me. The user might be working with multiple documents in parallel later on. Or he might close the scene and open a new one. The more correct approach would be, to check the existence of your BaseContainer later on, when you actually want to access it, and then create it on the fly if needed. On 18/08/2018 at 09:52, xxxxxxxx wrote: Hi, Andreas. May I ask, why you are trying to set up such a global directory of tag instances? What I wanted to create is some kind of visibility switcher that gonna let me easely show/hide different groups of objects in my scene. Each instance of MyTag "knows" 4 things: 1)parameter number (i mean [c4d.ID_USERDATA,param_num] of controller object) 2)active parameter value 3)active layer 4)inactive layer I'm creating controller object which contains different parameters, and when value of some parameter is changed, python script sends message to all instances of MyTag with number of parameter that was changed and it's new value. (* ) If (new_value==active_value) then (layer=active_layer), else (layer=inactive_layer) > (* ) _That's the step where I needed whole list of MyTag-s. I avoided this problem by creating MyTag list within my python code. > _ ---------------- UPD (offtopic) : BTW, Andreas, there's definetely something wrong with photometric light sources in C4D. I wrote about it here: Here are some IES files to check: I think it's a bug. On 24/08/2018 at 06:17, xxxxxxxx wrote: I'm actually not quite sure, if we still have an open question here. Please forgive. For the IES lights I'd recommend to submit the bug to our user support: How can we help?
https://plugincafe.maxon.net/topic/10900/14349_how-to-get-list-of-all-myplugin-instances
CC-MAIN-2021-31
refinedweb
613
54.02
This is your resource to discuss support topics with your peers, and learn from each other. 05-05-2010 11:20 AM - edited 05-05-2010 11:23 AM Hi, I have a new application to do that needs network access. I've read this EXCELLENT post by peter_strange: Since I cannot use BIS-B because I'm not an Alliance Partner, I wanted to take a look at the new Network API for OS 5.0 and see how it works. I know that network connections need to be done in a separate thread. I'm far from being an experienced Blackberry developer... so I have a few questions regarding threads. I looked around the Internet, read the forum, read the documentation, did some tests and so far, I came up with this code: public class HTTPConnection extends UiApplication { public static void main(String[] args) { HTTPConnection theApp = new HTTPConnection(); theApp.enterEventDispatcher(); } public HTTPConnection() { pushScreen(new HTTPConnectionScreen()); } } class HTTPConnectionScreen extends MainScreen { public HTTPConnectionScreen() { setTitle("HTTPConnection"); add(new RichTextField("Choose a connection type: ")); final RadioButtonGroup rbGroup = new RadioButtonGroup(); RadioButtonField radioButtonF1 = new RadioButtonField("Direct TCP", rbGroup, false); RadioButtonField radioButtonF2 = new RadioButtonField("WAP 1.0/1.1", rbGroup, false); RadioButtonField radioButtonF3 = new RadioButtonField("WAP 2.0", rbGroup, false); RadioButtonField radioButtonF4 = new RadioButtonField("BES/MDS", rbGroup, false); RadioButtonField radioButtonF5 = new RadioButtonField("BIS-B", rbGroup, false); RadioButtonField radioButtonF6 = new RadioButtonField("WiFi", rbGroup, false); add(radioButtonF1); add(radioButtonF2); add(radioButtonF3); add(radioButtonF4); add(radioButtonF5); add(radioButtonF6); FieldChangeListener listener = new FieldChangeListener() { public void fieldChanged(Field field, int context) { ConnectionThread ct = new ConnectionThread(rbGroup.getSelectedIndex()+1); ct.start(); } }; ButtonField buttonField = new ButtonField("Connect", ButtonField.CONSUME_CLICK); buttonField.setChangeListener(listener); add(buttonField); } /* over-ride default onSavePrompt method to avoid being asked if I want to save each time */ protected boolean onSavePrompt() { return true; } } class ConnectionThread extends Thread { private int transportType; public ConnectionThread(int tt) { transportType=tt; } public void run() { ConnectionFactory connFact = new ConnectionFactory(); ConnectionDescriptor connDesc = connFact.getConnection("URL", transportType, null); if (connDesc != null) { try { HttpConnection httpConn = (HttpConnection)connDesc.getConnection(); httpConn.setRequestMethod(HttpConnection.POST); httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStream out = httpConn.openOutputStream(); out.write(Integer.toString(transportType).getByte int responseCode = httpConn.getResponseCode(); if (responseCode == HttpConnection.HTTP_OK) { UiApplication.getUiApplication().invokeLater(new Runnable() { public void run() { Dialog.alert("--CONNECTION SUCCESSFUL--"); } }); } if (httpConn!=null) httpConn.close(); } catch (IOException e) { System.err.println("Caught IOException: " + e.getMessage()); } } } } Actually, this code works fine... but I want to improve it and I have a few questions: 1- I think that right now, everytime I click on the "Connect" button, I start a brand new thread. I would like to close that thread in the "run" method, but I don't really know how to access the "ct" variable from there. Any advise on how to do this? Or maybe always use the same thread until my application is closed? 2- In the FieldChangeListener of my "Submit" button, I want to access the radio box value. What I did works, but I had to make my variable "final". Is this the right way to do so? 3- Instead of displaying a Dialog with "Connection Successful", I would like to write something back in my main screen. How could I do that? I'm just a bit confused as to all put that together when using a separate thread. Thanks for your advices! Edit: Hid the URL I'm connecting to... Solved! Go to Solution. 05-05-2010 11:29 AM 05-05-2010 12:00 PM Thanks for your lightning fast answer! Regarding #1: So nothing to change here... but I just want to make sure I fully understand. If I understand correctly, I start a new thread when I click on the "Connect" button. This automaticaly execute the code inside my "Run" method. When the code in this method has finished executing, the thread "dies"... so that's why I don't need to close it. The application is still running though. So if I click on the "Connect" button again, then a new thread is started again that will eventually "dies" when the "Run" method is finished and so on. Am I right? If I wanted to close completely my application, would I only need to add "System.exit(0);" somewhere in my "Run" method? Regarding #2: I wanted to make sure I did this the right way (it's Eclipse who told me to make my variable "final"). I did a FieldChangeListener much like the example in the javadocs... and wanted to know how to access variables from the outer class in the inner class. So nothing to change here as well Regarding #3: I'll read your link. Thanks again! 05-05-2010 12:09 PM 05-06-2010 02:12 PM Regarding #3: I read your link (many times!)... but I'm still confused as to how to do that. I want to write stuff to the main screen in the "Run" method. Since it's not from the same class and not from the same thread, I don't know how to do this. Also, I don't want to make all my variables "final" cause some of them might have to change. I know I'm asking a lot, but could you just give me an quick example on how to do this based on my situation? Sorry, I'm still a newbie on Blackberry development... and it's been a while since I did OO coding. 05-07-2010 03:05 AM 05-07-2010 04:37 AM Here is a sample that uses the first approach as suggested by Simon - i.e. updates the screen directly. I'm working on the article that does the second (the Observer Interface). I'm interested in any comments too.... 05-10-2010 02:16 PM I got it! Thanks Simon for all your help and Peter for your great sample! I'm waiting for part-2
https://supportforums.blackberry.com/t5/Java-Development/Questions-regarding-threads/m-p/497122/highlight/true
CC-MAIN-2016-36
refinedweb
979
50.02
use_prefix warnings update Expand Messages - Dear SOAP::Lite Users, I am uploading into CPAN as we speak SOAP::Lite 0.66.1 - this is a MINOR release that simply suppresses the warning message about the use of use_prefix. It does not fix any other underlying problems. I wanted to get this out there as a stop gap so that people's error logs weren't getting spammed with these warning messages. Meanwhile, I working on unraveling a bit of the SOAP::Lite code base to see if I can't fix the problem more elegantly. I am using the Delayed Stock Quote service as a core use case, and so far I have been unable to send a message to it without hacking the source code directly to swap out the use of "ns()" for "default_ns()". Long story short, I have some work to do. My sincerest apologies for any trouble this has caused. I am working on a fix. But if you have ever looked at the SOAP::Lite source code, you may have some empathy for me. Paul (the original author) is a genius (sincerely), but reading the notes of a genius can be excruciating work sometimes. :) Anyway - here is what I am proposing I do: I am going to rewrite the source code that SOAP::Lite generates from a WSDL file, then I am going to modify SOAP::Lite to generate that sourcecode as opposed to what it is generated currently. Take a look at this code: my $client = SOAP::Lite->service(<URL TO WSDL>); Now, let me ask you: what do you think is the object type of the $client variable? The intuitive response I believe is the same thing that would be returned if I called: my $client = SOAP::Lite->proxy(<URL TO endpoint>)->ns(<NAMESPACE>); Or in other words, an instance of a SOAP::Lite client. It is in fact an instance of net_xmethods_services_stockquote_StockQuoteService. Which is fine by me assuming I can still access the accessors or a SOAP::Lite client to toggle the use of a default namespace or not. Anyway, for the Perl hackers out there who are interested - here is a snapshot of the code SOAP::Lite generates based upon a WSDL. You may notice that it is not that object oriented. I need to fix that. But then again, there are sooooo many things about SOAP::Lite I need to fix. # Generated by SOAP::Lite (v0.66) for Perl -- soaplite.com # -- generated at [Wed Jan 4 14:06:54 2006] # -- generated from package net_xmethods_services_stockquote_StockQuoteService; my %methods = ( getQuote => { endpoint => '', soapaction => 'urn:xmethods-delayed-quotes#getQuote', namespace => 'urn:xmethods-delayed-quotes', parameters => [ SOAP::Data->new(name => 'symbol', type => 'xsd:string', attr => {}), ], # end parameters }, # end getQuote ); #("","electric"); $self->serializer->register_ns("","soap"); $self->serializer->register_ns("","wsdl"); $self->serializer->register_ns("","soapenc"); $self->serializer->register_ns(" ockQuote/","tns"); $self->serializer->register_ns("","xsd");; Your message has been successfully submitted and would be delivered to recipients shortly.
https://groups.yahoo.com/neo/groups/soaplite/conversations/topics/5114?o=1&source=1&var=1
CC-MAIN-2017-26
refinedweb
488
52.29
This article describes Amazon S3 from the C# developer point of view. It shows how to access the Amazon S3 service from C#, what operations can be used, and how they can be programmed. Amazon SDK for .NET is used for the examples in the article. An Amazon EC2 account is required, and an access and private keys are also necessary to start using the SDK. See more details at this link. Amazon S3 is called a simple storage service, but it is not only simple, but also very powerful. It supports a lot of features that can be used in everyday work. But of course, the main feature is the ability to store data by key. You can store any data by key in S3, and then you can access and read it. But to do it, a bucket should be created at first. A bucket is similar to a namespace in terms of C# language. An AWS account is limited by 100 buckets, and all bucket names are shared through all of Amazon accounts. So you must select a unique name for it. See more details at this link. Let's see how to check if a bucket is already created, and how to create it in case of its absence: ListBucketsResponse response = client.ListBuckets(); bool found = false; foreach (S3Bucket bucket in response.Buckets) { if (bucket.BucketName == BUCKET_NAME) { found = true; break; } } if (found == false) { client.PutBucket(new PutBucketRequest().WithBucketName(BUCKET_NAME)); } where "client" is the Amazon.S3.AmazonS3Client object. You can see how to initialize it in the example that is attached to this article. client Amazon.S3.AmazonS3Client Let's run the code and check that the bucket has been really created. I am using EC2Studio (add-in for Microsoft Visual Studio) to work with S3 through the UI. A code that stores some data for some key in a bucket is shown here: PutObjectRequest request = new PutObjectRequest(); request.WithBucketName(BUCKET_NAME); request.WithKey(S3_KEY); request.WithContentBody("This is body of S3 object."); client.PutObject(request); Here, the S3 object is created with a key defined in the constant S3_KEY and a string is written into it. S3_KEY A content of a file can also be put into S3 (instead of a string). To do it, the code should be modified a little: PutObjectRequest request = new PutObjectRequest(); request.WithBucketName(BUCKET_NAME); request.WithKey(S3_KEY); request.WithFilePath(pathToFile); client.PutObject(request); To write a file, the method WithFilePath should be used instead of the method WithContentBody. See more details about S3 objects at this link. WithFilePath WithContentBody Now, let's make sure that the data into S3 has really been written: After you see the S3 object in the S3 browser in the EC2Studio add-in, double click on it and select a program to use to show its content. The screenshot shows that S3Object has been created and its content is opened in Notepad. S3Object To read the S3 object from C# code: GetObjectRequest request = new GetObjectRequest(); request.WithBucketName(BUCKET_NAME); request.WithKey(S3_KEY); GetObjectResponse response = client.GetObject(request); StreamReader reader = new StreamReader(response.ResponseStream); String content = reader.ReadToEnd(); In addition to the S3 object content, a metadata (key/value pair) can be associated with an object. Here is an example of how it can be done: CopyObjectRequest request = new CopyObjectRequest(); request.DestinationBucket = BUCKET_NAME; request.DestinationKey = S3_KEY; request.Directive = S3MetadataDirective.REPLACE; NameValueCollection metadata = new NameValueCollection(); // Each user defined metadata must start from "x-amz-meta-" metadata.Add("x-amz-meta-test", "Test data"); request.AddHeaders(metadata); request.SourceBucket = BUCKET_NAME; request.SourceKey = S3_KEY; client.CopyObject(request); Amazon S3 does not have a special API call to associate metadata with an S3 object. Instead of it, the Copy method should be called. Copy But the S3 API has a special method for reading metadata: GetObjectMetadataRequest request = new GetObjectMetadataRequest(); request.WithBucketName(BUCKET_NAME).WithKey(S3_KEY); GetObjectMetadataResponse response = client.GetObjectMetadata(request); foreach (string key in response.Metadata.AllKeys) { Console.Out.WriteLine(" key: " + key + ", value: " + response.Metadata[key]); } Let's see through the EC2Studio add-in that the metadata has been assigned: The good news is that S3 allows accessing S3 objects not only by API calls, but directly by HTTP (so each S3 object has a URL that can be used to access it by any web browser). You can use S3 as a simple static HTTP server, where you can host your static web content. Moreover, S3 has an access control that allows limiting users who can access data (see more about ACL access below). And not only who, but also when... The Amazon SDK API allows generating a signed URL that is valid for a limited time only. Here is the code that makes a URL with a validity for a week: GetPreSignedUrlRequest request = new GetPreSignedUrlRequest().WithBucketName(BUCKET_NAME).WithKey(S3_KEY); request.WithExpires(DateTime.Now.Add(new TimeSpan(7, 0, 0, 0))); string url = client.GetPreSignedURL(request)); And the same can be done through the EC2Studio add-in: Then you can send the URL to everyone and be sure that the access to your data is stopped for them after the defined time. When talking about hosting a static web content at Amazon S3, the log access feature should be mentioned, because you should know who accesses your web site and when. S3 has such a feature. First of all, you should configure logging for a bucket. It can be done through an API, but it is a quite a rare operation, so let's just use the EC2Studio add-in to turn logging on for a bucket. A target bucket where your logging files are stored must be defined. A prefix can be defined to know where those log files are from. As a result, every access to any object in the bucket will be logged to the destination bucket, and Amazon S3 will create the file with logging information from time to time. The file can be read using the usual API call for reading any S3 object. But it has a special format that is not very convenient to view, so let's use EC2Studio again to see the logging information. See more details at this link. As I mentioned earlier, Amazon S3 has a feature to define access. There are two types of access: by user ID/email, or by URL (this means predefined groups or users): So you can define a read or write access and define who is permitted to read and write ACL for any S3 object or bucket. There is a special API call to set or read ACLs; for example, an owner of S3Object can be found like: GetACLResponse response = client.GetACL (new GetACLRequest().WithBucketName(BUCKET_NAME).WithKey(S3_KEY)); Console.Out.WriteLine("Object owner is " + response.AccessControlList.Owner.DisplayName); Another cool feature of Amazon S3 is versioning. You can turn versioning on for a bucket, and when you put any object into it, it will not be simply replaced, but the new version of the object will be created and stored under the same key. So you will be able to access and manage all versions (modifications) of the object. All versions of an S3 object can be retrieved by the following call: ListVersionsResponse response = client.ListVersions (new ListVersionsRequest().WithBucketName(BUCKET_NAME).WithPrefix(S3_KEY)); Console.Out.WriteLine("Found the following versions for prefix " + S3_KEY); foreach (S3ObjectVersion version in response.Versions) { Console.Out.WriteLine(" version id: " + version.VersionId + ", last modified time: " + version.LastModified); } For accessing versions by UI: To delete a particular object version, client.DeleteObject can be used. The required version ID should be put as a request parameter. client.DeleteObject The same is true for accessing objects. A version can be read by client.GetObject with the version ID as a request parameter. client.GetObject If you use any S3 browser (the EC2Studio add-in or any other), you will notice that all of them represent the S3 storage as a file system, while it is just a key/value storage. Moreover, most tools show S3 primarily as a file storage (usually to backup files). As shown earlier, it has a lot of cool features that don't exist in usual file systems. So S3 can be used as a more generic storage for keeping application data. It is useful to have a hierarchical structure, and S3 supports it. Every key of S3Object can have special delimiters (usually '/' is used, but you can define your own delimiter) that divide a full key into some path. And you can request an S3 object list for a defined path (directory): ListObjectsRequest req = new ListObjectsRequest(); req.WithBucketName(BUCKET_NAME); req.WithPrefix(DIR_NAME); ListObjectsResponse res = client.ListObjects(req); Console.Out.WriteLine("Enumerating all objects in directory: " + DIR_NAME); foreach (S3Object obj in res.S3Objects) { Console.Out.WriteLine(" S3 object key: " + obj.Key); } And the same can be viewed in the UI: The Amazon S3 service is a full featured service that can be utilized from C# code to store application data, to define additional metadata for it, with the ability to define who will have a pure HTTP access to your data and when. See the log for data access. And moreover, there is the versioning storage with the ability to define a hierarchical.
http://www.codeproject.com/Articles/84961/Amazon-S-from-C-Developer-Point-of-View?msg=3492438
CC-MAIN-2016-07
refinedweb
1,531
57.27
Try ditching the const, and instantiating Block, then set Blockstone. I have verified the instance name matches.The object of this is to show a countdown and then to go to the next scene to start playing the game.import flash.utils.Timer;import flash.events.TimerEvent;var countDownTimer:Timer Code: TypeError: Error #1009: Cannot access a property or method of a null object reference. What is way to eat rice with hands in front of westerners such that it doesn't appear to be yucky? this content Why do (some) aircraft shake at low speeds with flaps, slats extended? Elige tu idioma. Incoming Links Re: why am i getting this pop-up: ypeError: Error #1009: Il est impossible d'accéder à la propriété ou à la méthode d'une référence d'objet nul. That Is All Thanks for reading this Quick Tip! do NOT have set AS linkage because I cant manipulate the visibility with AS Linkage set. But debug warns all the objects such as page,volumn,article,journal,year,author,doi Like Show 0 Likes(0) Actions 5. But other times it’s helpful to narrow this down further. And trace the objects in that line, you can easily find out the null object.For debug the program, go to Debug -> Debug Movie -> in Flash Professional. All Rights Reserved. | Powered by Help | Terms of Use | Privacy Policy and Cookies (UPDATED) | Forum Help | Tips for AskingJive Software Version: 8.0.3.0 , revision: 20160218075410.6eafe9c.release_8.0.3.x senocular.com Why can't the second fundamental theorem of calculus be proved in just two lines? How strange is it (as an undergrad) to email a professor from another institution about possibly working in their lab? Error #1009 Easyfile Depending on the result, you can either run the set up code right away, or set up a different event listener for when the QuickSprite does get added to the stage. The variable s may have been declared, but its value is null (we never set the value, just declared the variable), so calling the toUpperCase method on it is troublesome. Error #1009 As3 Like Show 0 Likes(0) Actions 3. Re: What is TypeError: Error #1009: Cannot access a property or method of a null object reference. his explanation Now, common sense also plays into this. NOTE: MP01, MP02... Typeerror Error #1009 As3 Step 3: Start Tracing If you’ve located the offending line but are still unsure what’s going on, pick apart the line. Which should clue you in that the stage property is null, and now you can go about fixing it. If it were me, I'd fire up the debugger. –prototypical May 7 '13 at 23:01 add a comment| 1 Answer 1 active oldest votes up vote 1 down vote accepted Focusing Code: //Listen for Ball Handler event stage.addEventListener(KeyboardEvent.KEY_DOWN, MoveBallHandler); That line is still looking for the ball when the game is finished. The simple way to solve this kind of problem (#1009) is by adding an ADDED_TO_STAGE event, here's how: package { import ..... public class MyClass extends ..... Typeerror Error #1009 Cannot Access A Property Or Method Of A Null Object Reference. Flash If the Number has a value of 0, then technically it has a value, but testing if (someNumberThatEqualsZero) will evaluate to false. Cannot Access A Property Or Method Of A Null Object Reference. As3 Never miss out on learning about the next big thing.Update me weeklyAdvertisementTranslationsEnvato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this postPowered byAdvertisementWatch anycourse Like Show 0 Likes(0) Actions 4. news share|improve this answer answered Jan 11 '11 at 18:10 user1385191 well I already know which ones they are, The spring and the fall buttons don't work. Forum New Posts FAQ Calendar Community Groups Albums Member List Forum Actions Mark Forums Read Quick Links Today's Posts View Site Leaders Advanced Search Forum Programming [AS3] Error #1009: Cannot access Verify it's on the display list (parent is not null) then remove the object from it's parent directly. Error 1009 Adobe Flash Player All default parameters must be at the end of a parameters list; non-default parameters cannot be listed after a default parameter. If you remove the event listener when the game over screen is triggered your error should go away. Please turn JavaScript back on and reload this page. have a peek at these guys Note that this behavior is new to ActionScript 3.0. It will tell you where the error is. Easyfile Error 1009 Forum Today's Posts FAQ Calendar Forum Actions Mark Forums Read Quick Links View Forum Leaders What's New? Then you may need to get crafty, and read the next step. Examples: function myAddFunction(a:Number, b:Number):Number { return a + b; } myAddFunction(1); // Error #1063 // exactly two arguments are required function myRandomFunction():Number { return Math.floor( 10 * Math.random() ); } myRandomFunction(1); In general this notation works; you can always use if (someSprite.stage != null) if you prefer. Not the answer you're looking for? Typeerror Error #1009 Vmware Switch to another language: Catalan | Basque | Galician | View all Cerrar Sí, quiero conservarla. I hope you are enlightened a bit about how Error 1009 occurs, and how you can debug it. For Numbers you can use the isNaN() function to determine if a valid numeric value is stored in a given variable. In real-life terms, if our glass is empty, then fill it with a tasty beverage before picking it up. check my blog Browse other questions tagged flash actionscript-3 or ask your own question. If you create a function that is used for an event handler, it must be able to accept single Event argument. Zdolshin 22.557 visualizaciones 5:06 شرح حل مشكله التحميل في متجر ابل ورساله الخطأ - Duración: 1:34. محمد حدائدي 21.315 visualizaciones 1:34 Installing HASP Drivers for Local HASP Code - Duración: 3:13. Winter works for some reason. For example, in the following sample where myParent is a Sprite or some other DisplayObjectContainer instance that (supposedly) contains a child Sprite (or some other DisplayObject) called myChild: myParent.removeChild(myChild); this error There is one exception to this rule: event handlers for the Event.REMOVED event when a timeline containing the child display object moves to a frame where the child does not exist. Error 1009 means that you’ve tried to do something with a variable that you assume has a value, but really does not. The error we get is a run-time error, which means we only get it when we run the SWF.
http://degital.net/error-1009/typeerror-error-1009-as3-flash.html
CC-MAIN-2018-22
refinedweb
1,117
64.2
41977/how-to-call-one-lambda-function-using-another Here is how I did it using python boto3. from boto3 import client as boto3_client from datetime import datetime import json lambda_client = boto3_client('lambda') def lambda_handler(event, context): msg = {"key":"new_invocation", "at": datetime.now()} invoke_response = lambda_client.invoke(FunctionName="another_lambda_", InvocationType='Event', Payload=json.dumps(msg)) print(invoke_response) Here is what I found on Amazon ...READ MORE I tried several times trying to pass ...READ MORE In order to create Log Group and ...READ MORE Launch an Amazon RDS MySQL database engine ...READ MORE Check if the FTP ports are enabled ...READ MORE To connect to EC2 instance using Filezilla, ...READ MORE I had a similar problem with trying ...READ MORE You can try out the following steps Post ...READ MORE $ aws lambda put-function-concurrency --function-name my-function --reserved-concurrent-executions ...READ MORE Here is a way but I have ...READ MORE OR
https://www.edureka.co/community/41977/how-to-call-one-lambda-function-using-another
CC-MAIN-2019-30
refinedweb
153
54.39
----------------------------------------------------------------------------- -- | -- Module : Data.List.LCS.HuntSzymanski -- Copyright : (c) Ian Lynagh 2005 -- License : BSD or GPL v2 -- -- Maintainer : igloo@earth.li -- Stability : provisional -- Portability : non-portable (uses STUArray) -- -- This is an implementation of the Hunt-Szymanski LCS algorithm. -- Derived from the description in \"String searching algorithms\" by -- Graham A Stephen, ISBN 981021829X. ----------------------------------------------------------------------------- module Data.List.LCS.HuntSzymanski ( -- * Algorithm -- $algorithm -- * LCS lcs ) where import System.Environment (getArgs) import Data.Array (listArray, (!)) import Data.Array.MArray (MArray, newArray, newArray_) import Data.Array.Base (unsafeRead, unsafeWrite) import Data.Array.ST (STArray, STUArray) import Control.Monad (when) import Control.Monad.ST (ST, runST) import Data.List (groupBy, sort) {- $algorithm We take two sequences, @xs@ and @ys@, of length @\#xs@ and @\#ys@. First we make an array > matchlist[i=0..(#xs-1)] such that > (matchlist[i] = js) => ((j `elem` js) <=> (xs !! i == ys !! j)) > && sort js == reverse js i.e. @matchlist[i]@ is the indices of elements of @ys@ equal to the ith element of @xs@, in descending order. Let @\#xys@ be the minimum of @\#xs@ and @\#ys@. Trivially this is the maximum possible length of the LCS of @xs@ and @ys@. Then we can imagine an array > k[i=0..#xs][l=0..#xys] such that @k[i][l] = j@ where @j@ is the smallest value such that the LCS of @xs[0..i]@ and @ys[0..j]@ has length @l@. We use @\#ys@ to mean there is no such @j@. We will not need to whole array at once, though. Instead we use an array > kk[l=0..#xys] representing a row of @kk@ for a particular @i@. Initially it is for @i = -1@, so @kk[0] = -1@ and @kk[l] = \#ys@ otherwise. As the algorithm progresses we will increase @i@ by one at the outer level and compute the replacement values for @k@'s elements. But we want more than just the length of the LCS, we also want the LCS itself. Another array > revres[l=0..#xys] stores the list of @xs@ indices an LCS of length @l@, if one is known, at @revres[l]@. Now, suppose @kk@ contains @k[i-1]@. We consider each @j@ in @matchlist[i]@ in turn. We find the @l@ such that @k[l-1] < j <= k[l]@. If @j < k[l]@ then we updated @k[l]@ to be @j@ and set @revres[l]@ to be @i:revres[l-1]@. Finding @l@ is basically binary search, but there are some tricks we can do. First, as the @j@s are decreasing the last @l@ we had for this @i@ is an upper bound on this @l@. Second, we use another array > lastl[j=0..#ys-1] to store the @l@ we got last time for this @j@, initially all @1@. As the values in @kk[j]@ monotonically decrease this is a lower bound for @l@. We also test to see whether this old @l@ is still @l@ before we start the binary search. -} -- |The 'lcs' function takes two lists and returns a list with a longest -- common subsequence of the two. lcs :: Ord a => [a] -> [a] -> [a] -- Start off by returning the common prefix lcs [] _ = [] lcs _ [] = [] lcs (c1:c1s) (c2:c2s) | c1 == c2 = c1 : lcs c1s c2s -- Then reverse everything, get the backwards LCS and reverse it lcs s1 s2 = lcs_tail [] (reverse s1) (reverse s2) -- To get the backwards LCS, we again start off by returning the common -- prefix (or suffix, however you want to think of it :-) ) lcs_tail :: Ord a => [a] -> [a] -> [a] -> [a] lcs_tail acc (c1:c1s) (c2:c2s) | c1 == c2 = lcs_tail (c1:acc) c1s c2s lcs_tail acc [] _ = acc lcs_tail acc _ [] = acc -- Then we begin the real algorithm lcs_tail acc s1 s2 = runST (lcs' acc s1 s2) lcs' :: Ord a => [a] -> [a] -> [a] -> ST s [a] lcs' acc xs ys = do let max_xs = length xs max_ys = length ys minmax = max_xs `min` max_ys -- Initialise all the arrays matchlist <- newArray_ (0, max_xs - 1) mk_matchlist matchlist xs ys kk <- newArray (0, minmax) max_ys unsafeWrite kk 0 (-1) lastl <- newArray (0, max_ys - 1) 1 revres <- newArray_ (0, minmax) unsafeWrite revres 0 [] -- Pass the buck to lcs'' to finish the job off is <- lcs'' matchlist lastl kk revres max_xs max_ys minmax -- Convert the list of i indices into the result sequence let axs = listArray (0, max_xs - 1) xs return $ map (axs !) is ++ acc eqFst :: Eq a => (a, b) -> (a, b) -> Bool eqFst (x, _) (y, _) = x == y -- mk_matchlist fills the matchlist array such that if -- xs !! i == ys !! j then (j+1) `elem` matchlist ! i -- and matchlist ! i is decreasing for all i mk_matchlist :: Ord a => STArray s Int [Int] -> [a] -> [a] -> ST s () mk_matchlist matchlist xs ys = do let -- xs' is a list of (string, ids with that string in xs) xs' = map (\sns -> (fst (head sns), map snd sns)) $ groupBy eqFst $ sort $ zip xs [0..] -- ys' is similar, only the ids are reversed ys' = map (\sns -> (fst (head sns), reverse $ map snd sns)) $ groupBy eqFst $ sort $ zip ys [0..] -- add_to_matchlist does all the hardwork add_to_matchlist all_xs@((sx, idsx):xs'') all_ys@((sy, idsy):ys'') = case compare sx sy of -- If we have the same string in xs'' and ys'' then all -- the indices in xs'' must map to the indices in ys'' EQ -> do sequence_ [ unsafeWrite matchlist i idsy | i <- idsx ] add_to_matchlist xs'' ys'' -- If the string in xs'' is smaller then there are no -- corresponding indices in ys so we assign all the xs'' -- indices the empty list LT -> do sequence_ [ unsafeWrite matchlist i [] | i <- idsx ] add_to_matchlist xs'' all_ys -- Otherwise the string appears in ys only, so we ignore it GT -> do add_to_matchlist all_xs ys'' -- If we run out of ys'' altogether then just go through putting -- in [] for the list of indices of each index remaining in xs'' add_to_matchlist ((_, idsx):xs'') [] = do sequence_ [ unsafeWrite matchlist i [] | i <- idsx ] add_to_matchlist xs'' [] -- When we run out of xs'' we are done add_to_matchlist [] _ = return () -- Finally, actually call add_to_matchlist to populate matchlist add_to_matchlist xs' ys' lcs'' :: STArray s Int [Int] -- matchlist -> STUArray s Int Int -- lastl -> STUArray s Int Int -- kk -> STArray s Int [Int] -- revres -> Int -> Int -> Int -> ST s [Int] lcs'' matchlist lastl kk revres max_xs max_ys minmax = do let -- Out the outermost level we loop over the indices i of xs loop_i = sequence_ [ loop_j i | i <- [0..max_xs - 1] ] -- For each i we loop over the matching indices j of elements of ys loop_j i = do js <- unsafeRead matchlist i with_js i js minmax -- Deal with this i and j with_js i (j:js) max_bound = do x0 <- unsafeRead lastl j l <- find_l j x0 max_bound unsafeWrite lastl j l vl <- unsafeRead kk l when (j < vl) $ do unsafeWrite kk l j rs <- unsafeRead revres (l - 1) unsafeWrite revres l (i:rs) with_js i js l with_js _ [] _ = return () -- find_l returns the l such that kk ! (l-1) < j <= kk ! l find_l j x0 z0 = let f x z | x + 1 == z = return z | otherwise = let y = (x + z) `div` 2 in do vy <- unsafeRead kk y if vy < j then f y z else f x y in j `seq` do q1 <- unsafeRead kk x0 if j <= q1 then return x0 else f x0 z0 -- Do the hard work loop_i -- Find where the result starts succ_l <- find_l max_ys 1 (minmax + 1) -- Get the result unsafeRead revres (succ_l - 1)
http://hackage.haskell.org/package/lcs-0.2/docs/src/Data-List-LCS-HuntSzymanski.html
CC-MAIN-2016-36
refinedweb
1,217
65.86
It's very well known concept in OOP and if we have learned any object oriented language we might have learned it in introductory lesson. Here I am documenting some important concepts of Polymorphism which I found useful and informative. In java language, we have two flavor of polymorphism : In java language, we have two flavor of polymorphism : - Compile time polymorphism (static binding or method overloading) Programs are written in such a way, that flow of control is decided in compile time itself. i.e : Using method overloading - compile time polymorphism is achieved. - Method overloading - An object can have more than one method with same name but different signature (Parameter type and number of parameters different). On compile time compiler ensures that which method (Possibly) will be called at execution time. Why "possibly" ? Answer : Because at run time method chosen by compiler may be changed by run time polymorphism. Based on parameter type and number of parameters at compile time compiler ensures that appropriate method will be available at run time but it may change. - Run time polymorphism (dynamic binding or method overriding) Run time polymorphism comes into picture when we use inheritance and there is possibility of parent child relationship in program. - Method overriding : Parent class method can be overridden and at execution time it is decided which method will be called based on type of object that initiated this call. During execution JVM starts to look for the candidate method with the signature as exactly defined during the compiling-time. Actually search for the method to be executed starts from the real Object implementation Class (which can be a subclass of the type-Class) and surf the whole hierarchy up. what is this real Object implementation class ? Answer : Object which initiated the method call not the reference which is pointing to that Object. class Gadget { public void switchon() { System.out.println("Gadget is Switching on!"); } } class Smartphone extends Gadget{ @Override public void switchon() { System.out.println("Smartphone is switching on!"); } } class DemoPersonnel { public void demo(Gadget g) { System.out.println("Demoing a gadget"); } public void demo(Smartphone s) { System.out.println("Demoing a smartphone"); } } public class DT { public static void main(String[] args) { List<Gadget> l = new LinkedList<Gadget>(); l.add(new Gadget()); l.add(new Smartphone()); for (Gadget gadget : l) { gadget.switchon(); } DemoPersonnel p = new DemoPersonnel(); for (Gadget gadget : l) { p.demo(gadget); } } } ----------------------------------------------------------------------------------------- On executing this code : - First for loop prints as follows : Smartphone is switching on! - Second for loop prints as follows : Demoing a gadget Demoing a gadget Analysis : In first for loop : Ist iteration : At compile time gadget.switchon(), since gadget is reference type of Gadget class so compiler ensure that appropriate method(switchon()) is available in that class.It is important to note that at compile time compiler check for method signature in reference type class and at run time switchon() of gadget class is called because reference is pointing to Gaget class object and displays Gadget is Switching on!. 2nd Iteration : At compile time same as what is discussed above(since reference is of type Gadget class ), but at run time since reference is pointing to object of Smartphone so JVM will search for switchon() in Smartphone class and displays Smartphone is switching on!. In second for loop : In both iteration at compile time reference type is of DemoPersonnel class so compiler ensure that demo(Gadget g) method signature is available and at run time in first iteration demo(Gadget g) is called this is fair enough .But in second iteration also demo(Gadget g) is called why?Answer: Because signature of method which was made available by compiler at compile time same for both iteration so demo(Gadget g) is called for 2nd iteration also. Conclusion : The whole concept of polymorphism is based on the fact that the concrete class is only known at runtime but not at compile time. This of course means that the compiler must ensure that the methods that are called on a reference will be available on the referenced object at runtime. The only methods for which this holds true are the methods of the class for which the variable was declared (including all inherited methods from the super classes). Reference : polymorphism use case Cheers !! Nikhil
http://www.devinline.com/2013/07/
CC-MAIN-2019-13
refinedweb
709
52.49
A company file is where you store your company’s records in QuickBooks, and it’s the first thing you need to work on in the program. You can create a company file from scratch or convert records previously kept in Quicken, but the most agreeable approach is to use a file that someone else created. If you’ve worked with an accountant to set up your company, she might provide you with a company file configured precisely for your business so that you can hit the ground running. If you must create your own company file, this chapter tells you how to use the QuickBooks EasyStep Interview to get started, and it points you to the other chapters in this book that tell you how to finish the job. If you already have a company file, you’ll learn how to open it and modify basic company information. Here are the easiest methods for opening QuickBooks: Desktop icon. If you requested during installation that QuickBooks create a desktop shortcut, double-click that shortcut to launch QuickBooks. Quick Launch toolbar. The fastest way to open QuickBooks is to click its icon on the toolbar (Figure 1-1). If you have a QuickBooks desktop shortcut, right-drag (that’s dragging while holding down the right mouse button) the desktop shortcut onto the Quick Launch toolbar and then choose Copy Here to create a second shortcut on the toolbar. (If you’re trying to clean up your desktop, choose Move Here to move the desktop shortcut to the Quick Launch toolbar.) You can also use the right-drag technique to copy or move a shortcut in Windows Explorer or from the Start menu. Programs menu. Without a desktop icon, you can launch QuickBooks from the Windows Start menu. Click Start, and then choose Programs → QuickBooks → QuickBooks Pro 2006 (or QuickBooks Premier 2006). The first time you launch QuickBooks, you’re greeted by the “Welcome to QuickBooks” window. Later, if you close a company file, the No Company Open window appears, as shown in Figure 1-2. These two windows are nearly—but not quite—the same. The rest of this chapter tells you when and how to use each one. You still have to create or open a company file the first time you launch QuickBooks. But after you’ve opened a company file in one session, QuickBooks kicks off your next session by opening the same company file. If you use only one company file, you might never have to actively open a QuickBooks file again. Keeping books requires accuracy, attention to detail, and persistence, hence the customary image of spectacled accountants hunched over ledgers. QuickBooks can help you keep your books without ruining your vision or your posture—as long as you start your QuickBooks company file with good information. The EasyStep Interview tries to make creating a company file as painless as possible, but the process isn’t pain free. Indeed, the EasyStep Interview is much like a family reunion, where you’re asked a lot of questions that you don’t want to answer. Unlike the reunion, however, you can skip parts of the Interview or return to it when you’re better prepared for the interrogation. In QuickBooks 2006, the Interview is short and sweet. All it wants to know is some company information, the industry you’re in, and the features you want to use. The Interview sets your preferences and creates a few accounts, but you have to do the bulk of the work yourself later. For example, the company file that EasyStep Interview creates doesn’t even know what tax form you use to file your business tax return. You must fill in this information in the Company Information dialog box and slog through individually assigning each account to a tax line. If you’ve just started a business and want to inaugurate your books with QuickBooks, your prep work will be a snap. On the other hand, if you have existing books for your business, you have a few small tasks to complete before you jump into QuickBooks’ setup. Whether your books are paper ledgers or electronic files in another program, gather your company information before you open QuickBooks. Then, you can hunker down in front of your computer and crank out a company file in record time. Here’s a guide to what you need to create your company file in QuickBooks. To keep your entire financial history at your fingertips, you need every transaction and speck of financial information in your QuickBooks company file. But you know that you have better things to do than enter years worth of checks, invoices, and deposits, so the comprehensive approach is practical only if you started your company quite recently. The more realistic approach is to enter your financial state as of a specific date (ideally the beginning of a fiscal year) and from then on, add all new transactions in QuickBooks. In QuickBooks, the date you choose is called the start date and you shouldn’t choose it arbitrarily. Here are your start date options and the ramifications of each: The first day of the fiscal year. If you’re setting up QuickBooks during the first half of the year, bite the bullet and choose the first day of your company’s fiscal year as the QuickBooks start date. Yes, you have to enter checks, credit card charges, invoices, and other transactions that occurred since the beginning of the year, but that won’t take as much time as you think. You’ll regain those hours when tax time rolls around and you nimbly generate the reports you need to complete your tax returns. During the second half of the year, the best approach is to be patient and postpone your QuickBooks setup until the next fiscal year. Intuit releases its new versions in November for just that reason. The first day of a fiscal period. The next best start date is the first day of a fiscal quarter (or fiscal month at the very least). Waiting until next year isn’t always an option, particularly if your old accounting system vendor wants a truckload of cash for an upgrade. Starting in the middle of a fiscal year makes the entire year’s accounting more difficult. Even if you fill in year-to-date values for all your accounts, since your company file doesn’t contain a full year’s worth of detail, you’ll have to switch between QuickBooks and your old filing cabinets to prepare your tax returns and look up any financial information. Starting at the beginning of a fiscal period mitigates this hassle but doesn’t eliminate it. Unless you begin using QuickBooks when you start your business, you need to know your account balances as of the start date to get things rolling. For example, if your checking account has $342 at the end of the year, that value feeds into QuickBooks during setup. Here are the balances you need to know and where you can find them in your records: Cash balances. For each bank account you use in your business (checking, savings, money market, petty cash, and so on), find the bank statements with statement dates as close to but earlier than the start date for your QuickBooks file. Gather deposit slips and your checkbook register to identify the transactions that haven’t yet cleared in your bank accounts. You’ll need them to enter transactions, as described in the upcoming chapters. If you have petty cash lying around, count it and use that number to set up your petty cash account. Customer balances. If customers owe you money, pull the paper copy of every unpaid invoice or statement out of your filing cabinet. If you didn’t keep copies, you’ll have to figure out how much you sold in services and products, the discounts you applied, what you charged for shipping and other charges, and the amount of sales tax. As a last resort, you can ask your customers for copies of the invoices they haven’t paid or create invoices in QuickBooks to match the payments you receive. QuickBooks needs this information to calculate your Accounts Receivable balance. Vendor balances. If your company considers handing out cash more painful than data entry, find the bills you haven’t paid and get ready to enter them in QuickBooks. If you’d rather reduce the transactions you have to enter, pay those outstanding bills. Asset values. When you own assets such as buildings or equipment, the value of those assets depreciates over time. If you’ve filed a tax return for your company, you can find asset values and accumulated depreciation on your most recent tax return (yet another reason to begin using QuickBooks at the beginning of a year). If you haven’t filed a tax return for your company, the asset value is typically the price you paid for the asset, and you won’t have any depreciation until you file that first return. Liability balances. Unpaid vendor bills that you enter in QuickBooks generate the balance for your Accounts Payable liability account. However, you must find the current balances you owe on any loans or mortgages. Inventory. For each product you stock in inventory, you need to know how many items you had in stock as of the start date, how much you paid for them, and what you expect to sell them for. Payroll. Payroll services offer great value for the money, which you’ll grow to appreciate as you collect the information you need for payroll (including salary and wages, tax deductions, benefits, pensions, 401(k) deductions, and other stray payroll deductions you might have). You also need to know who receives withholdings, such as tax agencies or the company handling your 401(k) plan. Oh yes, you need payroll details for each employee. Chapter 11 explains the ins and outs of payroll using QuickBooks. If you’re going back to the beginning of the fiscal year for the start date, you need every transaction that has occurred since the beginning of the year: sales you’ve made, expenses you’ve incurred, payroll and tax transactions, and so on, to reestablish your asset, liability, equity, income, and expense accounts. So, dig that information out of your existing accounting system (or shoebox). Federal tax returns and payroll tax returns (federal and state) include all sorts of information that QuickBooks setup wants to know, like your federal tax ID number. And the balance sheet that goes with the return is a great starting point for your account balances. You can create a brand-new company file from either the “Welcome to QuickBooks” window or the No Company Open window by clicking “Create a new company.” Although the wizard doesn’t provide hints about which step comes next, the interview covers the basics for creating and customizing a company file to fit your business. Click Next or Back to move from screen to screen. The Get Started screen assures you that you’ll be ready to start using QuickBooks in about 30 minutes. Start by choosing one of the following three buttons: Convert Data. If you have existing records in Quicken or Peachtree, you’re in luck. Converting your books is easier than starting from scratch. Skip Interview. If you’re something of a QuickBooks expert, this option lets you set up a company file without a safety net. It opens the bare-bones Creating New Company window, followed by a few screens of data entry. If you need help during the process, you can always click the Help button. Start Interview. If you don’t fit into either of the previous categories, this one’s for you. The first setup screen asks you for the basic 411 about your company, as you can see in Figure 1-3. If any of the fields are confusing, try clicking “Get answers” in the upper-right corner. Click Next when you’re done. The second screen in the EasyStep Interview asks you to set a password for the administrator login. The administrator can do absolutely anything in your company file: set up other users, log in as other users, and access any area of the company files. Surprisingly, the administrator password is optional. QuickBooks lets you click Next and skip right over it, but this is no time for shortcuts. Type the password you want to use in both the “Administrator password” and “Retype password” boxes. Keep the login name and password in a safe but memorable place; see the box below for more password advice. After you set the administrator password and click Next, the Create Your Company File screen appears. If you’re new to QuickBooks, the first screen includes a link “Where should I save my company file?”, which opens a QuickBooks Help window that explains the pros and cons of storing files in different places (Section 7.1). QuickBooks veterans can click Next to specify the file name and location. QuickBooks opens the “Filename for New Company” dialog box, which is really just a Save File dialog box. Initially, it sets the “Save as” type to QuickBooks Files and the location to Program Files → QuickBooks → Company Files. But you’re free to change the name or navigate to a different folder for saving. Here are some guidelines: QuickBooks fills in the “File name” field with the company name that you entered earlier in the Interview. Keep this name or type one that is shorter or that better identifies the company’s records within. Instead of the Program Files → QuickBooks folder, consider storing your company file in a folder with the rest of your company data so that it gets backed up along with everything else. (Typically, backup programs skip the Program Files folder.) For example, you could create a Company Files folder in My Documents, if you’re the only person who uses QuickBooks. When you click Save, QuickBooks can take a minute or so to create the new file, and, in the meantime, the “Creating new company file” message box appears. When the company file is ready, the Easy Step Interview displays the Customizing QuickBooks for your business screen. Click Next to dig in. The next several screens in the EasyStep Interview ask you about your business to decide which features to turn on, what to include on your QuickBooks Home page, and so on. Unlike its counterpart in QuickBooks 2005, this interview sticks to the basics, so you’ll have more setup to do later. As you step through the screens in this section, make a list of the features you’re turning on (and the corresponding page number in this book) for reference. Here are some guidelines for answering the questions on the screens that follow: Choose carefully on the “Select your industry” screen. As shown in Figure 1-4, the list of industries is robust, so chances are good you’ll find one that’s close to what your organization does. Based on choice, QuickBooks recommends accounts and preferences. If QuickBooks makes assumptions that you don’t like, you can change preferences later (Section 6.1). The “What do you sell?” screen is where you tell QuickBooks whether you sell services, products, or both. When you choose one of these options, QuickBooks knows which types of income accounts you need. The interview asks about whether you track inventory later. If your business sells things, you see the “Do you sell products online?” screen. Whether you want to sell online or not, you can bypass Intuit’s marketing pitch for their add-on sales services by selecting the “I don’t sell online and I am not interested in doing so” option. The “Do you charge sales tax?” screen contains only Yes or No options. If you’re one of the unfortunate souls who must navigate the rocky shoals of sales tax, select Yes. If you don’t charge sales tax, select No and breathe a sigh of relief. For detailed instructions on sales taxes in QuickBooks, see Section 4.6. On the “Do you want to create estimates in QuickBooks?” screen, select Yes or No to turn the estimate feature on or off. If you prepare quotes, bids, or estimates for your customers and want to do so in QuickBooks (Section 8.8.1), select Yes. The “Using sales receipts in QuickBooks” screen is targeted to retailers who provide sales receipts when customers purchase or pick up products and pay in full. Simply select Yes if you want to create sales receipts in QuickBooks (see Section 8.1.1). “Using statements in QuickBooks” is where you tell the program whether you generate statements to send to your customers (Section 8.1.3). For example, your wine-of-the-month club might send monthly statements to your members. Or, a consultant could send invoices for work performed and then send a statement that summarizes the fees, payments, and outstanding balance. The “Using progress invoicing” screen asks whether you invoice customers based on the percentage you’ve completed on a job. To learn why (and how) you might use this feature, see Section 8.9. “Managing bills you owe” asks whether you plan to write checks to pay bills immediately (No) or enter bills in QuickBooks and then pay them later (Yes). You can read about bill and payment preferences on Section 6.10. “Tracking inventory in QuickBooks” is the screen where you tell QuickBooks whether you keep track of the products you have in stock. This screen provides a few examples of when to track or bypass inventory, but Section 4.3 includes more guidelines for whether tracking inventory makes sense for your business. The “Do you accept credit cards?” screen lets you tell QuickBooks whether you take credit cards for payment (as well as whether you want to get a sales pitch about Intuit’s card). If you bill by the hour, “Tracking time in QuickBooks” is ideal. Select Yes to track the hours that people work and create invoices for their time. You can turn time tracking on in the Interview, but you’ll need the instructions on Section 17.1.1 to set it up properly. “Do you have employees?” is where you specify whether you need QuickBooks payroll and 1099 features. If you use non-Intuit services to run payroll or generate contractors’ 1099s, select No. When you click Next on the “Do you have employees?” screen, you see the “Using accounts in QuickBooks” screen and the progress bar indicating that you’re about three-quarters through the interview. With a few more steps, you’ll have your start date and most of the accounts you want to use. Here are the last things to set up: The “Enter your start date” screen offers a summary of what you learned about starting dates on Section 1.3.1. If you’ve already decided which start date to use, simply type or choose that date in the “Start date” box and click Next. The “Add your bank account” screen asks if you’d like to add an existing bank account. Select Yes if you’d like QuickBooks to walk you through setting up a bank account. If you’re comfortable setting up the account on your own, select “No, I’ll add a bank account later.” If you select Yes, the next screen asks for the bank account name, bank account number, and when you opened the account. Click Next again and another screen asks for the statement ending date and ending balance prior to your company file start date. After you create that account, you can add additional bank accounts, or select No to add the rest after you finish the interview. The “Review expense accounts” screen lists the expense accounts typically used by companies in your selected industry, as shown in Figure 1-5. You can’t change these accounts now, but if you need to, make a note to edit your Chart of Accounts once you complete the interview (Section 2.2.1). The “Review income accounts” screen mimics the expense accounts screen. You’ll see a short list of income accounts typically used by companies in your industry. Select Yes to use the accounts that the program suggests as a start. If you want to create your income accounts from scratch, select “No, I will create my own accounts later.” When you click Next, you’ll see a bright yellow Congratulations! Click Finish, and you end up in the QuickBooks Learning Center, which contains several tutorials about the remaining setup options. If you made a list of your interview choices, you can start setting up those features now, or you can wait until you need them. The EasyStep Interview in QuickBooks 2006 doesn’t tell you what to do next. Because the interview sets up only a bare framework, you may be looking for guidance. Look no further than the book in your hands. Here are the ways you can flesh out your company file: Specify the first month of your fiscal year and tax year. See Section 1.9. Specify the income tax form you use. See Section 1.9. Set up your users and passwords. See Section 23.1.1. Review and/or change the preferences that QuickBooks set. See Section 6.1. Set up or edit the accounts in your Chart of Accounts. If you set up accounts in the EasyStep Interview, you must edit them to assign them to the tax lines on your tax form. See Section 2.3.2. Create a journal entry to specify account opening balances. See Section 13.3. Create items for the products and services you sell. See Section 4.1. Set up sales tax codes. See Section 4.5.4. Set up your 1099 tracking. See Section 6.17. Sign up for Intuit Payroll Service if you want help with payroll. See Section 11.1. Enter your historical transactions. For invoices, see Section 8.1.3; for bills, see Section 10.2; for payroll, see Section 11.4. Create a backup copy. See Section 7.2. Customize your forms. See Section 22.3. “Open an existing company” appears in both the “Welcome to QuickBooks” window and the No Company Open window. When you click this button, the “Open a Company” dialog box appears, and you can double-click the name of the company file you want to open. However, the fastest route to opening your company file (in the No Company Open window) is by double-clicking one of the file names in the list of recently opened files, as shown in Figure 1-6. If you’re like many small business owners, your accountant probably recommended that you make the leap from tracking your business in Quicken to using QuickBooks. Quicken doesn’t report your business performance in the way that most accountants want to see, nor does it store your business transactions the way QuickBooks does. If you want the conversion to proceed as smoothly as possible, do some cleanup in your Quicken file first. For example, you have to record overdue scheduled transactions and send online payments before you convert your Quicken file. Make sure that customer names are consistent and unique. QuickBooks doesn’t support repeating online payments, so you must also send an instruction in Quicken to delete any repeating online payments you’ve set up. In addition, you need complete reports of your past payroll because Quicken payroll transactions don’t convert to QuickBooks. Intuit has published a detailed guide to help you prepare for a Quicken conversion. The easiest way to locate this document is to point your browser to, which displays a section for searching the knowledge base. In the Enter search terms box, type Quicken convert to find topics that include links to the Quicken to QuickBooks Conversion Guide. When your Quicken file is ready for QuickBooks prime time, you have two options in QuickBooks: Choose File → New. In the EasyStep Interview window, click Convert Data and choose Quicken. Choose File → Utilities → Convert → From Quicken. In the No Company Open window, you’ll see “Restore a backup file.” Backup files are the answer to the adrenaline rush you get when you do something incredibly stupid with your company file or when your hard drive crashes. To learn how to create backup files in the first place, as well as how to restore them, see Section 7.2. In the EasyStep Interview, QuickBooks extracts the basic information about your company in small chunks spread over several screens. After your company file exists, you can edit any of this information in one dialog box, as illustrated in Figure 1-7. Remember, the legal name and address are the ones you use on your federal and state tax forms. To open this dialog box, choose Company → Company Information. No credit card required
https://www.oreilly.com/library/view/quickbooks-2006-the/0596101848/ch01.html
CC-MAIN-2019-39
refinedweb
4,168
70.84
Understanding React Hooks React Hooks are a way for your function components to “hook” into React’s lifecycle and state. They were introduced in React 16.8.0. Previously, only Class based components were able to use React’s lifecycle and state. Aside from enabling Function components to do this, Hooks make it incredibly easy to reuse stateful logic between components. If you are moving to Hooks for the first time, the change can be a little jarring. This chapter is here to help you understand how they work and how to think about them. We want to help you transition from the mental model of Class components to function components with React Hooks. Here is what we’ll be covering: - A quick refresher on the lifecycle of Class components - An overview of the lifecycle of Function components with Hooks - A good mental model to understand React Hooks in Function components - A subtle difference between Class and Function components Note that, this chapter does not cover specific React Hooks in detail, the React Docs are a great place for that. Let’s get started. The React Class Component Lifecycle If you are used to using React Class components, you’ll be familiar with some of the main lifecycle methods. constructor render componentDidMount componentDidUpdate` componentWillUnmount - etc. You can view the above in detail here. Let’s understand this quickly with an example. Say you have a component called Hello: class Hello extends React.Component { constructor(props) { super(props); } componentDidMount() { } componentDidUpdate() { } componentWillUnmount() { } render() { return ( <div> <h1>Hello, world!</h1> </div> ); } } This is roughly what React does when creating the Hello component. Note that, this is a simplified model and it isn’t exactly what happens behind the scenes. - React will create a new instance of your component. const HelloInstance = new Hello(someProps); This calls your component’s constructor(someProps). It’ll then call HelloInstance.render(), to render it for the first time. Next it’ll call HelloInstance.componentDidMount(). Here you can run any API calls and call setStateto update your component. Calling setStatewill in turn cause React to call HelloInstance.render(). This is also the case if React wants to re-render the component (maybe because its parent is being re-rendered). After the updated render, React will call HelloInstance.componentDidUpdate(). - Finally, when it’s time to remove your component (maybe the user navigates to a different screen), React will call HelloInstance.componentWillUnmount(). The key thing to understand about the lifecycle is that your Class component is instantiated ONCE and the various lifecycle methods are then called on the SAME instance. This means that you can save some sort of “state” locally in your class instance using class variables. This has some interesting implications that we’ll talk about below. But for now, let’s look at the flow for a Function component. The React Function Component Lifecycle Let’s start with a basic React Function component and look at how React renders it. function Hello(props) { return ( <div> <h1>Hello, world!</h1> </div> ); } React will render this by simply running the function! Hello(someProps); And if it needs to be re-rendered, React will run your function again! Again we are using a simplified React model but the concept is straightforward. For a Function component, React simply runs your function every time it needs to render or re-render it. You’ll notice that our simple Function component has no control over itself. Also, we can’t really do anything with regards to the React render lifecycle like our Class component above. This is where Hooks come in! Adding React Hooks React Hooks allows Function components to “hook” into the React state and lifecycle. Let’s look at an example. function Hello(props) { const [ stateVariable, setStateVariable ] = useState(0); useEffect(() => { console.log('mount and update'); return () => { console.log('cleanup'); }; }); return ( <div> <h1>Hello, world!</h1> </div> ); } We are using two Hooks here; useState and useEffect. One tells React to store some state for us. While the other tells React to call us during the render lifecycle. When our component gets rendered, we tell React that we want to store something in the state by calling useState(<VARIABLE>). React gives us back [ stateVariable, setStateVariable], where stateVariableis the current value of this variable in the state. And setStateVariableis a function that we can call to set the new value of this variable. You can read about how useState works here. Next we the useEffectHook. We pass in a function that we want React to run every time our component gets rendered or updated. This function can also return a function that’ll get called when our component needs to cleanup the old render. So if React renders our component, and we call setStateVariableat some point, React will need to re-render it. Here is roughly what happens: // React renders the component Hello(someProps); // Console shows: mount and update ... // React re-renders the component // Console shows: cleanup Hello(someProps); // Console shows: mount and update And finally when your component is unmounted or removed, React will call your cleanup function once again. You’ll notice that the lifecycle flow here is not exactly the same as before. And that the useEffect Hook is run (and cleans up) on every render. This is by design. The main change you need to make mentally is that unlike Class components, Function components are run on every single render. And since they are just simple functions, they internally have no state of their own. As an aside, you can optionally make useEffect call only on the initial mount and final unmount by passing in an empty array ( []) as another argument. useEffect(() => { console.log('mount'); return () => { console.log('will unmount'); } }, []); You can read about useEffect in detail here. React Hooks Mental Model So when you are thinking about Function components with Hooks, they are very simple in that they are rerun every time. As you are looking at your code, imagine that it is run in order every single time. And since there is no local state for your functions, the values available are only what React has stored in its state. As opposed to Class components, where specific methods in your class are called upon render. Additionally, you might have stored some state locally in a state variable. This means that as you are debugging your code, you have to keep in mind what the current value of a local state variable is. This slight difference in local state can introduce some very subtle bugs in the Class component version that is worth understanding in detail. On the other hand thanks to JavaScript Closures, Function components have a more straightforward execution model. Let’s look at this next. Subtle Differences Between Class & Function Components This section is based on a great post by Dan Abramov, title “How Are Function Components Different from Classes?” that we recommend you read. This isn’t specifically related to React Hooks. But we’ll go over the key takeaway from that post because it’ll help you make the transition from the Class components mental model to the Function components one. This is something you’ll need to do as you start using React Hooks. Using the example from Dan’s post; let’s compare similar versions of the same component first as a Class. class ProfilePage extends React.Component { showMessage = () => { alert('Followed ' + this.props.user); }; handleClick = () => { setTimeout(this.showMessage, 3000); }; render() { return <button onClick={this.handleClick}>Follow</button>; } } And now as a Function component. function ProfilePage(props) { const showMessage = () => { alert('Followed ' + props.user); }; const handleClick = () => { setTimeout(showMessage, 3000); }; return ( <button onClick={handleClick}>Follow</button> ); } Take a second to understand what the component does. Imagine that instead of the setTimeout call, we are doing some sort of an API call. Both these versions are doing pretty much the same thing. However, the Class version is buggy in a very subtle way. Dan has a demo version of this code for you to try out. Simply click the follow button, try changing the selected profile within 3 seconds and check out what is alerted. Here is the bug in the Class version. If you click the button and this.props.user changes before 3 seconds, then the alerted message is the new user! This isn’t surprising if you’ve followed along this chapter so far. React is using the SAME instance of your Class component between re-renders. Meaning that within our code the this object refers to that same instance. So conceptually React changes the ProfilePage instance prop by doing something like this: // Create an instance const ProfilePageInstance = new ProfilePage({ user: "First User" }); // First render ProfilePageInstance.render(); // Button click this.handleClick(); // Timer is started // Update prop ProfilePageInstance.props.user = "New User"; // Re-render ProfilePageInstance.render(); // Timer completes // where this <=> ProfilePageInstance alert('Followed ' + this.props.user); So when the alert is run, this.props.user is New User instead! Let’s look at how the Functional version handles this. // First render ProfilePage({ user: "First User" }); // Button click handleClick(); // Timer is started // Re-render with updated props ProfilePage({ user: "New User" }); // Timer completes // from the first ProfilePage() call scope alert('Followed ' + props.user); Here is the critical difference, the alert call here is from the scope of the first ProfilePage() call scope. This is happens thanks to JavaScript Closures. Since there is no “instance” here, your code is just a regular JavaScript function and is scoped to where it was run. The above pattern is not specific to React Hooks, it’s just how JavaScript functions work. However, if you’ve been using Class components so far and are transitioning to using React Hooks; we strongly encourage you to really understand this pattern. Summary This allows us to think of our components just as regular JavaScript functions. No special order of our lifecycle methods being called and no local state to track. Here’s the key takeaway: “React simply calls your function components over and over again when it needs to render it. You’ll need to use React Hooks to store state and plug into the React render lifecycle. And thanks to JavaScript Closures, your variables are scoped to the specific function call.” We hope this chapter helps you create a better mental model for understanding Function components with React Hooks. Leave us a comment in the discussion thread below if you want us to expand on something further. For help and discussionComments on this chapter
https://serverless-stack.com/chapters/understanding-react-hooks.html
CC-MAIN-2021-04
refinedweb
1,741
57.77
10 April 2009 19:44 [Source: ICIS news] TORONTO (ICIS news)--US refining major Valero has taken a stake in Terrabon, a privately held Houston-based renewable fuels firm that aims to convert landfill garbage into fuel, Terrabon said on Friday. Terrabon would use the money to speed up the commercial development of its acid formation technology, it said. The fuel it was developing was not ethanol but had a higher energy value than ethanol and could be blended directly with regular gasoline, it said. Chief financial officer Malcolm McNeill said that Terrabon could not currently disclose how much money Valero invested, but expected to issue a press release on that later. McNeill said Terrabon was planning a project in ?xml:namespace> The project would cost about $30m (€23m), with about $12m-15m coming from a government grant Terrabon was applying for, he said. The company already had a test facility in Bryan, Texas, which was currently in its start-up phase, he added. In a separate statement, Terrabon CEO Gary Luce commented: "Our strategic partnership with Valero is a big step in helping our country meet President Obama's goal of producing 36bn gallons [136 litres] of renewable fuels by 2022." Valero last month entered the biofuels production market when it won a bid to buy ethanol plants with a combined capacity of 780m gal/year from VeraSun, a ($1 = €0.76) Bookmark Simon Robinson's Big Biofuels
http://www.icis.com/Articles/2009/04/10/9207656/us-refiner-valero-takes-stake-in-biofuels-firm-terrabon.html
CC-MAIN-2014-52
refinedweb
239
56.69
I am trying to get ViewVC working but I believe I have something wrong in my config/build/installation of the Subversion python bindings. When I click on a repository listed on the from the on my server I receive the following error trace: ###### An Exception Has Occurred Python Traceback Traceback (most recent call last): File "/usr/local/viewvc/lib/viewvc.py", line 3629, in main request.run_viewvc() File "/usr/local/viewvc/lib/viewvc.py", line 253, in run_viewvc import vclib.svn File "/usr/local/viewvc/lib/vclib/svn/__init__.py", line 25, in ? from svn import fs, repos, core, delta File "/usr/local/lib/svn-python/svn/fs.py", line 19, in ? from libsvn.fs import * File "/usr/local/lib/svn-python/libsvn/fs.py", line 7, in ? import _fs ImportError: /usr/local/lib/svn-python/libsvn/_fs.so: undefined symbol: apr_hash_set #### Note: after installing the python bindings into the python module directory, python initially complained that it coudn't find '_fs'. To remedy this, I made symbolic links in 'libsvn' to all the modules with underscore prefixes but not extensions (such as: _core, _fs, _delta, etc.). My system configuration is as follows: Apache 2.0.59 (built from source) Subversion 1.4.2 (built from source) Swig 1.3.31 (build from source) ViewVC 1.0.3 My 'configure' command for Subversion was as follows: ./configure --without-berkeley-db \ --with-apxs=/usr/local/apache2/bin/apxs \ --with-apr=/usr/local/apache2 \ --with-apr-util=/usr/local/apache2 \ --with-ssl \ --with-zlib \ --with-swig I took the following steps to install: make sudo make install make swig-py ## BTW: 'make check-swig-py' fails with a python error ## of "ImportError: No module named _core" sudo make install-swig-py sudo cp -R /usr/local/lib/svn-python/* /usr/lib/python # Added symlinks in 'libsvn' similar to 'ln -s _core _core.so' Any ideas? Anyone seen this before? Christof Hamm --------------------------------------------------------------------- To unsubscribe, e-mail: users-unsubscribe@subversion.tigris.org For additional commands, e-mail: users-help@subversion.tigris.org Received on Wed Jan 24 23:35:20 2007 This is an archived mail posted to the Subversion Users mailing list.
https://svn.haxx.se/users/archive-2007-01/0969.shtml
CC-MAIN-2020-05
refinedweb
360
52.26
I defined a function inside of a function in a program (Python): def func1: x = 5 def func2(y): return x*y x = 4 print func2(5) First of all: you're being too lazy. Before you write code here, at least feed it to an interpreter or compiler for the language in question to weed out the obvious problems. In this case, there are two: ()on the definition of func1. func2being undefined when it is called. So let's try #!/usr/bin/env python def func1(): x = 5 def func2(y): #x = x + 1 # invalid: "x referenced before assignment" return x*y # not invalid! reference to x is fine global func3 func3 = func2 #print func3(5) # undefined func1() print func3(5) #print func2(5) # undefined Three lines are commented; they produce errors when uncommented. As you can see, Python definitions, of both variables and functions, are local by default: when defined within a function, they only apply within that function, and cannot be used elsewhere. Variables defined outside a function can be used inside the function. However, they can only be read, not written. This explains why we can use x inside func2 but cannot assign to it; when x = x + 1 is uncommented, it is interpreted as applying to a different x variable inside func2, which is why we'll get an error complaining that it is used uninitialized. In addition, Python has global variables, which can be used anywhere in the program; such variables must be marked global explicitly. This is very similar to PHP (in which variables can also be marked as global) and fairly similar to many other languages, such as C (which has no global, but the similar extern). What you're trying to do with your code is have a function ( func2) use a variable ( x) defined in the context of its definition, then call it outside the context where x is defined and still have it work. Functions that can do this are known as closures. We've just seen that Python only has partial support for closures: the function can read such variables, but cannot modify them. This is already better than many other languages. However, a full closure can also modify such variables. For instance, the following is valid Perl code: #!/usr/bin/env perl use strict; use warnings; my $func3 = sub { 1 }; my $func1 = sub { my $x = 5; my $func2 = sub { my ($y) = @_; ++$x; $x*$y }; $func3 = $func2 }; #&$func2(5); # won't compile: func2 is undefined print &$func3(5), "\n"; # prints 1 &$func1(); print &$func3(5), "\n"; # prints 30 print &$func3(5), "\n"; # prints 35 Full closure support is traditionally associated with dynamic scoping (i.e. making definitions executable statements, evaluated at run time). This is because it was introduced by Lisp, which was dynamically scoped, and support for it is rare in languages that use static (lexical) scoping (in which the scope of definitions is determined at compile time, not at run time). But all of the variables and function definitions in this Perl code are statically scoped.
https://codedump.io/share/UPpi2Anv9A25/1/defining-functions-inside-of-other-functions
CC-MAIN-2017-09
refinedweb
511
66.88
From the type name, one may be fooled into thinking that a char variable always represents a character — an ASCII character to be precise. However, char in C/C++ is not a "character type" but instead an "integer type". Indeed, the char type is simply an 8-bit integer type on virtually every platform (including all mobile phones and desktop computers). The C standard does not define whether char is a signed or unsigned type. Even though the standard defines char, signed char and unsigned char as three different types, it requires C compilers to treat the char type as either signed char or unsigned char (see section 6.2.5, item 15 of the C11 standard). Some compilers allow you to choose what is best for your project. For instance, gcc can be executed with the -fsigned-char or -funsigned-char flags to have char be interpreted as signed char or unsigned char respectively. This flexible signedness of the char type paves the way for many dangerous pitfalls. For example, the following code will run in finite time if char is unsigned, but will loop forever if char is signed: #include <stdio.h> int main() { for (char c = 0; c < 200; ++c) { printf("%c\n", c); } return 0; } If char is an unsigned type, the program will finish because an unsigned 8-bit integer can store any values ranging from 0 to 255. However, a signed 8-bit integer can only hold values ranging from -128 to 127, i.e., it can never be larger than or equal to 200 and therefore the condition on the for loop will never evaluate to false. To be precise, when evaluating the condition c < 200 with char being a signed type, c is first promoted to int and then compared with the (int) value 200; since int has at least 16 bits of length, it can represent 200, but even if we promote c to int, the resulting value will never exceed 127. Every time c becomes 127, the update statement ++c will make it overflow to -128 and so on. Below is also a classic example of how an incorrect assumption of the signedness property of the char type can lead to unwanted program behavior: #include <stdio.h> int main() { /* WRONG: getchar() returns int, not char! */ char c = getchar(); while (c != EOF) { printf("%c\n", c); c = getchar(); } return 0; } This program will never stop consuming input if char is unsigned. This happens because EOF is defined as the integer value -1 (on stdio.h), a value that an unsigned char cannot represent. Specifically, in the two's complement representation of integer values used by modern computers, -1 is 0xffffffff (assuming int has 32 bits of length, but the same argument follows on systems where int has 16 bits of length). When this value is written on an unsigned char, it is truncated to a one-byte integer value 0xff. This is where things go bad: when comparing c with EOF on line 8 of the code above, c is promoted to int, and its value 0xff is converted to 0x000000ff, which is 255 in decimal notation. So the condition c != EOF will always be true, even when getchar returns EOF to indicate an error or the end of input. This is how the program above should have been written instead: #include <stdio.h> int main() { /* CORRECT: getchar() returns int! */ int i = getchar(); while (i != EOF) { char c = i; printf("%c\n", c); i = getchar(); } return 0; } Notice how, on our very first sample code above, we used the post-increment operator on a variable of type char. In general, since char is an arithmetic type, all statements on the code below are valid: int main() { /* * since c is used here explicitly as a numeric type, * it should have been declared as either signed char * or unsigned char (alternatively, int8_t or uint8_t) */ char c; /* assignment statements */ c = 35; c = '#'; /* shortcut assignments */ c *= 2; c /= 3; c %= 25; /* increment and decrement operators */ c++; --c; /* arithmetic expressions */ c = 'a' + '#' - 20; c = 2*'c' + '#'/7; return 0; } It is important to keep in mind that as char is an integer type, it can overflow (as was the case in our first example). To have your code always behave the same way regardless of which compiler is used, consider using signed/unsigned char instead of plain char. Whenever you wish to perform arithmetic operations using 8-bit integers, use the int8_t and uint8_t types instead of a char type. These 8-bit integer types are defined on stdint.h. As the code just shown illustrates, an expression such as '#' represents the (integer) value of the ASCII code assigned to this symbol. Since the code assigned to '#' is 35, the two assignment statements on the program above are equivalent to each other because expressions like '#' are replaced with their associated integer values when a program is compiled. Therefore, a char type is no more similar to a "character" than any other integer type. It is merely the smallest integer type which can represent any of the 128 characters from the ASCII standard. Playing safe with char variables If you wish to avoid trouble when dealing with characters through variables of type char, do not compare them with integer values; instead, compare them only with ASCII characters enclosed in single quotes since these comparisons are guaranteed to be valid. Additionally, it is always better to use portable functions such as isalpha or isdigit for checking whether a char variable satisfies a given property instead of checking if its value falls within a range of integer values which represents a specific set of characters such as "alphanumeric" or "digit". Finally, whenever the goal is doing integer arithmetic on 8-bit integer types, use int8_t and uint8_t if possible instead of a char type.
https://diego.assencio.com/?index=b875a967eebd37d4071d87d990397d43
CC-MAIN-2019-09
refinedweb
975
64.95
#include <string> This browser is not able to show SVG: try Firefox, Chrome, Safari, or Opera instead. Go to the source code of this file. Connect all bitcoind signal handlers. Definition at line 59 of file noui.cpp. Non-GUI handler, which only logs a message. Definition at line 54 of file noui.cpp. Reconnects the regular Non-GUI handlers after having used noui_test_redirect. Definition at line 93 of file noui.cpp. Redirect all bitcoind signal handlers to LogPrintf. Used to check or suppress output during test runs that produce expected errors Definition at line 83 of file noui.cpp. Non-GUI handler, which logs and prints messages. Definition at line 22 of file noui.cpp. Non-GUI handler, which logs and prints questions. Definition at line 49 of file noui.cpp.
https://doxygen.bitcoincore.org/noui_8h.html
CC-MAIN-2021-17
refinedweb
132
71.1
Walkthrough: Calling the Query Service with a Static Query Applies To: Microsoft Dynamics AX 2012 R2, Microsoft Dynamics AX 2012 Feature Pack, Microsoft Dynamics AX 2012 The Microsoft Dynamics AX query service runs a query that you specify and returns the data in a dataset. When you call the query service, you can specify a static query, that is, a query that is already defined in the Application Object Tree (AOT). In this walkthrough, you will call the query service from a C# program and display customer and customer transaction data in grids on a form. This walkthrough illustrates the following tasks: Add a reference to the query service. Call the query service with a static query name and display the data. Prerequisites To complete this walkthrough you will need: Microsoft Dynamics AX 2012 Visual Studio 2010 The code in this topic runs against the default company of the current user. Therefore, you should ensure that you have data in the CustTable table for that company. Add a Reference to the Query Service In order to call the query service, you must first create a project in Visual Studio and add a reference to the service. To add a reference to the query service Open Visual Studio and create a new project by selecting File > New> Project. In the Project types tree, select Visual C# > Windows and then click the Windows Forms Application template. Type a project name such as QueryServiceStaticTest and then click OK. In Solution Explorer, right-click References and select Add Service Reference. In the Address Field, enter the URL of the service. For example, http://<servername>:8101/DynamicsAx/Services/QueryService. Click Go. In the Services tree, you should see the QueryService. Type QueryServiceReference in the Namespace field and then click OK. Call the Service and Retrieve the Data Now we will write the code that calls the query service and returns the data specified by the CustTable query. To call the query service In Solution Explorer, double-click Form1.cs to display the form in design mode. Open the Toolbox and add three DataGridView controls to Form1. By default, they will be named DataGridView1, DataGridView2, and DataGridView3. In the Form1.cs file, add the following using statement. using QueryServiceStaticTest.QueryServiceReference; In the Form1_Load event, add the code to call the query service. The Form1.cs file should contain the following code. using System; using System.Data; using System.Windows.Forms; using QueryServiceStaticTest.QueryServiceReference; namespace QueryServiceStaticTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); this.Load += new EventHandler(Form1_Load); } private void Form1_Load(object sender, EventArgs e) { QueryServiceClient client = new QueryServiceClient(); DataSet dataSet; Paging paging = null; // Create the binding source objects. BindingSource custBindingSource = new BindingSource(); BindingSource custTransBindingSource = new BindingSource(); BindingSource custTransOpenBindingSource = new BindingSource(); // Set the grid datasources to binding source objects. dataGridView1.DataSource = custBindingSource; dataGridView2.DataSource = custTransBindingSource; dataGridView3.DataSource = custTransOpenBindingSource; // Call the CustTable query using the query service. dataSet = client.ExecuteStaticQuery("CustTable", ref paging); // Set the binding source data sources and data members. // CustTable_CustTrans and CustTrans_CustTransOpen are table relations // in the dataset. custBindingSource.DataSource = dataSet; custBindingSource.DataMember = "CustTable"; custTransBindingSource.DataSource = custBindingSource; custTransBindingSource.DataMember = "CustTable_CustTrans"; custTransOpenBindingSource.DataSource = custTransBindingSource; custTransOpenBindingSource.DataMember = "CustTrans_CustTransOpen"; } } } Run the program. This code calls the query service and passes in the name of the CustTable static query. The results of the query are returned in a dataset and displayed in the three grids. The first grid contains customer records, the second grid contains customer transactions, and the third grid contains open customer transactions. The grids are bound to the dataset and use the existing table relations so if you click a customer, the transactions for that customer appear in the second grid. If you click on a transaction, the open transactions for that customer appear in the third grid. The relations are defined in data sources of the static query in the AOT. See also Handling Large Datasets Returned by the Query Service Feedback Send feedback about:
https://docs.microsoft.com/en-us/dynamicsax-2012/appuser-itpro/walkthrough-calling-the-query-service-with-a-static-query
CC-MAIN-2019-26
refinedweb
651
50.12
PVM++: A C++-Library for PVM This library provides an easy way to program the widely used parallel programming library PVM, which works in homogenous and heterogenous network environments. Features : - Easy sending and receiving of messages in heterogenous networks. - Full STL-integration. - Easy installation with configure-script on all UN*X platforms. - Easy access to all task and host information. - Message handlers are supported. - Messages can be automatically unpacked on arrival. WWW: No installation instructions: this port has been deleted. The package name of this deleted port was: pvm++ pvm++ PKGNAME: pvm++ distinfo: There is no distinfo for this port. NOTE: FreshPorts displays only information on required and default dependencies. Optional dependencies are not covered. No options to configure Number of commits found: 34) Deprecate a few unmaintained ports (leaf ports, non staged and unmaintained since more than 12 years) Unbreak this port by applying the real patchset that was submitted [1] which - adds USE_GCC since that's how libpvm3.a (a dependency) was built; - renames namespace Pvm::Internal to avoid conflict with class Pvm::Internal; - adds #include <stdlib.h> where required. While we are at it, migrate from USE_GMAKE to USES=gmake. PR: 182136 [1] Submitted by: Christoph Moench-Tegeder <cmt@burggraben.net> [1] Pointyhat to: gerald [1] Mark as broken: does not patch ===> Patching for pvm++-0.6.0_4 ===> Applying FreeBSD patches for pvm++-0.6.0_4 No file to patch. Skipping... 1 out of 1 hunks ignored--saving rejects to mrt/base_file.h.rej Can't create mrt/base_file.h.rej, output is in /tmp//patchr0fCQLw: No such file or directory => Patch patch-mrt-base_file.h failed to apply cleanly. => Patch(es) patch-configure applied cleanly. *** [do-patch] Error code 1 Fix the build with GCC 4.7 and later (which do fewer extraneous #includes of system include files). PR: 183342 Submitted by: Christoph Moench-Tegeder <cmt@burggraben.net> Add NO_STAGE all over the place in preparation for the staging support (cat: net) - mastersite. Source: distfile survey MIA mastersite. De-pkg-comment. - GNU_CONFIGURE -> USE_LIBTOOL PR: 46465 Submitted by: Ports Fury Add parallel to CATEGORIES. PR: ports/39094 Submitted by: trevor Fix PORTCOMMENTs that were killing INDEX builds. 105 pointy hats to: me Approved by: pat add missing file upgrade to 0.6.0 drop maintainership update to 0.5.1 fix plist error add pvm++, A C++-Library for PVM Servers and bandwidth provided byNew York Internet, SuperNews, and RootBSD 18 vulnerabilities affecting 102 ports have been reported in the past 14 days * - modified, not new All vulnerabilities
http://www.freshports.org/net/pvm++/
CC-MAIN-2017-43
refinedweb
421
59.9
Hi, I am trying to take a screen shot using SCPI with Python. I have got the laptop to connect and have sent some commands that work fine (I got the Spec An's details and set up the start and stop frequencies), but I cant get the screen grab to work. Below is a copy of my code, def screengrab(filename): sendstr = 'MMEM:STOR:SCR '+filename+',*WAI\n') self.s.send(sendstr.encode()) calling it by, import PXA p = PXA.pxa() p.screengrab("test.png") I am expecting this to save a screenshot in the default location in the D: drive but it isn't, there is no error so I think my Python is correct. Thanks in advance for any help, Mashly you are really close! Just change the , to a semicolon like this: sendstr = 'MMEM:STOR:SCR '+filename+';*WAI\n')
https://community.keysight.com/thread/25440
CC-MAIN-2018-22
refinedweb
143
78.89
I have decided to have a little go at creating a Team Foundation Server Event Handler in .NET 3.5 that is resilient and scalable. I will be using as many of the features of Team Suite as I can, but bear with me as there are a few things that are new to me. I am going to create everything under source control in CodePlex. For a full list of articles in this series: check this link. The first toy I am going to play with is the Team Edition for the Architecture components of Team Suite. This will hopefully allow me to create a system that has a bit of foresight and planning associated with it. I have played with these features before, but I have not, up until now, used them in battle. I have created a blank solution in my TFS Event Handler Codeplex project, so it is time to create the "Distributed System Diagram" that I will use to define the architecture of the system. When you create the diagrams, they are added to the Solution and not a specific project. These diagrams will be linked to the code that we will eventually create, allowing us to view these diagrams even if we have made changes. They will update automatically with any architectural changes that I have made after coding has started. The logical place to start is with the Application Diagram, and this is highlighted by default. The other diagrams are useful as well. The Logical Datacenter diagram will allow you to assign parts of the application to different servers and control the communication between these servers. The System Diagram is used to define logical systems that communicate with each other. You get a number of diagrammatic options in the toolbox. The Applications section lists all of the types of applications that are going to be in your solution and represents the projects that are going to be created under your solution. If you add a Windows Application, for example, you will get a Windows Application project within your Visual Studio solution. It is worth noting that there is no need to think about "individual projects like what assemblies am I going to need", or "how will I arrange my namespaces" at this point. All we are interested in is the main building blocks of the application. The first applications that I know that I am going to need are Web Service applications to handle incoming events from the Team Foundation Server and a web service that will allow us to configure any option for this part of the system and the subscriptions to team servers. Now that I have added a web service, you can see that it is just a different type of Web Application. This will need some configuring to be what we want. I have chosen to only handle two of the events that TFS throws, WorkItemChangedEvent and CheckInEvent. There are many other events that could be handled, but these two are probably the most common. WorkItemChangedEvent CheckInEvent The completed service looks quite simple, but we now need to configure it to allow it to work effectively. If you leave everything as defaults, you end up having a hundred things to change later, so it is way better to get it out of the way and polish it at this stage. There are different settings available for each application and endpoint type, so the best thing to do is to look through all of the options and see what is what. You can see from the image that I have configured all of the options on the service end point and I repeated this on all of the endpoints. Many of these settings are used when we generate the code at the end of this process. The second application is the decision service. It has a MSMQ service endpoint called EventReciever that the notification service passes all of the events that it has received to. This service will then execute all of the events against the Workflow service that will perform any activities associated with the event. The reason for the EventReciever service is to make the system more robust. Because the EventReciever is an MSMQ service, the Notification Service can still send messages to it even when it is down. The final end point to add is a web based administration system for the workflow system. I have added all of the links between the applications that define the communication between the services. The ability to create these diagrams is not limited to being done at the start of the process; you can add this diagram to any solution, and it will have all of your applications and links defined already. This is because there is a direct link between the solution and the diagrams. You can change either and affect both with the change, and this does not just apply to these architecture diagrams but to the Class diagrams that are part of the Team Edition for Development. With the application diagram done, I can now do a number of things. One of which is to implement "All Application" which will build my main projects for me. What I am going to do first take you through the "Define Deployment" and "Design Application System" options to get a better understanding of the capabilities of the system. Before I can do this, I will need to create a Logical Datacenter diagram to define what infrastructure is available, namely a single server that may or may not be the same server that the Team Foundation Server is installed on. In creating the Logical Datacenter, I realized that I had made a mistake in my diagram of the system and I had not allowed for the additional web interfaces for the application. I have updated the diagram to reflect the problems I encountered. The diagram now has a separate web administration application that talks to both of the main admin services to get information and to make changes to the way that the system operates. It has two web end points, one for administering the workflow in the event handler and the other for administering the subscriptions for the notification service. This is one of the best advertisements for this way of working as you spot more of the mistakes at this point and not half way through coding. The logical datacenter diagram is very simple for this application as I want it to run initially in a single server environment. At the moment, I have no need for a database, but it can easily be added to the system at a later date, I could even separate out the services from the website without having to change much of anything as far as the developers are concerned, it just impacts the architects. The options that you get are mainly self-explanatory, you can add "Zones" which are your firewall areas and put your servers with these areas. You can then add endpoints and their links through the firewalls to show how communication occurs. You can add all of your firewall rules into the system so it more readily replicates your network. For this application, I only have one zone and one line of communication as all other communication takes place on the server. You could have a much more complicated infrastructure, but for this application, it is unnecessary. The deployment diagram allows you to place all of your applications onto the diagram so you can define the communication lines and determine whether the applications can talk to each other in the desired way. In this case, we only have one Zone and one server, with HTTP inbound for the web sites. You can see from the diagram that I have added all of the applications to the one server. If you have a complicated system with more than a few applications, you will want to break up the diagram into manageable systems so that you can see the input and output of the system. You could say that there is a Core system that contains the web services, and that only two of the web services are accessible outside of the system. If you add the applications to a System diagram and right click on a web service, you get the option to create a "Proxy endpoint" that sites at the edge of the system but is linked to the main service. I can now create a From End System diagram that has the website and only a definition of the Core system without any of the internal components. You can see the result in the diagram. In a much larger system, it allows you to view the components and the interaction of the components from a variety of differing angles to see how the whole thing interacts. The last part of this is to initiate the implementation of all the applications that I have created. This will create the projects under a solution that can then be used to build the final application. As you an see, without doing any code or creating any projects within VS manually, I have a full solution. That is, my job as the architect is over, unless there are any changes from development. This would now be handed over to the developers for completion. Note: I have found that using this method, you can only create ASMX services, and not WCF. This will hopefully (please) be sorted for RTM of Visual Studio 2008. More articles and industry insight can be found here. Technorati Tags: Visual Studio Team System, Visual Studio 2008, Team Edition for Architects, TFSEventHandler, Microsoft .NET Framework, Software Industrial Revolution. Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/20138/TFS-Event-Handler-in-NET-3-5-Part-1-The-Architectu
CC-MAIN-2015-18
refinedweb
1,639
58.42
Top 30 Salesforce Interview Questions 1. Salesforce Interview Questions If you are preparing for a Salesforce Interview, then you are at right place. Here, we provide you the mostly asked Salesforce Interview Questions with their Answers. These Salesforce Interview Questions are specially designed by Salesforce experts which will help both freshers and experienced. So, let’s explore important Salesforce Interview Questions Before moving on we recommend revising Salesforce tutorial. 2. Best Salesforce Interview Questions Following are some basic SFDC Interview Questions which will help you to crack the Salesforce Interview. Let’s discuss salesforce Interview Question in detail: Q.1 What is Salesforce? Ans. Salesforce is the best Customer Relationship Management (CRM) item that conveys to the subscriber as a cost-effective Software-as-a-Service (SaaS). Q.2 What does a custom question allow the client to do? Ans. Once we characterize the custom protest, the endorser can play out the accompanying assignments: make custom fields, relate the custom question different records, track occasions and errands, assemble page designs, make a custom tab for the custom protest, break down custom protest information, make dashboards and reports, and offer custom tabs, custom applications, custom items, and different other related segments. None of these assignments can expert until the point when the custom question has a definition. Have a look at Top Salesforce Terminologies Q.3 What is an Apex exchange? Ans. An Apex exchange speaks to an arrangement of activities that are executed as a solitary unit. The activities here incorporate the DML tasks which are in charge of questioning records. All the DML tasks in an exchange either total effectively or if a blunder happens even in sparing a solitary record, at that point the whole exchange is moved back. Q.4 What is the contrast amongst open and worldwide class in Apex? Ans. The worldwide class is available over the Salesforce case regardless of namespaces. While open classes are available just in the comparing namespaces. Let’s revise Salesforce Lightning Techniques Q.5 What are getter strategies and setter techniques? Ans. Get (getter) strategy is utilized to pass esteems from the controller to the VF page. While the set (setter) strategy is utilized to set the incentive back to controller variable. Q.6 What is the contrast amongst SOQL and SOSL? Ans. The distinctions are said in the table underneath: SOQL vs SOSL I trust this arrangement of Salesforce inquiries will enable you to expert your prospective employee meet-up. As the subsequent stage of your profession, look at the different accreditations offered by Salesforce here: Salesforce Certifications. It will likewise assist you with understanding the activity parts and chalk out a vocation way for yourself. Q.7 What is a Self-Relationship? Ans. A Self-Relationship is a query relationship to a similar protest. It is this introduce enables clients to take the question “Stock” and make associations with different items. Learn more about Relationship in Salesforce Q.8 What is the Object Relationship Overview? Ans. In Salesforce, the question relationship outline joins custom protest records to standard question records in a related rundown. This is useful to track item deserts in related client cases. Salesforce enables clients to characterize diverse sorts of connections by making custom relationship fields on a protest. Q.9 What can cause information misfortune in Salesforce? Ans. Information misfortune in Salesforce can be caused by various reasons, including: - Changing information and date-time - Moving to percent, number, and money from other information composes - Changing from the multi-select picklist, checkbox, auto number to different kinds - Adjusting to multi-select picklist from any sort with the exception of picklist - Changing to auto-number with the exception of from content - Changing from content zone to email, telephone, URL, and content Q.10 Why would you utilize External ID fields? Ans. We can characterize certain fields as an outer ID on a question. These can be utilized as a part of a request to coordinate information from outside frameworks with an exceptional reference ID. For instance, on the off chance that you have to coordinate information from an outside bookkeeping framework to the Accounts in Salesforce, you can utilize an outer ID field to reference the Accounting frameworks one of a kind ID rather than the Salesforce ID. Let’s discuss Salesforce export data Salesforce Interview Questions for freshers – Q. 1,2,3,5,7,8,9 Salesforce Interview Questions for experienced – Q. 4,6,10 3. Most Asked Salesforce Interview Questions You must revise all these Salesforce Interview Questions twice – Q.1 What all information composes a set store? Ans. Sets can have any of the accompanying information composes: - Crude composes - Accumulations - sObjects - Client characterized types - Worked in Apex composes Q.2 What is a sObject write? Ans. A sObject is any protest that we can put away in the Force.com stage database. Zenith permits the utilization of non-specific sObject conceptual compose to speak to any question. Do you know about Salesforce Navigation Setup Q.3 What are Governor Limits in Salesforce? Ans. Ans. In the technology Salesforce, it is none other than the Governor Limits which controls how much information or in other words what number of records you can store in the mutual databases. Why? Since Salesforce depends on the idea of multi-occupant design. In less complex words, Salesforce utilizes a solitary database to store the information from numerous customers/clients. The beneath picture will enable you to identify with this idea. To ensure no single customer hoards the mutual assets, Salesforce presented the idea of Governor Limits which is entirely upheld by the Apex run-time motor. Representative Limits are a Salesforce designer’s greatest test. That is on the grounds that if the Apex code ever surpasses the farthest point, the normal senator issues a run-time special case that we can’t take care of. Henceforth as a Salesforce engineer, you must be exceptionally cautious while building up your application. Distinctive Governor Limits in Salesforce are: - Per-Transaction Apex Limits - Force.com Platform Apex Limits - Static Apex Limits - Measure Specific Apex Limits - Different Apex Limits - Pop-up message Limits Let’s take a tour of the Salesforce Data Security Model Q.4 What is a sandbox organization? What are the diverse kinds of sandboxes in Salesforce? Ans. A sandbox is a duplicate of the generation condition/organization, utilized for testing and advancement purposes. It’s valuable since it permits advancement on Apex programming without exasperating the creation condition. Q.5 Can two clients have a similar profile? Will two profiles be allocated to a similar client? Ans. Profiles decide the level of access a client can have in a Salesforce organization. To the extent the initial segment of the inquiry is concerned, Yes. One profile can be allocated to any number of clients. Take the case of a Sales or Service group in an organization. The whole group will be alloted a similar profile. The administrator can make one profile: Sales Profile, which will approach the Leads, Opportunities, Campaigns, Contacts and different articles esteemed fundamental by the organization. Along these lines, we can put numerous clients on the similar profile. On the off chance that the group captain or chief need access to extra records/protests then it should be possible by appointing authorization sets just for those clients. Noting the second piece of the inquiry, every client must be relegated 1 profile. You must read Salesforce automation tutorial Q.6 Would you be able to alter a zenith trigger/summit class underway condition? Would you be able to alter a Visualforce page underway condition? Ans. No, it isn’t conceivable to alter summit classes and triggers specifically underway condition. It should be done first in Developer version or testing organization or in Sandbox organization. At that point, to send it underway, a client with Author Apex consent must convey the triggers and classes utilizing arrangement apparatuses. Be that as it may, we can make and alter Visualforce in both sandbox and underway. If we want to accomplish something one of a kind with the page- some distinct quality, we need to produce it using a Sandbox. Q.7 What are the distinctive information composes that a standard field record name can have? Ans. A standard field record name can have information kind of either auto-number or content field with a breaking point of 80 singes. To produce auto-numbers, we should determine the configuration as we characterize the field. Then, for each inclusive record, it auto-creates a number. Let’s discuss Salesforce reports Q.8 Can you redo Apex and Visualforce straightforwardly in a generation organization? Ans. Peak can’t be tweaked in a generation Org. We must change and sent through a sandbox and meet test scope. Visualforce, again redone specifically underway (Although this isn’t best practice) Q.9 What are the two choices for when Apex Triggers can run? Ans. Peak triggers can keep running before we spare a record or after. We can use any activity before that to check data that we will embed. We do this after utilizing the trigger to get information a client or framework has already entered. Q.10 At the point when we should utilize Apex over Workflow Guidelines or Process Builder? Ans. There are different reasons why you should utilize Apex over decisive robotization alternatives: Work process standards and Process Builder tasks once in a while have to include constraints that we can overwhelm with Apex. For instance, pulling data from an outer framework. Let’s revise Salesforce Architecture When managing certain or huge arrangements of information, Apex can be more proficient than decisive alternatives because of fewer restrictions. Salesforce Interview Questions for freshers – Q. 1,2,3,4,6,8,9 Salesforce Interview Questions for experienced – Q. 5,7,10 4. Tricky Salesforce Interview Questions Now, here comes some tricky Salesforce Interview Questions which will help both freshers as well as experienced in Salesforce Q.1 What are Governor Limits? Would you be able to name 3 illustrations? Ans. Salesforce keeps running on a multitenant domain which implies assets (Storage, CPU, Memory). This imparts to different organizations on the Salesforce stage. This implies limits that must set up to guarantee that all organizations utilizing the Salesforce engineering comply with specific principles and don’t give their code or procedures a chance to hoard shared assets. A couple of cases of Governor Limits are: - Add up to the number of records recovered by a SOQL inquiry – 50,000 - Add up to the number of SOQL inquiries issued – 100 (Synchronous) 200 (Asynchronous) - Again, add up to the number of DML articulations issued – 150 - Add up to the number of callouts (HTTP asks for or Web administrations calls) in an exchange – 100 - Most extreme CPU time on the Salesforce servers – 10,000ms (Synchronous) 60,000ms (Asynchronous) Do you know about Salesforce CPQ Q.2 What is Apex? Ans. Zenith is a certain protest-arranged programming dialect to enable engineers to expand the Salesforce stage. They compose their own business rationale into the stage to do that. The peak is like that in Java and we can propel it through a collection of occasions the client begins. An example of this is record refreshes, catch clicks, triggers on articles, or outer web benefit demands. Q.3 How is SaaS useful to Salesforce? Ans. SaaS deals with membership. So customers can pick not to recharge and end utilizing the program whenever without punishment other than not having the capacity to utilize Salesforce. We expect SaaS to enable clients to maintain a strategic distance from overwhelming beginning startup charges and ventures. SaaS applications utilize a basic Internet interface bolstered by simple mix. Q.4 How does Salesforce track deals? Ans. Salesforce is the following project that records various accommodating essential points of interest, for example, Number of clients served day by day Day by day deals volume Point by point reports from Sales Manager Deals figures by month or quarter Above all, Salesforce tracks and reports rehash client movement, which is the way to any business association. Let’s revise Salesforce role hierarchy Q.5 What type of connections Salesforce Offers? Ans. Salesforce perceives two relationship composes: Master-detail connections and Lookup connections. Q.6 What is the trigger? Ans. The trigger is the code that is executed previously or after the record is refreshed or embedded. Q.7 What is the distinction amongst Trigger and Workflow? Ans. Keeping in mind the assessment criteria and governs criteria, we fire an activity with a mechanized procedure that we call the work process. After we refresh or embed the record, or on refreshing or embedding it, we execute the code that is the Trigger. Q.8 What is static asset in Salesforce? Ans. With Salesforce’s static asset, endorsers can transfer compress records, pictures, jostle documents, JavaScript, and CSS documents that we can allude in a Visualforce page. The ideal size of static assets in Salesforce is 250 MB. Q.9 What is the contrast amongst Force.com and Salesforce.com? Ans. Force.com is Platform-as-a-Service (PaaS), while Salesforce.com is Software-as-a-Service (SaaS). Q.10 Is there a point of confinement for data.com records? Ans. Salesforce clients can see their point of confinement frame setup effectively by essentially clicking data.com organization/Users. From the data.com clients area, the clients can see their month as far as possible and precisely what number of records send out amid the month. Let’s learn Salesforce import data Salesforce Interview Questions for freshers – Q. 1,2,3,6,8,9,10 Salesforce Interview Questions for experienced – Q. 4,5,7 So, this was all Salesforce Interview Questions. Hope you like our explanation. 5. Conclusion – SFDC Interview Questions Hence, you have completed the first part of the Salesforce Interview Questions. Keep connected with Data Flair for more Salesforce Interview Questions and Answers. Soon, we will publish its second part. Still, if you want to add more Salesforce questions, you can tell us through comments. See also – Salesforce career in India For reference
https://data-flair.training/blogs/salesforce-interview-questions/
CC-MAIN-2019-13
refinedweb
2,357
56.55
TSConfig Functions¶ Synopsis¶ #include <ts/ts.h> - unsigned int TSConfigSet(unsigned int id, void * data, TSConfigDestroyFunc funcp)¶ Description¶ These functions provide a mechanism to safely update configurations for a plugin. If a plugin stores its configuration in a data structure, updating that structure due to changes in the configuration file can be dangerous due to the asynchronous nature of plugin callbacks. To avoid that problem these functions allow a plugin to register a configuration and then later replace it with another instance without changing the instance in use by plugin callbacks. This works in the same manner as shared pointer. When a plugin needs to access the configuration data, it calls TSConfigGet() which returns a pointer that will remain valid until the plugin calls TSConfigRelease(). The configuration instance is updated with TSConfigSet() which will update an internal pointer but will not change any instance in use via TSConfigGet(). When the last in use pointer is released, the old configuration is destructed using the function passed to func:TSConfigSet. This handles the overlapping configuration update case correctly. Initialization is done with TSConfigSet(). The id should be zero on the first call. This will allocate a slot for the configuration, which is returned. Subsequent calls must use this value. If the id is not zero, that value is returned. In general, the code will look something like class Config { ... }; // Configuration data. int Config_Id = 0; //... void ConfigUpdate() { Config* cfg = new Config; cfg.load(); // load config... Config_Id = TSConfigSet(Config_Id, cfg, [](void* cfg){delete static_cast<Config*>(config);}); } //... PluginInit() { // ... ConfigUpdate(); // ... } Config_Id is a global variable holding the configuration id, which is updated by the return value of TSConfigSet(). The configuration instance is retrieved with TSConfigGet(). This returns a wrapper class from which the configuration can be extracted with TSConfigDataGet(). The wrapper is used to release the configuration instance when it is no longer in use. The code in a callback tends to look like int callback() { auto cfg_ref = TSConfigGet(Config_Id); Config* cfg = static_cast<Config*>(TSConfigDataGet(cfg_ref)); // ... use cfg TSConfigRelease(Config_Id, cfg_ref); }
https://docs.trafficserver.apache.org/en/latest/developer-guide/api/functions/TSConfig.en.html
CC-MAIN-2019-39
refinedweb
335
50.02
4eraltd C a4{Ro E EDITORS. y E1fi, C. DAY, AUGUST 9, 1883 A.ASOE THZ PZOPLS. S'~en is a thIgest respectFs!'a j devoted to the materiaik ,,h 'p~oplof this Coutyand Iat.It extensively,and as a medium oders unrivaled ad antges, Tor Tams.see irast page. MEWS AND COURIEB LAW. A few days ago, our Charlestoi contemporary, in a strong editorio in favor of schdols for tenchnica training, made the following arga ment: A student of law is required t ead law three years and stand ai drmination before he can be ad pitted to the bar, and a physicial has to take a full course in som, medicaY college before he can prac tice. Why not apply the sam< rule to mechanics and tradesmen: It would gie us better labor, ana it would be better for those whi oe engaged inractical pursuits. The weak point of the argumen quoted is in the words, "A studen of law is required to read law threi years and stand an examinatioi before he can be admitted to thi bar." We, . at least, have no sue] and it is ir to presume tha contemporary was speaking o the law of this State. What thi law does provide is that "any citi sen of this State who has attainei athe full age of twenty-one years E and who may pass an examinatioj upon the course of study prescribe( by the Supreme Court, and caa produce the certificate of a practic ing attorney of the Supreme Courl that he is of good moral character shall be permitted to practice las in this State, on taking the oatl required by the Constitution and the oath respecting dueling." Th( odly qualification required, then, if the .ability to stand an examina tion, get a certificate of good mora: character, and: take an oath; anc we sincerely pity the man who can not do this.. Indeed, one is aboul as easy as the other, and he is s sorry fellow\ who cannot, aftei five months' study, stand the ex. .amination, as it is now conducted. In saying -that one is required tc study law thee years before he car be admitted to the bar, the Nesce and Covrier clearly acted on the doctrine that whastever ought to be, is- there ought to be such a law, whether there is or not. But as thiat paper carries information, as well as news, into many of the families of thts State, a correctior should be mbde. This is due tothe members of the bar who have' beer admitted under the new law; for the people must have a sorry opin ion'of the capacity of many a law. yer, if they think he was three years'acquiring the little law whici is a dangerous thing to his clients. TeNews and Courier should say, "A student of law ought to be (nol is, but ought to be) required to read law three years." The News andi Courier objects tc the sulky, on the ground that the ae tion of the rider is not graceful and his occupation' not conducive to sociability. It says man is * Ssociable creature, and social phil osophers object to solitary amuse ments. The News and Couries carries this theory into practice; il is-not fond of solitary amusements Some time ago it mounted :: hobbs and rode a tilt at Capt. Lipscomb but it found the ride solitary, an.d -oh ! so loresome-not at all con -ducive to sociability. In,deed, th4 hobby proved so much worse than sulky, that it was abandoned witi a promptness that was admirable for our contemporary is not giver - to solitary amusements. SAVAN, August $.-Specia reports to the Morning News fron thirty-nine counties in Georgia located in different sections of th4 State, say that the condition of th4 cotton crop of the State averages ix general about the same as last year Owing to a drought of five or sib weeks' duration the condition of the crops in some sections is not at favorable as at the correspondin time last season. The probable yield is considered as an average - crop. Rain has broken the droughi in some sections and an improve * ment is looked for. The outlook in Florida is con siderably brighter, owing to th~ greater frequency of rains. Labo, generally.is reported in good sup ply. Picking has begun in a feiw S counties and will be general fir about August 15th to September 1sI UNIN, August 1.-It gives 'me great pleasure to report that all of the sufferers from the poisoned ice eresm-are convalescent. .Some of tisem lisa very narrow escapes, how ver.s-New* and Comrier Cor. TEACH 'F' IOHE LAW. When the general stock law Was enacted, a murmir of discontent, was heard from 'Les gton, which has since deepeWd; nto s *ll growl. The maleontents, who of course, do not represent the good and progressive citizens of their county, have made threats, dis played coffins and engaged in other demonstrations of lawlessness, to the terror of those who honor the law. The News and Courier of August 3rd, contained this infor mation: A delegation of substantial farm era ofLexington County waited on Governor Thompson to-day and presented a statement of their grievances in regard to outrages and depredations committed upon their property, crops, fences and 1 barns during the last tyo weeks by 1 anti-Stock law men. One case re 1 lated was that a party of men . rode up to the house of one of these farmers, shot into it, wounding his wife, set fire to his fences and burnt his barn- cpta ng corn, fddder, 1 &c. They state that these lawless men have threatened and terrorized the whole community, and report many other outrages of a like char - acter. - They asked the Governor to take such steps as would lead to the apprehension of the guilty '>ar ties. Governor Thompson has ta ken the matter into consideration and is now investigating it. b When the bill which became the general stock law, was before the legislature, we thought that it would be wisest and fairest to leave the matter to local option, and not k thrust the law upon a county which was opposed to it. Thinking as t we did, we could not help sympa thizing with poor Fishburne who fought the bill so bitterly in behalf I of his own county. But the law was enacted;. it is on the statute books; and all the people should be taught to respect it. Most of those who oppose it, do so because under its operations they are not allowed to pasture their cattle upon other people's property, as they had done from time immemorial.. But they cannot be a law unto themselves, and prompt measures should be taken for the punishment of these midnight marauders of Lexington, who, we take it for granted, will live long enough to see the criminal folly of harassing law-abiding citi zens, and attempting to nullify a law which the government has the power to enforce. N. G. G.a correspondent of the News ansd (ourier says: "Prof. L. B. Haynes, chairmaan of the execu tive committee of the State Teach ers' Association, announces the fol lowing programme: The association will meet during the session of the white Normal Institute, on August 14 and 15, in the chapel of :he Female College. The following lectures wilf be delivered : Primary and Seebndary Education, by Prof. C. R. Hemphill, of the Theological Seminary; the One Study Plan, by Rev. S. .Lander, D. D., president Williarnston Female College. Mr. Virgil C. Dibble of the Charleston High School, who has recently be come a member of the National Council of FAucation, will also ad dress the association. Printed re ports will be submitted for the dis cussion by the committee oil public schools and high -schools. As the members will desire to attend the Normal Institute reduced rates for travel and board can be secured. Ample arrangements have been made for-the board of all teachers attending the Institute at tour dol lars and a half a week. Applica tions for board indicate a good at tendance. The Illinois Legislature recently passed an Act providing for the compulsory school attendance of all the children of the State, "to secure to all children the benefit of an-elementary education." Parents or guardians, under this law. must send children between the ages of eight and fourteen to a public or private school for a period of not less than twelve weeks in each year, unless the local educational board excuses such attendance for good reasons. The penalty of the law is a fine of from ten to twenty dollars. 'There is such a glut of Georgia watermelons in New York that they fail to sell for enough to pay freight, and many large consignments have been refused and were sold by the railroad company to pay expenses. The Georgia farmers, encouraged by the profits earned last year, have raised entirely too many, and the consequences will be disastrous to their hopes. Prepayment of freight is now required at Savannah. The prices at New York now range from $10 to $14 per hundred. LONDoN, August 3.-A dispatch to the Exchange Telegraph Com pany from Paris says it is rumored that a plot to restore the monarchy has been discovered. The news paper La Franice professes to give the details of the plot. It says that 24,000 missiles for a popular risiig have been ordered and that attempts have been made to tamper with the army. It also states that three conspirators_have been arrested. The appeal cases from the May or's courtin Anderson in which fines had been imposed for violating the ordinance forbidding the selling or furnishing of intoxicating liquors to minors and persons of known intemperate habits, have .been set tled by .payment of the fines in fnul BUTLER'S PLAN. A Senator Butler's fourth. letter on the 'aPublic Roads" goes to the I marrqw of ths subject, and contains ti suggetions :that are worthy of con- a sideration. 3'he Senator thinks 1' that the proposed amendments to f< the present road laws, properly g executed, would give us good roads; d and he regards his plan as feasible ii without being burdensome. We n give this extract which embodies a his'plan, with the exception of cer- i tain details: I should-first amend Section 1,084 d of the GenerilIStatutes by striking t out "twelve" in the proviso of that - section, and inserting - "three"; so that it would read: "Provided, t That no more than three' days' work & are required of any one hand in a t] year." And in Section 1,089 I o would strike out the words "three" and "twelve" in the--tiird line and insert in lieu ereof the words "one" and' ee" respectively; so that tle/part of the section will a readAnot less than 'one' nor moe 1 than 'three' days," &c., &c. The E effect of these amendments would a be to reduce the minimum and a maximum of working days to one and three respectively. With these 0 changes, and perhaps some others n of minor importance, I should allow p the present law to stand, and sup- R plement it by one, two or more sec- 0 tions embodying the following prop- t ositions : First. I should levy a tax of one $ dollar a head on every able-bodied d male person liable to road duty, to C be levied and collected by the coun- p ty treasurers; to be paid out on a 0 warrant of the county commission- 8 ers; to be denominated a "road n tax," and kept apart and dedicated i exclusively to the construction, re- ti pair and maintenance of the high- t ways in the county where collected. it Second. I should provide for the 11 appointment by the county commis- f sioners, by and with the advice and 1 consent of the Senator and Repre- n sentatives of the county then in n 'office, or a majority of them, of a t competent supervisor of county t roads, whose salary should be fix- 19 ed by law at say fifty or seventy- q five dollars per month, who hall enter into a bond with approved tl sureties for the faithful discharge of t< his duties and care of the public t] property committed to his custody. t The county commissioners should ff have power to authorize the super- e visor to organize and equip with the n necessary outfit under the direction a of said commissioners a force of 0 able-bodied laborers, twenty, fifty I or one hundred, as the exigencies tl may require, whose wages should be li fixed by the commissioners, and 11 when fully organized and equipped t with a full complement of improved s< implements, tents, wagons or carts, 5 mules, &c., to enter upon the con- t1 struction, change and repair of the T public roads, beginning at the court- f house ;md putting in perfect repair b the first ten miies of road leading t thereto, and extending the work t1 from month to month, or year to p year, until the main highways and f thoroughfares are completed, and ft then less frequented parallel and C cross roads, until every public road tl in the county has been put in good Vl condition. .c; This supervisor, with his force, nI should be kept constantly at work ni on the highways, and if, after once e getting the roads in good condition, t it should be found, as I have no C doubt it would be, that the head tax t< pi-ovided was in - excess of the re- e: quirements for maintenance it could p be from time to time reduced. The n supervisor should be indictable and tl removable for any neglect of duty, E besides liable in a civil action on k his official bond for the loss, destruc- ca tion or damage to any public pro- ce perty in hi,s charge. - There should rt be established in connection with t: this and all other taxes disbursed A by the commissioners a proper sys- ii tem of accountability, by requir- v ing them to suibmit annually to the ti grand jury, on the first Monday in t March, an itemized account of their ti receipts and disbursements, and tl publish the same in a county paper. Besides this, the solicitor of the circuit should be required to ex- si ine and inspect this annual st e- b ment of accounts and make a writ- fr ten report on the same to the presid- Ii ing judge at the next ensuing court al after the publication in the county ir paper, that such orders may be d taken as the interest of the public b may require. n If this plan can be carried out as e >lement to existing law, how c hb money would it raise ? If I b ~right in my estimate of the ci irrmber of persons in the State d liable to road duty, it would give ti $150,000 annually, or thereabouts, c' the sums raised in each county to p: be expended in the county. e Let us take Edgefield as an c< example. We have about 9,000 tI voters; say we have 7,000 road hands. Assuming that the full tax of $1 a head should be collected, ti we would have $7,000 annually. Of al this sum, perhaps $2.000 would be B expended the first year in an outfit n< and for wages, &c., leaving $5,000 l1 to be laid out on the roads.d It is safe to say, that with ti: an average expenditure of ii twenty dollars a mile the roads can cr be put in first-rate order; some bi sections costing perhaps fifty or o' seventy dollars, others not more cc than five or ten dollars per mile, so pl that the $5,000 would improve 250 miles of road. The second year, having an outfit, there would be a is larger fund available for the roads, S and in five years' time every road in p: Edgefield County would be in good T condition, and after that easily| ai kept up at a slight cost.;t W. C. McGregor, Columbia, S. n< C., says: "Brown's Iron Bitters has ti< merand it has givn ainfation." cc .GAINST SOUTHERN FACTORIES. Some time ago the Abbeville 'ress and Banner opposed the erec on of a cotton factory at Abbeville, ad its views, besides being sharp. 7 criticised by the press, drew )rth a letter full of facts and ar ument, from Mr. Hammett, Presi ent of the Piedmont Manufactur ig Company. The Press and Ban er of last week contains a long nd forcible editorial in reply to s critics and reviewers, from which e publish the following extract efining our contemporary's posi on. The views expressed are not opular perhaps; but we believe iem to be honest; and they de erve consideration. We think that iey are not very unlike the views nce held on the subject by Jno. C. alhoun: Mr. Hammett takes great credit > the Company which he repre ants, for the enhancement of the inds for miles about Piedmont. ven if the factory had brought bout this wonder, which we do not dmit, it is not an unmixed good. 'he great majority of our people wn no land, and if the establish ient af the factory has placed the rice of a home beyond their reach, re fail to see wherein that part of ur population is benefited. On ze other hand nine-tenths of the wners of the land do not want to all, and if the taxes on those who o not want to sell have been in reased in the ratio of the selling rice, then nine-tenths of the owners f the land do not want to sell, ad if the taxes of those who do ot want to sell has been increased i the ratio of the selling price, 1en nine-tenths of the owners of ie land hav suffered a direct in iry by such enhancement of value. t matters little to the owner of a Lrm, who expects to live on it. -hether it is of great or small iarketable value-the productive ess of . it is the same. So, all of Ir. Hammett's boasted benefit in ie matter of the enhanced value of tud dwindles down to a doubtful uantity. But we have been led away from e subject. Our objection to fae >ries is, that ours is a thinly set ed community, and that it is bet ir for our people to stay on the irms than to con'gregate as labor rs in factories; a woman who goes ito a factory becomes, so to speal, mere machine, learning to do nly one thing, while if the same 'oman remains at home she learns ie duties and work of a womanly fe-the life, which nature and the mws of our civilization intended iat she should live. We cannot e how factorv girls are to learn to w, to cook, or to keep house for ie husband which she should have. e also object to girls going to ctories because it establishes caste etween our own race, and we think deir entrance into these institu ons often lessens their chances of roper marriages. We think it well yr capitalists to let factories alone, yr with an honest administration f the National Government and is rCntttoa protection which ie State guarantees to our people, pitalists can find better invest ients for money. It is cheap ioney, and not cheap labor, which nables the English manufacturers > compete with us. The English pitalist is satisfied with from two >four per cent. while the South ruer wants from ten to twenty er cent. The difference in the de iand for interest lies in the fact at we have little money while the uglishman has more of it than he nows what to do with. No new antry can compete with any old auntry in manufactures. The diffe mee in freights, which everybody ilke about. is the merest nothing. ss the capital stock of no factory ithe South had any appreciable alue before the war-and before 1e days of protective tariffs aid ixddging-so they have but lit e value when these impositions on ie people are removed. TLhe Abbeville Press an~ .Banner lys: "The month of July has een unprecedentedly hot and dry, -om the first to the last. Very ttle rain has fallen in this month, aid the whole county has suffered itensely for rain, until a very few ay ago, when partial showers egan. to fall. The corn crop in early every section has been injur :1, and in some fields the crop is >mpletely ruined. On much of the est bottom land in the county the op will be a failure because of the ry spring, which interfered with ie preparation of the land, and be iuse of the difficulty in getting a roper stand. The cotton crop, en where it is still in a healthy >ndition, is but little larger now ian it was three weeks ago." The best tonic medicine-one it is not composed mostly of cohol or whiskey-is Brown's Iron itters. It is guaranteed to be an-intoxicating and will absolute kill all desire for whiskey and ~her intoxicants. It has been oroughly tested and proven itself every instance a never failing re for dyspepsia, indigestion, lliousness, weakness, debility. rerwork, rheumatism, neuralgia, msumptive disease, liver com .aints, kidney troubles, etc. It has been suggested that there a serious obstacle in the way of mator Butler's plan for the im -ovement of the public highways. he constitution forbids the levy of iy capitation tax except the poll x of one dollar for educational rposes. The Senator'S. plan can >t, it see' s, be carried, into execu >n witho t an amendinent to the >ntt n .lVew .Idvertisesents. the oM ST. r RODI! 1i For our immense Fall and Winter Stock, which will be the largest and by far the most complete that will be brought to the Up-Country, and to get the deces sary room, (our store being already too small for our rapidly increasingbusiness), we are clearing out our Spring and Summer Goods at 8m1NS RllE&RTION8HOlR (JAl! There never has, nor ever will be a time in the History of Newberry when goods can be bought to a- greater advantage. Throw aside your heavy shoes during this oppressive weather, and enjoy the real comfort, which Opera Slip pers will afford. You can buy them from us so cheap that there is no excuse whatever for making yourself uncomfortable. Now is he time to buy your Prints. We are selling the very best Sc. and 6ic. Prii for 61c. and 5c. per yard. Mosquito Nettings in Pinks, Blues, and Bnffs. French Bronze for dressing, Children's Fancy Shoes, Slippers and fancy articles generally. Our 10c. blelching still leads all other bleachings; and shall it not always lead? We believe every customer is more or less a Bargain-Seeker, and, if you will take the prices demanded for Dry Goods prior to our establishment, . and compare them with our prices as they exist to-day, you will at once see that we have acted upon that belief. Do you want a shoe that will look well on Sundays, and yet stout enough to meet the requirements of every day wear? Then buy J. W. BRIGlAM'S SJIJTOt MADE 8lOE8! See that J. W. Brigham is branded upon the sole of each shoe, and you have an honest shoe made by an honest man. Whenever and wherever you buy shoes see that the manufacturer's name is branded upon them. It is an infallible test of a good shoe; for every manufacturer of genuine shoes can afford to let you know that he has made them, while no manufacturer of Shoddy and Paste Board Shoes can afford to make himself known, for it would never increase his sales, nor cause your hearts to pulsate with joy. We are not trying to misrep resent our position. We never expect to see that day "when we are to make our living by misrepresentations. We mean that we have marked down our Spring a9d Summer Goods-those goods that cannot be sold in Winter-and we shall expect you to call early, and purchase largely of the great bargains which we not only offer or the next 30 days, but for the next 360 days. B. H. CLINE & CO. aug. 1, 31-tf. T NI FIT!I IKW in [NS, FEEDERS AND CONDENSERS Admitted by all public ginners who have used them to pe the best. The revolv ing Heads in the ends of the cotton box of these gins prevent.its breaking the roll or choking. It-makes as good sample as can be made, gins the seed per fectly clean and does the work rapidly. Every Gin Feeder and Condenser is guaranteed to give perfect satisfaction i every respect or no pay. We use nothing but the very best material in its con struction and employ none but the very best mechanics to do the work. We import our own saw steel and iron for shafting, and it is tile best we can- get. Every gin thoroughly tested before shipped. Messrs. Aull Bros., Newberry, S. C., are our agents, and will sell you one at Factory prices. Wr4te to or see them before placing your order.' DANIEL PRATT GIN CO., Frattvile, Ala. June 5, 23-3m. NOTICE. JSTATE OF SOUTH CAROLINA, The County Commissioners will beByJcb .Felr,Poaeud. at Piester's Bridge over Bush River atByJcb .Felr,Poaeud. 10 o'clock A. M. Saturday, Au 1st 'WHEREAs, Robert P. Wallace and 25t, ist,forthepuroseof warng ! George L. Neel have made suit to me a contract for buildino a new Bridge. i to grant them Letters of Administra In the mean while. p?ans and specifi- tion of the estste and effects of James eations may be seen in their office. A. Wallace, deceased. By order,of County Commission4rs. These are, therefore, to cite and JAS. K. P. GOGGANS, admonish all and singular the kindre.d Aug. 8th, 1883, 32-3t. Clerk. Jand creditors of the said James A. _______________________- IWallace, deceased, that they be and N T CEN appear before ulhe, inthe Court of * Prbat, t beheldat ewbrryCourt FSectib.n 1178 of the General Statutes House on the 22d day of August next, requiress that all landowners In the after publication hereof, at 11 o'clock County of Newberry shall remove from in the forenoon, to shew causg, if any the running streams of water upon they have, why the said Administra their lands all trash, trees. rafts, and tion should not be granted. timber, during the monthis of March Given under my Hand this 7th day and September in each year. Land- of August Anno Domini, 1883. owners are notified to comply with the Augus. ,ELLERS, .T. P. N. C. By order of the County Commission ers. JAS. K. P. GOGGANS, IT lIi1t August 8th, 1883, 32-3t. Clerk. fI H I NOTICE. r We the undersigned comprising the I II ~ 1 D C J firm of McFall & 'atterwhite do here-J* I li Ih E by announce that said firmi is dissolved N by mutual consent. All persons holding demands of any A e n w i h character whatsoever against said firm will present the same to Dick S. Sat- ro aeyo c pe terwhite for settlement-he having as summed payment thereof. *by I1s So li Re And all~persons in anywise indebted to said firm will make payment to Dickd r S. Satterwhite-who alone is authori zed to collect said indebtedness,.u h i tc J. Y..MW.ACLPPof DICK S.sSASophiaITe Newberry. S. C., August 3rd, 1883. E 32-3t. t A & 5 Bring Your Work &c., saved from the TO THEfire, without regard Newberry Herald to cost. -., ~~Bargains may b had by calling earlyC aug. 8, 32-4t. NEATLY CHEALTHEN Withssuperuperiorsser,rapidrgerk,sorll cleanedfSeed,Tandgoodosample, ande Paperldndt arlowoprice,handfollascom is keptdonihand,rthisPofascecislfullyspre parempleoGin,awythnFeaderkandsCondeor entr,uated ttore. Whr alsoeIte C and Exesfcted agion14. S P OZR HEPLYAN BOK TOREBOM EXEDITIOUSLYas no Paper,o frraeidualit, 1well. FROMANeaere, send qud aml, and s Visitig Card to a P s ol at alwperc, olqality on accm sal Ca, firt-rt3 Feeder a qundes Withsupeior resss, alarg assrt- Bilt mysoeim 0es men o Jo Tpe god nk,fie . S.i5t~e 2. BEt. Papr ndCadsofwhchaNulosoc Paer misaedIum lty 20 ct s. paredto d anyand al kidsoowor Paer second quality, 10 ts.r entrustedetoPit.r, coonut, 20 et s.pe pak qmre Dry Goods. 4 The citizens of Newberry and adjoin ing cOunties are aware of the late fire which destroyed Mollohon Row, and with other houses, laid low in ashes,=f the well-known CHEAP CAS = STORE of With great exertions, a portion of stock was saved; and though parf. is badly burnt, a great dea is erfect. No sooner was he bro ack to face with the disaster t1ha in his usual irrepressible style, det mined that he should rise once mq At last he succeeded in securing that magnificent stand of the weli firm of Y .~Y together ith their beautifl stock DRY GOODS, which ".e pur hased a a heavy dieount Off New York -{t FO. CASH, and he is nowbe with pleasure, at being able tostt customers better than ever. The stand is the finest in town; goods are petty and well seleo~; and a well- *hted store showstbu to the best adyanae. - This fine stock, toehrwith t goods saved from the.fI~ will be of fered to the public from to-morrow, t' AN IMM]ENSE BAORIFIO Having procured a heavydiouA on this stock and-received dainage~ for the goods saved by firb,, he is ina& position to fairly Slaughter Prices The stock comprises a beautifnl C sortment of notions, Dress God,io# all kinds, in daing pr-ofusion, trimmings to corsond ; aind an e~ less variety of H 1I Y, G O J and in fact everything in the ptr GOODS LINE, at~ price to every one. 'lhe great s 1ugt*e TI commence on Monday with a for which he-is now preparng, b having ee lii ed do\vn, ready for the rush. Suhan opportt Tmay not occur again to secure bargains. The gopds miLbe sold,tto make room for a Fall and Winter stock: so' Wo AVOID THE c'ca 1 come early, as it will be mlire pleasant than I#fe % iisb day. The stock is so immnense and all hands pi-eparing go#ds for C; exhibition, that a list of either gosor ppies inaggssible: but I guarantee a saving ofKat eat30) per cent. 1eilthan my other house. A mounthin of ith'a regular stockt second to none inth hSti.. A11 My 014 Fx$exiuI ~re reguested to call erotmd at the new stand, nd;e o ,hemselves. They will .always receive the samejdt reatment, whether they purchase or not. I will arde ~o sell as many goods for $7.60 as any other ho'ise inthe state can sell for410.0' '4 COME ONE! COME ALLP Lnd secure some of those rare bargains before-the are all rone, and you will leave the store smiling and dlgtdand vill tell your neighbors that the place to get bargains is a& D). C. iELYNN'S, TL A TEE OF LOW P IELLY & PUR,ICELLJ Eanagers. Old Stand of McI al Af tew # xml | txt
http://chroniclingamerica.loc.gov/lccn/sn84026909/1883-08-09/ed-1/seq-2/ocr/
CC-MAIN-2014-41
refinedweb
5,348
67.18
So what's your collective take on solution folders with Visual Studio? For the longest time, I didn't pay them no never mind. Then there was a brief period when I had an intense love affair with them. Everything went into my solution. Third-party libraries, testing tools, documentation, damning evidence that other members of the team were plotting to beat me up and steal my lunch money. At my last contract, even the projects were organized within solution folders and when I first saw that, I nodded approvingly to myself. The rationale was that if it was in the solution, I didn't need to leave Visual Studio to deal with source control. It was safe in Visual Studio. It gave me comfort. Even joy. Windows Explorer was a scary place and this TortoiseSVN/Explorer integration wackiness was just plain FREAKY FRIDAY! Better to stay in my happy place. Then I noticed cracks in the veneer. I couldn't add a physical folder to a solution folder and have it magically add all the files within it to my solution. I felt a slight twinge of annoyance at having to navigate an extra layer to get to the project I wanted. And at the risk of being called a "slave to my tools" (which is a funny accusation at the best of times, unless the accusers writes code in Notepad and compiles from the command line with csc), I do enjoy the Collapse All Projects feature of Gaston Milano's CoolCommands, which didn't work as nicely with that extra layer. So now I find myself back to having all my projects at the top level and using solution folders sparingly for things like batch files, build files, and readme files. I ventured out of my comfort zone in Visual Studio and learned to deal with third party library folders and tool folders externally. And really, it only took one time re-creating the full NAnt folder structure in solution folder format to make me drop the practice. How about you? What do you store in solution folders? Do you maintain a project hierarchy in them? Use them for any non-code-type files? Love them long time or hate them with a Charles Bronson-like vengeance? Kyle the Solvable [Advertisement] I like to use solution folders for existing legacy projects because they tend to be huge and have existing nonsensical organization. One solution has 50 projects, 3 web apps, 5 services, etc. and I need solution folders to make sense of the madness. These are projects where project name != root namespace name != assembly name and each folder might have 10 different namespaces. On green- or brown-field projects, I use a single "solution items" folder that holds my common config files (StructureMap.config, Log4Net.config, hibernate.cfg.xml), my build file, and any other common or non-code files. I find with good naming and structuring conventions, folders aren't necessary. We use solution folders for projects that are not in the specific layer that the solution is focused at. If it is the application, then projects from lower layers in the stack will be found in solution folders, sometimes multiple folders one per layer. We use solution folders for assembly version and signature files and create links to them within each project. That way we only have to update one file when changing the version number. We use seperate solutions for seperate concerns and lots of assembly linking if required. So, we try to cut down on how many projects we have in a single solution and make sure our solutions for a project take a proper directory structure from our root drive. We then mirror the same structure on the build server, so when we do a check in, it gets the same assembly linkages on the build server (and if we've configured the build correctly in the same build order/triggers/etc), so we don't have any issues with that. And as well try to make each atomic element of our systems reusable across many projects (working in-house for a firm makes this easier than in a consulting role, I bet :). So basically we house the projects directly in the solution, and use the solution folder for any critical notes, and basically little things like FxCop - anything that may change and need to be checked in to source control (ie if our assembly changes or we add a project and we need to redo the FxCop, it gets updated in source control for the build server to pick up). We originally used them a lot in our domain model solution but in the end we broke off a lot of sub-soltuons instead. However we still have one overall solution and in there we have a few solution folders, for example we have "CRM" containing all our CRM projects and within that solution folder we have another "Test" solution folder with all the CRM test projects. Actually one nice thing about solution folders is you can hide them, which I use a lot. I use them for build files and any .template files (config.template, sql.template) that get tokenized by Nant during the build. I find I use it most for editing web.config.template, and the .build file(s) Having figured out that the solution folders were a little flaky, I opted to create empty projects to replace the solution folders and then removed them from the default build. This way I get to include all sub folders etc within my solutions.
http://codebetter.com/blogs/kyle.baley/archive/2008/02/18/solution-folders.aspx
crawl-002
refinedweb
933
70.43
Ui woes Been doing some heavy UI work, and Here are a few quirks/bugs I've found: keyboard_get_frameand associated methods don't work in fullscreen, except in portrait, and only the view was started in portrait. In landscape, or if device is rotated, we get bad values. Here is a sequence dumping out keyboard frame starting in portrait, and rotating clockwise start portrait kb frame ... = (0.0, 760.0, 768.0, 264.0) correct kb frame ... = (416.0, 0.0, 352.0, 1024.0) maybe correct if x,y,w,h are really y,x,h,w kb frame ... = (0.0, 0.0, 768.0, 264.0). Incorrect y kb frame ... = (0.0, 0.0, 352.0, 1024.0) also incorrect kb frame ... = (0.0, 760.0, 768.0, 264.0) correct again, original orientation Next, I restarted in landscape, and repeated the test start in landscape kb frame ... = (416.0, 0.0, 352.0, 768.0) hmmm. That's not right, should be 1024 width kb frame ... = (0.0, 0.0, 768.0, 264.0) nope...y is wrong kb frame ... = (0.0, 0.0, 352.0, 768.0). Still wrong kb frame ... = (0.0, 760.0, 768.0, 8.0). Nope kb frame ... = (416.0, 0.0, 352.0, 768.0) Things seem to work ok in sheet, panel, etc. but, in sheet view, the view's frame property lies about the x,y position. I guess this is because the view cannot be repositioned, however, it makes it tricky to figure out where the keyboard frame is relative to the view. callbacks like keyboard_frame_will_changecontinue to be called even after the view is closed. I'm not sure if this is a desirable situation, it can lead to funny situations that require restart ( an exception in the will change function ends up in and endless cycle that can't be fixed by going back to console, etc. changing a views size within draw()can cause strange problems. Like it seems the drawing context is set to original bounds. The issue is that, since measure_stringcan only be called from within draw(), if I want to resize the view to hold the string, there is no way to do it. Try using ui.convert_pointand ui.convert_rect. Both functions take a point/rect tuple and two views as arguments, and will translate the point/rect's coordinates from the first view's system into the second view's system. Setting Noneas one of the views will convert from/to absolute screen coordinates, so you might want to run ui.convert_rect(ui.get_keyboard_frame(), None, your_view)to get correct relative coordinates. Thanks, that solves item 2, as it should let me get the keyboard relative to a sheet. But in fullscreen, the keyboard frame returns garbage! When are you checking the keyboard frame? You may have to wait a second or two after selecting the text field, otherwise you may be measuring the keyboard while the sliding animation is still happening. If you're using iOS 8, the keyboard size may also vary because of the word preditction bar above the keyboard. I am using the argument to keyboard_frame_did _change, which seems to trigger after the animation is complete. The will and the did change method always get the same argument, only get_keyboard_frameis subject to a delay.... I have done experiments using delays, and the result is the same. See below. When running fullScreen landscape, this always reports a height of 1024, instead of width of 1024. The top box shows the delayed version, the second shows the frame passed to the did change method. Otherwise works perfectly in panel, sheet,etc import ui class testkb(ui.View): def __init__(self): self.bg_color=(1,1,0) self.t1=ui.Label(frame=(0,0,400,20)) self.t2=ui.Label(frame=(0,30,400,20)) self.t3=ui.Label(frame=(0,60,400,20)) self.t4=ui.Label(frame=(0,90,400,20)) self.t5=ui.TextView(frame=(0,120,400,20)) [self.add_subview(s) for s in [self.t1,self.t2,self.t3,self.t4,self.t5]] self.t5.begin_editing() def keyboard_frame_did_change(self,frame): if self.on_screen: self.t2.text='kb frame ... = {0:3}'.format(frame) self.t3.text='frame = {0:3}'.format(self.frame) self.t4.text='biunds = {0:3}'.format(self.bounds) ui.delay(self.update_frame,3.0) def update_frame(self): self.t1.text='delayed ={0:3}'.format(ui.get_keyboard_frame()) #print self.t1.text T=test() T.present('fullscreen') 'kay, I didn't even know that the keyboard_frame_did_changemethod is a thing. Thanks for telling me.
https://forum.omz-software.com/topic/1145/ui-woes
CC-MAIN-2021-21
refinedweb
765
65.93
Hi guys having a single problem with some code. The program is statically linked to another which is suppose to take an input from a text file into an array; and then return a pointer to the array to the main program. The text file contains 10 ints one per line and read in line by line. System calls and the cin >> stream seem to be the problems but have been trying for days to find a solution. Sorry if the code isn't great been playing around with it for days. Here is the main: #include "stdlib.h" #include "stdafx.h" #include "FileLib.h" #include <iostream> #include "amplify_dll.h" using namespace std; FileFunc myFile; // = new FileFunc; int _tmain(int argc, _TCHAR* argv[]) { int *pSignals;//The pointer to the signal file array. char fileName[280]; int state = 0; // The programs state. int signals[280]; int i; int select = 0; //Entry point for application. cout <<"To begin please load a signal file."<< endl; cout <<"Please enter a .txt file name to load:"<< endl; cout <<">"; cin.getline(fileName, 280); pSignals = myFile.LoadFile(fileName);//loads file and points to array. state = 1; if (state == 1) { cout << "Please select from the following functions:" << endl; cout << "1: Display signal files" << endl; cin >> select;//when this and the if statment are removed pointer is passed to display function as expected. if (select == 1) { myFile.Display(pSignals); } } system ("pause"); return 0; } Here is the load file function: int * FileFunc::LoadFile(char *fileName) { int *pSignals = 0; int arraySize = 0; // First variable; number of readings in the file. int i; int Signal[280];//The array which will store the signal files. ifstream myStream; myStream.open(fileName, ios::in);//opens input stream with given file name. if(!myStream){ cout << "Unable to open file with the name " << fileName << endl; return (0); } else { myStream >> Signal[0]; // reads the first number in the file and passes on to array. arraySize = Signal[0]; for(i = 1; i <= arraySize; i++){ //starts at position 1 to offset previous reading. myStream >> Signal[i]; } cout << "Load successful" << endl; pSignals = Signal;//points at the first integer in the array. return pSignals; } } Here is the display function, in future version need to out put the whole contents of the array but current just trying to read any value from it. : void FileFunc::Display(int *pSignals) { int i; int arraySize; cout << pSignals[3]; cout << pSignals[5]; cout << endl; } When the commented cin is removed the function displays the correct ints; when cin is present displays 2617860. If any other information is needed let me know. Thanks in advance. Edited 6 Years Ago by indigo.8: n/a
https://www.daniweb.com/programming/software-development/threads/263204/problem-with-pointer-values
CC-MAIN-2016-50
refinedweb
436
75.3
Design Guidelines, Managed code and the .NET Framework Continuing on the weekly series, today we posted the session on naming conventions. Thanks for watching the intro class and coming that chat. We had over 1,600 folks already watch the talk and nearly 80 folks in the chat. If you missed it you can catch it here and the chat transcript here. A couple of notes on this sessions: I mention that these naming conventions, and for that mater the design guidelines as a whole can save your company money. If you spend less time arguing about items that are subjective then you can get more done in less time. I actually had a couple of customers tell me this at last year’s TechEd. They totally see the Design Guidelines doc as a huge argument-killer and therefore a time saver. I am more than happy to help! I made the understatement of the year that Anders Hejlsberg has some experience Pascal . As you might know it was Anders that really popularized the Pascal language with the Turbo Pascal product. I learned to program with Turbo Pascal so it has been bright spot in my career to work closely with Anders on all of these guidelines we are talking about in this series. Hungarian notation – I’d stress that the ban on these is for publicly exposed APIs.. I am going to stay clear on the religion debates about how you format your source code. Can you guess what GUI framework that I am referring too? I’ll give you a hint, I would highly doubt anyone is using it today… The most recent doc on it I could find on the MSDN site is dated Jan 1997 ;-) The whole notion of breaking changes is an interesting discussion that is really applicable when you don’t control all the clients. Sometimes you can force all the clients to recompile on your new version, but other times you want those apps to be able just pick up the new version of your framework. Do take time to pause the talk and do that code review on your own… Here is the code if you need it an editable format… the idea is to spot the bad naming conventions used. public class HtmlEncoding { public const string DEFAULT_NAME = "Html3.2"; public HtmlEncoding(string strVer) {..} public string Doctypename { get {..}} public bool UseJsEncoding { get {..}} protected void _coreEncodeCharacter(char value) {..} } During the chat I’d love to hear your comments on how we’d fix it. Naming Conventions Learn why good naming is a key factor in API design, and what the recommended naming guidelines are to ensure consistency with the rest of the .NET Framework. [56k] [300k] I will be in a chat room on 1/26 1pm PST to answer questions and hear your comments on this topic. The Q&A part of these classes is always my favorite part; I hope you will take time to come. Naming Conventions [Sign up for the post session chat] Rich Type System [Sign up for the post session chat] Member Types [Sign up for the post session chat] Designing Inheritance Hierarchies [Sign up for the post session chat]
http://blogs.msdn.com/brada/archive/2005/01/21/358407.aspx
crawl-002
refinedweb
533
70.23
Opened 8 years ago Closed 8 years ago #4103 closed (fixed) Add "reverse" to url_dispatch documentation for named url patterns Description Just a small addition to the documentation for accessing named URL patterns at: See email exchange between myself and Malcolm below... On Sat, 2007-04-21 at 01:47 -0700, Michael wrote: I'm not sure if this is obvious, but the documentation at: doesn't mention how you can use your named URL patters to redirect from one view to another. It only shows how you can get the url for a view from within a template. Anyways, turns out to be pretty simple (found it in the source django_src/django/template/defaulttags.py): from django.core.urlresolvers import reverse return HttpResponseRedirect( reverse( 'your-url-name' ) ) Have I missed something and this was documented else where? Otherwise I'll raise a ticket to update the above documentation for named url patterns... We haven't documented reverse() anywhere, as far as I know. So worth filing a ticket. Thanks, Malcolm Attachments (2) Change History (6) comment:1 Changed 8 years ago by Simon G. <dev@…> - Keywords docs url_dispatch added - Needs documentation set - Needs tests unset - Patch needs improvement unset - Summary changed from Addition to url_dispatch documentation for named url patterns to Add "reverse" to url_dispatch documentation for named url patterns - Triage Stage changed from Unreviewed to Accepted Changed 8 years ago by Simon G. <dev@…> Changed 8 years ago by Simon G. <dev@…> comment:2 Changed 8 years ago by Simon G. <dev@…> comment:3 Changed 8 years ago by Simon G. <dev@…> - Has patch set comment:4 Changed 8 years ago by mtredinnick - Resolution set to fixed - Status changed from new to closed Here's a first attempt - what else needs to be commented? (take the second patch, the first has some crud in there from something else).
https://code.djangoproject.com/ticket/4103
CC-MAIN-2015-32
refinedweb
310
61.56
Miral asks for the recommended way of passing messages across processes if they require custom marshaling. There is no one recommended way of doing the custom marshaling, although some are hackier than others. Probably the most architecturally beautiful way of doing it is to use a mechanism that does perform automatic marshaling, like COM and MIDL. Okay, it’s not actually automatic, but it does allow you just give MIDL your structures and some information about how they should be interpreted, and the MIDL compiler autogenerates the marshaler. You can then pass the data back and forth by simply invoking COM methods and letting COM do the work. Architecturally beautiful often turns into forcing me to learn more than I really wanted to learn, so here’s a more self-contained approach: Take advantage of the WM_ message. This is sort of the poor-man’s marshaler. All it knows how to marshal is a blob of bytes. It’s your responsibility to take what you want to marshal and serialize it into a blob of bytes. WM_ will get the bytes to the other side, and then the recipient needs to deserialize the blob of bytes back into your data. But at least WM_ does the tricky bit of getting the bytes from one side to the other. Let’s start with our scratch program and have it transfer data to another copy of itself. Make the following changes: #include <strsafe.h> HWND g_hwndOther; #define CDSCODE_WINDOWPOS 42 // lpData -> WINDOWPOS void OnWindowPosChanged(HWND hwnd, LPWINDOWPOS pwp) { if (g_hwndOther) { COPYDATASTRUCT cds; cds.dwData = CDSCODE_WINDOWPOS; cds.cbData = sizeof(WINDOWPOS); cds.lpData = pwp; SendMessage(g_hwndOther, WM_COPYDATA, reinterpret_cast<WPARAM>(hwnd), reinterpret_cast<LPARAM>(&cds)); } FORWARD_WM_WINDOWPOSCHANGED(hwnd, pwp, DefWindowProc); } void OnCopyData(HWND hwnd, HWND hwndFrom, PCOPYDATASTRUCT pcds) { switch (pcds->dwData) { case CDSCODE_WINDOWPOS: if (pcds->cbData == sizeof(WINDOWPOS)) { LPWINDOWPOS pwp = static_cast<LPWINDOWPOS>(pcds->lpData); TCHAR szMessage[256]; StringCchPrintf(szMessage, 256, TEXT("From window %p: x=%d, y=%d, cx=%d, cy=%d, flags=%s %s"), hwndFrom, pwp->x, pwp->y, pwp->cx, pwp->cy, (pwp->flags & SWP_NOMOVE) ? TEXT("nomove") : TEXT("move"), (pwp->flags & SWP_NOSIZE) ? TEXT("nosize") : TEXT("size")); SetWindowText(hwnd, szMessage); } break; } } // WndProc HANDLE_MSG(hwnd, WM_WINDOWPOSCHANGED, OnWindowPosChanged); HANDLE_MSG(hwnd, WM_COPYDATA, OnCopyData); // WinMain // If there is another window called "Scratch", then it becomes // our recipient. g_hwndOther = FindWindow(TEXT("Scratch"), TEXT("Scratch")); hwnd = CreateWindow( "Scratch", /* Class Name */ g_hwndOther ? TEXT("Sender") : TEXT("Scratch"), WS_OVERLAPPEDWINDOW, /* Style */ CW_USEDEFAULT, CW_USEDEFAULT, /* Position */ CW_USEDEFAULT, CW_USEDEFAULT, /* Size */ NULL, /* Parent */ NULL, /* No menu */ hinst, /* Instance */ 0); /* No special parameters */ Just to make it easier to tell the two windows apart, I call the one sending the message “Sender”. (Note that my method for finding the other window is pretty rudimentary, because that’s not the point of the example.) Whenever the sender window receives a WM_ message, it sends a copy of the WINDOWPOS structure to the recipient, which then displays it in its own title bar. Things to observe: - The value you put into dwDatacan be anything you like. It’s just another DWORDof data. Traditionally, it’s used like a “message number”, used to communicate what type of data is being sent. In our case, we choose 42 to mean “The lpDatapoints to a WINDOWPOSstructure.” - The cbDatais the number of bytes you want to send, and lpDatapoints to the buffer. In our case, the number of bytes is always the same, but variable-sized data is also fine. - The lpDatacan point anywhere, as long as the memory is valid for the lifetime of the SendMessagecall. In this case, I just point it at the data given to me by the window manager. Of course, if you allocated memory to put into lpData, then the responsibility for freeing it also belongs to you. - For safety’s sake, I validate that when I get a CDSCODE_request, the associated data really is the size of a WINDOWPOS WINDOWPOSstructure. This helps protect against a rogue caller who tries to crash the application by sending a CDSCODE_with a size less than WINDOWPOS sizeof(WINDOWPOS), thereby triggering a buffer overflow. (Exercise: Under what other conditions can the size be incorrect? How would you fix that?) - The WM_copies data in only one direction. It does not provide a way to pass information back to the sender. (Exercise: How would you pass information back?) COPYDATA - The hwndFromparameter is a courtesy parameter, like dwData. There is currently no attempt to verify that the window really is that of the sender. (In practice, all that could really be verified is that the window belongs to the thread that is doing the sending, but right now, not even that level of validation is performed.) The WM_ message is suitable for small-to-medium-sized amounts of memory. Though if the amount of memory is so small that it fits into a WPARAM and LPARAM, then even WM_ is overkill. If you’re going to be passing large chunks of memory, then you may want to consider using a shared memory handle instead. The shared memory handle also has the benefit of being shared, which means that the recipient can modify the shared memory block, and the sender can see the changes. (Yes, this is one answer to the second exercise, but see if you can find another answer that tays within the spirit of the exercise.) The size of WINDOWPOS would be incorrect if one process was 32-bit and the other was 64-bit. I would this this by sending a different structure that only contained the x, y, cx, cy and flags fields. If I wanted to pass information back then I'd probably send another window message back to the first window (which you know from the wParam of the WM_COPYDATA message), although you would have to use a PostMessage instead of SendMessage to avoid deadlocks. You can of course send a WM_COPYDATA back to the "client" if you need to return data but if you need to send a lot of these messages it might be better to use SHAllocShared or some other shared memory map implementation… "No deadlock here, because a thread can process inbound sent messages while waiting for an outgoing sent message to complete. -Raymond" I don't get it. If both threads/processes are using SendMessage to call each other, wouldn't they be in a state of deadlock? 1. Process A calls SendMessage to send to Process B, and waits for process B's window procedure to return. 2. Process B's window procedure is now called, and calls SendMessage to send to process A. Now process B waits for process A to process that message. 3. Process A will never process message sent by process B because it's still waiting for B's window procedure to return. There are other message functions that seem much more appropriate in this situation. @JamesJohnston blogs.msdn.com/…/150929.aspx WM_COPYDATA is also fast. I was writing a logger process and was surprised that it would log thousands of log string per second — each send with WM_COPYDATA from another process. Impressive! @AsmGuru62: Yeah, copying a contiguous block of data from one memory location to another is very fast, especially if you know what CPU you're using and you can use that to tune the code to use the SIMD registers. Does anybody know when WM_COPYDATA was created? Obviously it had to exist for Win32 to work (because different windows could have different address spaces), but it's not clear that there was a use for it in 16-bit Windows. @Gabe: I remember noticing it in the pre-release docs for Win32 and I remember thinking it was new. As you say, Win16 doesn't need it and Win32 almost certainly does. Well that's a lot cleaner than XxxxProcessmemory. And it handles 32/64 bit correctly if your structs are defined sanely* (system structs often aren't). *local definition is suitable for use in binary file formats. @Gabe: Of course, there's nothing to stop you from sending a 0x004A message in 16-bit Windows and passing an hWnd in wParam and a COPYDATASTRUCT in lParam ;-) Hooray for WM_COPYDATA, I use it since..forever and never failed me. I disagree Ray, is not "poor-man's marshaler" but is the smart man's marshaler, KISS! I must concur with Danny, especially considering how dangerous COM is to your tech support resources due to loading broken DLLs into your process (not MS DLLs). I've been recently working on a project, where we needed to pass/share information between/with application instances running within different terminal sessions. The only way we finally found was to use UDP-sockets: the data amount was small enough not to exceed UDP packet size. Is this method OK? Is there anything more suitable? The whole task was the following: all application instances share a single list of items; if UserA in terminal session A adds/deletes an item to/from the list, UserB in terminal session B should see the changes as soon as possible. Thank you. @Virtual8086: See global named pipes. But yeah, I've found the UDP datagrams to localhost to be far more reliable to get working. Named pipes seems to have some odd resource allocation glitches that appear to be residue of an older era. @Joshua: pipes were also not suitable, because we had to send data to multiple application instances (3 and more) while pipes are somewhat like TCP-sockets allowing only 2 sides to be connected. @Gabe I checked out an old copy of Visual C++ 1.5 and it didn't seem to know about WM_COPYDATA, but it turns out that by comparison I also have a 16-year-old copy of the Platform SDK .HLP (!) file which did know about WM_COPYDATA and claims that Win32s supports it. OK… now I just learned about some re-entrancy implications that I hadn't really thought about before! Ouch.
https://blogs.msdn.microsoft.com/oldnewthing/20121019-00/?p=6293/
CC-MAIN-2016-07
refinedweb
1,652
61.46