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 |
|---|---|---|---|---|---|
This installment finishes up the series on your eDoc reader by incorporating the functionality to extract the text from PDF documents. You'll accomplish this task by using an open source Java package called PDFBox and the not-so-well-documented Cocoa-Java bridge.
In order to empower you as a more capable developer, I'm writing this article a little differently than some others you've read. Instead of just handing you a picture-perfect project and explaining how it works, I'm going to lead you through the development process as I went through it and troubleshoot problems as they come up.
My intentions are to give you more insight into some of the unfamiliar problems you may encounter when bridging different languages. When we're finished here, you'll have a deployable standalone application that makes reading your eDocs easy, and you'll be able to incorporate existing Java into your other projects with minimal hassle.
The ability to work with PDF files provides your application with a uniform approach to work with almost any text format you can imagine. For example, instead of removing the tags from HTML or saving RTF as text, you could just as easily print these as PDF files and then extract the text from the PDFs. But why use Java to do this?
In short, there's a nice Java package written that does the job, but there's not an Objective-C equivalent (if there were, it would probably be preferable to use it instead). Consequently, we have a couple of options here. Two of them are obvious: rewrite the Java package in Objective-C, or interface to the Java package. We'll choose the latter.
First and foremost, back up your existing work! The quickest way is to just compress it into a tarball. You can do this to your entire project directory in Terminal. Typing man tar gives you more information on tar if you need it. If you really want to be slick, however, you can use CVS from Terminal or Source Code Management (SCM) from Xcode. With that said, go to PDFBox.org and download version 0.6.7. If there's a newer release, feel free to try it, but version 0.6.7 has been verified to work with the procedure outlined in this article. PDFBox is released under the BSD license, which very non-restrictive in terms of use. Read it and understand what will mean if you decide to distribute any work you produce with PDFBox. Once your download completes, extract the files and place them in a convenient location.
man tar
tar
Related Reading
Learning Cocoa with Objective-C
By James Duncan Davidson, Apple Computer, Inc.
Next, open your working project from part two of this series in Xcode and follow along very closely as we get the Java bridge working. Seemingly minute differences in some of the following steps can result in frustrating error messages that aren't the most obvious ones to fix that you'll ever see. To incorporate Java classes into our project, we'll create another target that groups these files. This is handy, because the result of all of these files in the target is a single JAR file that encapsulates things nicely.
Do the following to add another target to your project:
JavaClasses
Given the new JavaClasses target, we'll now add some classes to it. For now, just get the files added. We'll backstep and define their bodies in a moment.
PodReader
In order to be official about informing the compiler about the Java method we'll be invoking from our Objective-C code, we define an Objective-C header file that contains this information. Let's add this file to the project.
What have we done so far? We defined a target called JavaClasses, specified some Java classes and added them to it, and then added an Objective-C header file to the PodReader target that informs the compiler that this Java magic isn't really magic at all--it's simply a matter of referencing some code from elsewhere. With that said, let's fill in these empty files.
The first body we'll define is for PDFBoxBridge.java. Download it here. If you look at your PDFBox package you downloaded from PDFBox.org, you'll notice that PDFBoxBridge.java is almost exactly the same as installDir/PDFBox-0.6.7a/src/org/pdfbox/ExtractText.java with just a couple of differences annotated in the header comments and inline. The idea was to change as little as possible and to clearly document any changes made to the file.
The file PDFBoxWrapper.java offers a little more than first meets the eye. For now, notice that this class offers a public method that receives an NSArray of arguments (the PDF source file, among other possible things) and extracts the text from the PDF file using the PDFBoxBridge class from above.
NSArray
PDFBoxBridge
Take note that we pass in an NSArray to extractText and have to first convert it to a Java array "by hand," since extractText is a Java method, and its signature expects a Java array. Still, we're able to "seamlessly" pass in an NSArray to PDFBoxWrapper by importing the Java NSArray class. Once we have the Java NSArray, we can easily manipulate it to get a pure Java array of String[]. The lesson to take from this is that we cannot seamlessly pass an NSArray (even if it's filled only with NSStrings) directly to a Java method that requires an array of String[].
extractText
PDFBoxWrapper
String[]
NSString
/* PDFBoxWrapper.java*/
import com.apple.cocoa.foundation.NSArray;
public class PDFBoxWrapper {
private PDFBoxBridge bridge;
public PDFBoxWrapper() {
bridge = new PDFBoxBridge();
}
private String[] convertNSArrayToJavaArray(NSArray array) {
NSArray newArray = new NSArray(array);
String[] javaArray = new String[newArray.count()];
newArray.getObjects(javaArray);
return javaArray;
}
public void extractText( NSArray args ) throws Exception {
try{
bridge.extractText(this.convertNSArrayToJavaArray(args));
}
catch (Exception e) {
System.out.println("Exception in extractText in PDFBoxWrapper");
}
}
}
At this point, the Java classes are in place, but how do we relate our Objective-C code to the Java code? The simple header file below takes care of this for us. It specifies the method signature and vouches that the class PDFBoxWrapper exists, offers the method extractText:, and is accessible.
extractText:
/*JavaInterfaces.h*/
@interface PDFBoxWrapper : NSObject
{}
- (void)extractText:(NSArray*)array;
@end
We're now ready to replace the stub we left for handling PDF files back in the AppController.m source file, which we designed last time. You should change the first block of your if statement in copyIt: to be the following code block. We'll address the "prelude shell script" comment in detail in a moment.
if
copyIt:
[progressIndicator startAnimation:nil];
if ([[fileName pathExtension] isEqualToString:@"pdf"]) {
//load the vm
id vm = NSJavaSetupVirtualMachine();
//embedded jar files. Loading the PDFBox jar files here didn't work.
//In short, the best fix was to add a prelude shell script
NSMutableArray* jarFiles = [NSMutableArray arrayWithObject:
[[NSBundle mainBundle] pathForResource:@"JavaClasses" ofType:@"jar"]];
NSJavaClassesFromPath(jarFiles, nil, YES, nil);
PDFBoxWrapper* wrapper = NSJavaObjectNamedInPath(@"PDFBoxWrapper", nil);
NSString* filePrefix =
[[[sourceFile stringValue]
lastPathComponent]
stringByDeletingPathExtension];
NSString* tempFile =
[[@"/tmp/" stringByAppendingString:filePrefix]
stringByAppendingString: @".podreaderTEMP"];
NSArray* args = [[NSArray alloc]
initWithObjects:[sourceFile stringValue],
tempFile,
nil];
[wrapper extractText:args];
//used alloc, so "args" has a retain count of 1. release it
[args release];
[chunker chunkIt:tempFile
toDir:[[destDir stringValue] stringByExpandingTildeInPath]
withSeparator:[separatorValue stringValue]];
}
else if ([[fileName pathExtension] isEqualToString:@"txt"]) {
This should be fairly straight forward once you've looked it over. We start up a Java Virtual Machine (JVM), specify that a JAR file called JavaClasses (remember that target you added?) should be in the application bundle and tell it to load the classes from that location. We proceed to use the class you've seen called PDFBoxWrapper to extract the text from the PDF document to a temporary file located in the /tmp directory. From there things are just like before: we use the temporary file created and process it using the same text handling routine like last time.
Now, you're very close to having compilable code within Xcode, but you're not quite there. Take a moment and ask yourself what's missing. If you need a hint, change the "Active Target" using the popup button in the upper left-hand corner of Xcode to "JavaClasses" and try to compile. Take note of the error messages you receive.
Change the active target from "PodReader" (currently set) to "JavaClasses"
A moment later: while in deep meditation it occurred to you that all the Java references in PDFBoxBridge.java are undefined at the moment, and they must be defined for successful compilation to occur. By inspecting PDFBoxBridge.java, you astutely observed that the JAR file PDFBox-0.6.7a.jar (distributed with PDFBox), in particular, must be included in the project. Even though references to log4j-1.2.8.jar are commented out, it turns out that PDFBox-0.6.7a.jar includes references to log4j-1.2.8.jar, so it must also be added to the project. The reason for adding these references is to resolve the compile time errors.
To add these files, control-click on the JavaClasses target in the left-hand pane of Xcode, and then choose Add -> Existing Files.... Navigate to where you extracted PDFBox and add the log4j-1.2.8.jar file from the /PDFBox-0.6.7a/external directory. When adding the file, check the box at the top to copy the file into the project and make sure only the JavaClasses target is checked. Repeat the process for the PDFBox-0.6.7a.jar file in the /PDFBox-0.6.7a/lib directory. In the left-hand pane, drag each of the files that appears in the very top to Resources to keep things nice and tidy. Note that in the JavaClasses target each of these JAR files appears under Frameworks & Libraries. If you plan on passing your work onto anyone else, you're required by the BSD license to add a copy of the PDFBox LICENSE file to your source at this time. Check your project directory in Finder or Terminal to make sure that these files are actually copied. At this point, you can successfully compile the JavaClasses target.
Add the JAR files packaged with PDFBox to your project
Change the build Active Target in the upper left-hand corner of Xcode to PodReader and try to build. You should get an error or two. Being the good detective that you are, you see that in AppController.m there's an undefined reference to our PDFBoxWrapper class, so you add #import "JavaInterfaces" to the top of AppController.m, recompile, and all is well for compilation. Without that directive, the file JavaInterfaces.h doesn't exist, as far as the compiler is concerned.
#import "JavaInterfaces". | http://www.macdevcenter.com/pub/a/mac/2005/01/07/ipod_reader.html?page=1 | CC-MAIN-2016-30 | refinedweb | 1,807 | 55.44 |
Question:
Our project is using many static libraries to build the application. How can we make sure we are using release version of libraries in release build of application?
We are making mistakes by taking debug library in release application build.
I am looking for an elegant way in which I can write a module in that we can check whether a particular library is release or debug and report it if not matching. Our application is written in C/C++. (Platform MSVC & GCC)
Solution:1
The normal approach is eithr to give the libraries different names or store them in different directories, such as Debug and Release. And if your build is correctly automated, I can't see how you can make mistakes.
Solution:2
Yes. You can check the
Characteristics field of the
IMAGE_FILE_HEADER structure of the file. If the library is a release build, then bit 0x0200 (
DEBUG_STRIPPED) will be set; on a debug build, it will be clear.
You can find technical information on the PE Format used by Windows EXEs and DLLs, to see how to retrieve that structure, in various places on the 'net (such as here).
Solution:3
Can you not solve this using naming conventions (i.e.,
foo_rel.a and
foo_dbg.a )?
Solution:4
Naming conventions aside, if you're on a unix-like system, you can probably parse the output of:
objdump -g mylib.a
If you only get empty lines or lines starting with object file names, then you have no debug information in the library.
Note that this does not generally mean that the library is "release" or "debug", but it may mean it in your case.
Solution:5
How about having a simple function which returns the version of the library? Return different things based on your build being debug or release. Call that function at the start of your app and report the error.
Solution:6
Normally one would distinguish the versions using a slightly different names. For example under debug builds all the libraries are suffixed with a character 'd' before their extension. Ex.
commonUtilsd.lib Under release mode the same would be
commonUtils.lib. This approach IMHO is simpler and cleaner. In MSVC use can specify the output filename under
Librarian-->General-->Output File
Another recommendation is to have these output files in the configuration directory. i.e. have debug-version in the Debug folder and release-versions under Release folder. Again under MSVC this can be done generically using the $(ConfigurationName) IDE-macro. And attach the right path in the lookup directories during build.
Solution:7
I use and successfully tested this code:
using System.Diagnostics; FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(fileName); return fvi.IsDebug;
Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
EmoticonEmoticon | http://www.toontricks.com/2018/05/tutorial-how-to-identify-if-library-is.html | CC-MAIN-2018-43 | refinedweb | 470 | 56.55 |
In the previous two posts (Read Data from Facebook and Publish Facebook Posts) the topic was the connection to Facebook using the Graph API. This is a simple HTTP based API, over which via HTTP requests data of Facebook can be accessed.
Today I want to explain, how to connect to the Facebook Chat via C#, which is based upon the XMPP (earlier Jabber) protocol.
XMPP is a communication protocol basing upon XMP, which is mainly used for instant messaging.
Some known programs, like Google Talk and WhatsApp use this protocol, many others, e.g. ICQ, Skype and Facebook offer a possibility for connecting.
The XMPP protocol is easy to understand and very structured, so that we can connect without much code to the Facebook chat and send and recceive messages.
Since the chat and the "normal" messaging function are not separated as earlier anymore, we can also send and receive conventional messages with the code.
Reading out the contact list is also possible.
I will introduce the chat step by step. Today I will show the inclusion of XMPP and the logging in to the Facebook service.
In the next days the following posts will come online:
Reading Out the Contact List
Sending Messages
Receiving Messages
Complete Chat Client
Determine Status "Typing"
Advanced Chat Client
Now let us come to the first part. In theory we can write our own XMPP framework, which then transmits data via sockets etc.
I will use an external libary though, nameley agsXMPP, which saves us from a lot of work.
Please install this first and install it.
If we want to use it in the project, we have to add a reference to it. For that we click on "Add Reference - Browse" and select in the installation directory \agsxmpp\bin\(matching .Net Version, probably 3.5)\(Debug | Release)\agsXMPP.dll.
In the next posts we will need the following using directives:
using agsXMPP;
using agsXMPP.protocol.client;
using agsXMPP.protocol.iq.roster;
using agsXMPP.Collections;
Then we can prepare the connection to the Facebook server (chat.facebook.com) with:
XmppClientConnection xmpp = new XmppClientConnection("chat.facebook.com");
Before the actual logging in we store a function as reaction to the OnLogin event. This is, because the logging in occurs asynchronous, as soon as it is done the event occurs:
xmpp.OnLogin += new ObjectHandler(OnLogin);
The function looks as follows, basically all commands it are optional, the last 3 lines of codes change our login status to online:
private void OnLogin(object sender)
{
MessageBox.Show("Login successful.");
Presence p = new Presence(ShowType.chat, "Online");
p.Type = PresenceType.available;
xmpp.Send(p);
}
After that we can connect with our data. Here the Facebook name (the name in the URL of the profile, e.g. for hans.wurst) and the password is needed:
xmpp.Open("name", "password");
The complete code could look as follows:("", "");
}
private void OnLogin(object sender)
{
MessageBox.Show("Login successful.");
Presence p = new Presence(ShowType.chat, "Online");
p.Type = PresenceType.available;
xmpp.Send(p);
}
}
}
hi! Good work!
I really appreciate the work you done!
NO DOWNLOAD LINK..!
Will you please mail me the Facebook Chat related Samples..!
One more thing can we use same for ASP.NET Web Applications?
Please write some blogs on FacebookChat in Asp.net and let me know..!
Thanks,
Hi, That this example looking very nice.
Please provide me c# code for facebook chat.
My email is sudeshchhipa102@gmail.com
I'll use this on windows application.
May I use this on web applications?
Thanks
Hi guys,
I sent you the project via Email.
I created the code using the publicily available Facebook documentation which is open for everybody to use, whether you are allowed to use it though (commercially), you have to check with Facebook.
hi nice work man....
please send me code for help...
asgharali.ntu@gmail.com
Hi!
I think there's something wrong in my code, because it cannot connect facebook (It not show messagebox "Login successful"). Do you have the method to show connection status or something like this?
If not, can you please mail me this c# code facebook chat.
my e-mail is kwanchanok1987@hotmail.com
Thanks.
hi Oliver, please send the code om my email : batrashish@gmail.com
Regards,
Ashish
Hi guys,
due to many requests, like described in the corresponding post the code for a complete Facebook chat client is available on
Enjoy!
Thanks man. u are awesome
thanks man
Kindly send me as soon as possible
rehankhantht@gmail.com
Tutorials is not run ? Can you explain for me okay? I have provided url and pass.
Thanks you very much.
Hey guys,
as mentioned in the post unfortunately this does no longer work.
Facebook disabled this function :-(
hi guy
Please sent your code on my email.Thank you very much. | http://csharp-tricks-en.blogspot.de/2013/10/connect-to-facebook-chat.html | CC-MAIN-2018-09 | refinedweb | 799 | 68.16 |
DBIx::XMLServer - Serve data as XML in response to HTTP requests
use XML::LibXML; use DBIx::XMLServer; my $xml_server = new DBIx::XMLServer($dbh, "template.xml"); my $doc = $xml_server->process($QUERY_STRING); die "Error: $doc" unless ref $doc; print "Content-type: application/xml\r\n\r\n"; print $doc->toString(1);
This module implements the whole process of generating an XML document from a database query, in response to an HTTP request. The mapping from the DBI database to an XML structure is defined in a template file, also in XML; this template is used not only to turn the data into XML, but also to parse the query string. To the user, the format of the query string is very natural in relation to the XML data which they will receive.
All the methods of this object can take a hash of named parameters instead of a list of parameters.
One
DBIx::XMLServer object can process several queries. The following steps take place in processing a query:
my $xml_server = new DBIx::XMLServer( $dbh, $template_doc [, $template_node] ); my $xml_server = new DBIx::XMLServer( dbh => $dbh, doc => $template_doc, template => $template_node, maxpagesize => $maxpagesize );
The constructor for
DBIx::XMLServer takes two mandatory arguments and two optional arguments.
$dbh
This is a handle for the database; see DBI for more information.
$template_doc
This is the XML document containing the template. It may be either an
XML::LibXML::Document object or a string, which is taken as a file name.
$template_node
One template file may contain several individual templates; if so, this argument may be used to pass an
XML::LibXML::Element object indicating which template should be used. By default the first template in the file is used.
$maxpagesize
This option may be used to limit the number of records than will be returned in a query. The user can choose a page size smaller than this by using the
pagesize option on their query (see below), but they will not be allowed to request a page size larger than this maximum.
my $result = $xml_server->process( $query [, $template_node] ); my $result = $xml_server->process( query => $query, template => $template_node, rowcount => $rowcount, userformat => $userformat );
This method processes an HTTP query and returns an XML document containing the results of the query. There are one mandatory argument and two optional arguments.
$query
This is the HTTP GET query string to be processed.
$template_node
As above, this may indicate which of several templates is to be used for this query. It is an
XML::LibXML::Element object.
$rowcount
It is possible to limit the number of rows returned in one query, either in response to a user request (by using the
pagesize option, see below) or by passing the
maxpagesize option when creating the
DBIx::XMLServer object. In these cases it may be useful to know the total number of rows that would have been returned had no limit been in place. The number of rows can be put into the output XML document using the <sql:meta element in the template (see below). This argument chooses how this information should be obtained from the database.
Passing
rowcount => 'FOUND_ROWS' tells the module to use the SQL_COUNT_FOUND_ROWS option and the FOUND_ROWS function. If your database supports these, use this option.
Passing
rowcount => 'COUNT' means that a second query will be done after the main database query, of this form:
SELECT COUNT(*) FROM ... WHERE ...
$userformat
Setting this to a true value allows the user to choose between several templates in the file by specifying the
format option in the query string.
The return value of this method is either an
XML::LibXML::Document object containing the result, or a string containing an error message. An error string is only returned for errors caused by the HTTP query string and thus the user's fault; other errors, which are the programmer's fault, will croak.
This example is taken from the tests included with the module. The database contains two tables.
Table dbixtest1: +----+--------------+---------+------+ | id | name | manager | dept | +----+--------------+---------+------+ | 1 | John Smith | NULL | 1 | | 2 | Fred Bloggs | 3 | 1 | | 3 | Ann Other | 1 | 1 | | 4 | Minnie Mouse | NULL | 2 | | 5 | Mickey Mouse | 4 | 2 | +----+--------------+---------+------+ Table dbixtest2: +----+----------------------+ | id | name | +----+----------------------+ | 1 | Widget Manufacturing | | 2 | Widget Marketing | +----+----------------------+
The template file (in t/t10.xml) contains the following three table definitions:
<sql:table <sql:table <sql:table
The template element is as follows:
<sql:template <employees> <sql:record> <employee id="foo"> <sql:field <name> <sql:field </name> <manager> <sql:field </manager> <department> <sql:field </department> </employee> </sql:record> </employees> </sql:template>
The query string name=Ann* produces the following output:
<?xml version="1.0"?> <employees> <employee id="3"> <name>Ann Other</name> <manager>John Smith</manager> <department>Widget Manufacturing</department> </employee> </employees>
The query string department=Widget%20Marketing&fields=name produces the following output:
<?xml version="1.0"?> <employees> <employee id="4"> <name>Minnie Mouse</name> </employee> <employee id="5"> <name>Mickey Mouse</name> </employee> </employees>
The main part of the template file which controls DBIx::XMLServer is the template element. This element gives a skeleton for the output XML document. Within the template element is an element, the record element, which gives a skeleton for that part of the document which is to be repeated for each row in the SQL query result. The record element is a fragment of XML, mostly not in the sql: namespace, which contains some <sql:field> elements.
Each <sql:field> element corresponds to a point in the record element where data from the database will be inserted. Often, this means that one <sql:field> element corresponds to one column in a table in the database. The field has a type; this determines the mappings both between data in the database and data in the XML document, and between the user's HTTP query string and the SQL WHERE clause.
The HTTP query which the user supplies consists of search criteria, together with other special options which control the format of the XML output document. Each criterion in the HTTP query selects one field in the record and gives some way of limiting data on that field, typically by some comparison operation. The selection of the field is accomplished by an XPath expression, normally very simply consisting just of the name of the field. After the field has been selected, the remainder of the criterion is processed by the Perl object corresponding to that field type. For example, the built-in text field type recognises simple string comparisons as well as regular expression comparisons; and the build-in number field type recognises numeric comparisons.
All these criteria are put together to form the WHERE clause of the SQL query. The user may also use the special fields=... option to select which fields appear in the resulting XML document; the value of this option is again an XPath expression which selects a part of the record template to be returned.
Other special options control how many records are returned on each page, which page of the results should be returned, and may choose one of several templates in the file.
The template to use for a query is chosen as follows:
DBIx::XMLServer::process()and the user has chosen a template with the format option in the query string, that template is used.
DBIx::XMLServer::process(), then that template is used.
DBIx::XMLServerobject, then that template is used.
The behaviour of DBIx::XMLServer is determined entirely by the template file, which is an XML document. This section explains the format and meaning of the various elements which can occur in the template file.
All the special elements used in the template file are in the namespace associated to the URI. In this section we will suppose that the prefix sql: is bound to that namespace, though of course any other prefix could be used instead.
The document element of the template file must be an <sql:spec> element. This element serves only to contain the other elements in the template file.
Contained in the root element are elements of three types:
We now describe each of these in more detail.
A field type definition is given by a <sql:type> element. Each field in the template has a type. That type determines: how a criterion from the query string is converted to an SQL WHERE clause for that field; how the SQL SELECT clause to retrieve data for that field is created; and how the resulting SQL data is turned into XML. For example, the standard date field type can interpret simple date comparisons in the query string, and puts the date into a specific format in the XML.
Each field type is represented by a Perl object class, derived from
DBIx::XMLServer::Field. For information about the methods which this class must define, see DBIx::XMLServer::Field. The class may be defined in a separate Perl module file, as for the standard field types; or the methods of the class may be included verbatim in the XML file, as follows.
The <sql:type> element has one attribute, name, and four element which may appear as children.
The name attribute defines the name by which this type will be referred to in the templates.
If the Perl code implementing the field type is contained in a Perl module in a separate file, this element is used to give the name of the module. It should contain the Perl name of the module (for example,
DBIx::XMLServer::NumberField).
<sql:type <sql:module>DBIx::XMLOut::NumberField</sql:module> </sql:type>
Instead of the <sql:module> element, the <sql:type> element may have separate child elements defining the various facets of the field type.
This element contains the name of a Perl module from which the field type is derived. The default is
DBIx::XMLServer::Field.
This element contains the body of the
select method (probably inside a CDATA section).
This element contains the body of the
where method (probably inside a CDATA section).
This element contains the body of the
join method (probably inside a CDATA section).
This element contains the body of the
value method (probably inside a CDATA section).
This element contains the body of the
init method (probably inside a CDATA section).
Any SQL table which will be accessed by the template needs a table definition. As a minimum, a table definition associates a local name for a table with the table's SQL name. In addition, the definition can specify how this table is to be joined to the other tables in the database.
Note that one SQL table may often be joined several times in different ways; this can be accomplished by several table definitions, all referring to the same SQL table.
A table definition is represented by the <sql:table> element, which has no content but several attributes.
This mandatory attribute gives the name by which the table will be referred to in the template, and also the alias by which it will be known in the SQL statement.
This mandatory attribute gives the SQL name of the table. In the SELECT statement, the table will be referenced as <sqlname> AS <name>.
This attribute specifies the name of another table to which this table is joined. Whenever a query involves a column from this table, this and the following attributes will be used to add an appropriate join to the SQL SELECT statement.
This attribute specifies the type of join, such as LEFT, RIGHT, INNER or OUTER.
This attribute specifies the ON clause used to join the two tables. In the most common case, the following two attributes may be used instead.
This attribute gives the column in this table used to join to the other table.
This attribute gives the column in the other table used for the join. Specifying keycolumn and refcolumn is equivalent to giving the on attribute value
<this table's name>.<keycolumn> = <other table's name>.<refcolumn> .
A template file must contain at least one <sql:template> element. This element defines the shape of the output document. It may contain arbitrary XML elements, which are copied straight to the output document. It also contains one <sql:record> element, which defines that part of the output document which is repeated for each row returned from the SQL query.
Further, the template element may contain <sql:meta> elements which indicate that certain information about the query should be inserted into the output document.
As the output document is formed from the content of the <sql:template> element, it follows that this element must have exactly one child element.
The <sql:template> may have the following attributes:
This optional attribute gives a unique identifier to the template. The user may, if allowed, choose which template to use by specifying the format option in the query string together with this identifier.
This mandatory attribute specifies the main table for this template, to which any other tables will be joined.
In the HTTP query string, the user must refer to parts of the template. To avoid them having to specify namespaces for these, this attribute gives a default namespace which will be used for unqualified names in the query string.
Each template contains precisely one <sql:record> element among its descendants. This record element defines that part of the output XML document which is to be repeated once for each row in the result of the SQL query. The content of the record element consists of a fragment of XML containing some <sql:field> elements; each of these defines a point at which SQL data will be inserted into the record. The <sql:record> must have precisely one child element.
It is also to the structure inside the <sql:record> element that the user's HTTP query refers.
The <sql:record> element has no attributes.
The record element will contain several <sql:field> elements. Each of these field elements defines what the user will think of as a field; that is, a part of the XML record which changes from one record to the next. Normally this will correspond to one column in an SQL table, though this is not obligatory.
A field has a type, which refers to one of the field type definitions in the template file. This type determines the mappings both between SQL data and XML output data, and between the user's query and the SQL WHERE clause.
The <sql:field> element may have the following attributes:
This mandatory attribute gives the type of the field. It is the name of one of the field types defined in the template file.
This attribute specifies which table needs to be joined to the main table in order for this field to be found. (Note: this attribute is only read by the field type class's
join method. If that method is overridden, this attribute may become irrelevant.)
If this attribute is set, the contents of the field will not be returned as a text node, but rather as an attribute on the <sql:field> node's parent node. The value of the attribute attribute gives the name of the attribute on the parent node which should be filled in with the value of this field. When this attribute is set, the parent node should always have an attribute of that name defined; the contents are irrelevant.
This attribute gives the SQL SELECT expression which should be evaluated to find the value of the field. (Note: this attribute is only ever looked at in the field type class's
select method. If this method is overridden, this attribute need not necessarily still be present.)
This attribute determines the action when the field value is null. There are three possible values:
The field is omitted from the result, but the parent element remains.
The parent element is omitted from the record
The parent element has the xsi:nil attribute set.
Any element in the record may have the Boolean attribute sql:omit. If this attribute is set, then this element will be omitted from any record in which the element is empty (because child elements have been omitted).
The <sql:meta> element is used for putting information about the query into the output document. The information is selected by the type attribute of the element. The following type attributes are recognised:
This gives the original query string passed to DBIx::XMLServer.
This gives the page number within the results, as selected by the page= option in the query string.
This gives the page size, as selected by the pagesize= option in the query string.
This gives the SQL query which was executed to produce the results.
This gives the number of rows which the query would have returned, had it not been for the page= and pagesize= options. To tell the module how to find this information, set the rowcount option when processing the request (see above).
The <sql:meta> element in the template will be replaced by the corresponding string in the output document. Alternatively, it is possible to place the string into the output document as an attribute to the parent element of the <sql:meta> element. To do this, include an attribute attribute="name" on the <sql:meta> element, where name is the local name of the attribute. To add a namespace to the attribute, additionally include an attribute namespace="foo" on the <sql:meta> element, replacing foo with whatever namespace should be used.
The HTTP query string may contain certain special options which are not interpreted as criteria on the records to be returned, but instead have some other effect.
This option selects which part of each record is to be returned. In the absence of this option, an entire record is returned for each row in the result of the SQL query. If this option is set, its value should be an XPath expression. The expression will be evaluated in the context of the single child of the <sql:record> element and should evaluate to a set of nodes; the part of the record returned is the smallest subtree containing all the nodes selected by the expression.
These options give control over how many records are returned in one query, and which of several pages is returned. To put a limit on the page size which can be requested, use the maxpagesize option when creating the
DBIx::XMLServer object. By default there is no limit.
This option controls how records are ordered in the output document. The <list> should be a comma-separated list of XPath expressions, each optionally followed by a space and the string ascending or descending. Each of these XPath expressions is evaluated within the context of the single child of the <sql:record> element and should select one or more fields; these fields are used to order the result records. Fields are used in the order that they appear in the list; if a single list element selects more than one field, they are used in document order.
When a
DBIx::XMLServer object is created, the template file is parsed. A new Perl module is compiled for each field type defined.
The
process() method performs the following steps.
wheremethod called, being passed the remainder of the fragment of the HTTP query string. The result of the
wheremethod is added to the WHERE clause; all criteria are combined by AND.
selectmethod of each of the <sql:field> elements left after this pruning.
joinmethods of all the tables which are referred to either in the search criteria, or by any of the field to be returned.
valuemethod of the corresponding field type.
There are quite a lot of stray namespace declarations in the output. They make no difference to the semantic meaning of the markup, but they are ugly. I gather that XML::LibXML will provide the means to remove them in the near future.
The way we build JOIN expressions isn't very clever, and probably doesn't work for anything more than the simplest situations.
The way we add a default prefix to every XPath expression is a bit of a hack. I think the only way to fix this is to wait for XPath 2.0 to be widely available.
This module has been written to use MySQL and has only been tested on that platform. I would be interested to hear from users who have been able to make it work on other platforms.
Martin Bright <martin@boojum.org.uk>
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. | http://search.cpan.org/dist/DBIx-XMLServer/XMLServer.pm | crawl-002 | refinedweb | 3,419 | 61.16 |
I am trying to write a program that will allow me to capture packets from an Ethernet Line. Here are the logistics The program has to be a C program and it has to run on windows XP. Here is what i've gathered so far from other people's programs:.Code:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h> /* close() */
#include <string.h> /* memset() */
#define LOCAL_SERVER_PORT 100
#define MAX_MSG 500
int main(int argc, char *argv[])
{
int sd, rc, n, cliLen;
struct sockaddr_in cliAddr, servAddr;
char msg[MAX_MSG];
/* socket creation */
sd=socket(AF_INET, SOCK_DGRAM, 0);
if(sd<0) {
printf("%s: cannot open socket \n",argv[0]);
exit(1);
}
/* bind local server port */
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
servAddr.sin_port = htons(LOCAL_SERVER_PORT);
rc = bind (sd, (struct sockaddr *) &servAddr,sizeof(servAddr));
if(rc<0) {
printf("%s: cannot bind port number %d \n",
argv[0], LOCAL_SERVER_PORT);
exit(1);
}
printf("%s: waiting for data on port UDP %u\n",
argv[0],LOCAL_SERVER_PORT);
/* server infinite loop */
while(1)
{
/* init buffer */
memset(msg,0x0,MAX_MSG);
/* receive message */
cliLen = sizeof(cliAddr);
n = recvfrom(sd, msg, MAX_MSG, 0,(struct sockaddr *) &cliAddr, &cliLen);
printf("Fail\n");
if(n<0)
{
printf("%s: cannot receive data \n",argv[0]);
continue;
}
/* print received message */
printf("%s: from %s:UDP%u : %s \n",
argv[0],inet_ntoa(cliAddr.sin_addr),
ntohs(cliAddr.sin_port),msg);
}/* end of server infinite loop */
return 0;
}
Sorry i should have added a few things, first is that this is only the a part of the program i need to write. I need to capture and condition UDP packets from some instruments that i have running. I've tryed using many different ports, i've looked up these ports in the Windows command window. After doing some research, i've found that Windows wants exclusive control over the ports it is using. I've used wireshark and i can caputure packets that way but i can't condition the data using it. I need to know/find a way to unblock these ports. Thank you! | http://cboard.cprogramming.com/networking-device-communication/118326-ethernet-packet-capture-printable-thread.html | CC-MAIN-2014-52 | refinedweb | 355 | 57.77 |
01:25 PM.
The world is a dangerous place to live; not because of the people who are evil, but because of the people who don't do anything about it.
Albert Einstein
Hi guys,
The Sfc scan came but with corruptions but couldn't fix them.
I have the log file it created but yeah 2 megs of text ... and dont really know what I am looking for ....
Greetz Cider..
Curious could you please give more details about the laptop? ie OS, specs etc etc
Also not sure but maybe give this url a look at>
i typed the 0x80041003 code into google and this was 1 of the results that appeared.
Last edited by t34b4g5; July 23rd, 2009 at 03:16 PM.
Hey Buddy,
Acer , running Vista Business 32 bit.
Quite a decent laptop as its the boss ...
Ill check out the link
Similar to what t34b4g5 said:
from: Microsoft Developer Network
Allowing Users Access to a Specific WMI Namespace
You can allow or disallow users access to a specific WMI namespace by setting the "Remote Enable" permission in the WMI Control for a namespace. If a user tries to connect to a namespace they are not allowed access to, they will receive error 0x80041003. By default, this permission is enabled only for administrators. An administrator can enable remote access to specific WMI namespaces for a nonadministrator user.
The following procedure sets remote enable permissions for a non-administrator user.
To set remote enable permissions
Connect to the remote computer using the WMI Control.
For more information about the WMI Control, see Setting Namespace Security with the WMI Control.
In the Security tab, select the namespace and click Security.
Locate the appropriate account and check Remote Enable in the Permissions list.
That's Officer 11001001 to you...
Now you see me | Now you don't
"Relax, Bender; It was just a dream. There's no such thing as two." ~ Fry
sometimes my computer goes down on me
Hi,
I jsut gave everyone the permission 0_o and the problem has dissapeared.
Forum Rules | http://www.antionline.com/showthread.php?278361-Laptop-freeze-totally&p=950347&viewfull=1 | CC-MAIN-2018-17 | refinedweb | 344 | 64.41 |
Problem Statement
In this problem, we are given a non-negative integer. We have to convert the integer in a such a format, in which there will be some dots which separates all thousands, i.e. there are dots after each 3 places from right.
Example
#1
n = 987
"987"
#2
n = 123456789
"123.456.789"
Explanation:
The number is 123456789. The rightmost dot will be 3 places from right. So, seeing from right, we will leave 9,8 and 7 behind and put a dot between 6 and 7. Then after leaving 6,5 and 4 behind, we will put a dot between 3 and 4.
Now leaving 3,2 and 1 behind, we would place a dot only if there would be more number on left because . should be between two numbers according to the question.
Thus we will not place any dot.
Approach
First of all, we are converting the number into string (let str). Then we are traversing the string str from right. We are using a for loop for this. In each loop we are inserting its three digits followed by a dot.
But after each digit insertion, we will check if we have reached out of the left bound of the str. If yes, then we will break the loop. Otherwise, we will keep inserting the 3 digits and then 1 dot.
Note that the 3rd checking to insert a dot is the crucial one, which will be used in scenarios like 123 or 123.456 or 123.456.789 where we don’t need to insert a dot before leftmost digit.
Because we are inserting the characters from right to left thus our created string needs to be reversed to get the final answer. Thus, after reversing the string, return it.
Implementation
C++ Program for Thousand Separator Leetcode Solution
#include <bits/stdc++.h> using namespace std; string thousandSeparator(int n) { string str=to_string(n); stringstream ss; for(int i=str.length()-1;i>=0;){ ss<<str[i];//inserting 1st digit i--; if(i==-1)break;//checking if we are out of left bound ss<<str[i];//inserting 2nd digit i--; if(i==-1)break;//checking if we are out of left bound ss<<str[i];//inserting 3rd digit i--; if(i==-1)break;//checking if we are out of left bound ss<<".";//after 3 digits insertion, finally inserting a dot "." } str= ss.str(); reverse(str.begin(),str.end());//reversing the final string return str; } int main() { cout << thousandSeparator(123456789); }
123.456.789
Java Program for Thousand Separator Leetcode Solution
import java.util.*; import java.lang.*; class Solution { public static String thousandSeparator(int n) { String str=n+""; StringBuilder sb=new StringBuilder(); for(int i=str.length()-1;i>=0;){ sb.append(str.charAt(i));//inserting 1st digit i--; if(i==-1)break;//checking if we are out of left bound sb.append(str.charAt(i));//inserting 2nd digit i--; if(i==-1)break;//checking if we are out of left bound sb.append(str.charAt(i));//inserting 3rd digit i--; if(i==-1)break;//checking if we are out of left bound sb.append(".");//after 3 digits insertion, finally inserting a dot "." } return sb.reverse().toString();//reverse and return the final string } public static void main(String args[]) { System.out.println(thousandSeparator(123456789)); } }
123.456.789
Complexity Analysis for Thousand Separator Leetcode Solution
Time Complexity
O(len) : we are traversing the given number from right digit to left thus the time Complexity will be O(len) where len is the number of digits in the given number.
Space Complexity
O(len) : we have used a stringbuilder in java and stringstream in c++ thus using a extra space makes the space complexity O(len). | https://www.tutorialcup.com/leetcode-solutions/thousand-separator-leetcode-solution.htm | CC-MAIN-2021-49 | refinedweb | 619 | 65.93 |
Opened 6 years ago
Closed 19 months ago
#2252 closed defect (fixed)
Japanese wiki page name doesn't autowikify
Description
Japanese wiki page (page name is written in Japanese, not contents) doesn't wikify automatically.
I think it's concerned with utf-8 multibyte string.
In _update method, utf-8 string is escaped.
Is it correct behavior ?
Attachments (2)
Change History (28)
comment:1 Changed 6 years ago by athomas
comment:2 follow-up: ↓ 13 Changed 6 years ago by kondo@…
I use trac version 0.10.4.
I inserted "print(self.pages)" in autowikify.py.
def _all_pages(self): self.pages = set(WikiSystem(self.env).get_pages()) print(self.pages)
Output:
set([u'WikiNewPage', u'\u3042\u3042\u3042\u3042', ...snip...])
For example, page u'\u3042\u3042\u3042\u3042' does't autowikify.
Page name is below same as u'\u3042\u3042\u3042\u3042'.(Can you see?)
ああああ
comment:3 Changed 6 years ago by athomas
Yes, thanks! I'll try this out tonight.
comment:4 Changed 6 years ago by kondo@…
I fixed this problem in my local environment.
- trac version 0.11.1
Solution consists of two parts.
1.Add locale flag in trac wiki system
- See and try locale_add.patch.
- For trac 0.11 or later.
2.Remove blank "\b" from patterns in autowikify plugin.
- See remove_blank.patch
- Japanese words don't separate with blank.
- But I think this function should be able to toggle by option.
Changed 6 years ago by kondo@…
comment:5 Changed 5 years ago by cboos
I closed #T7552 as wontfix, since I don't think the problem comes from Trac.
The actual problem is also not related to the way re.escape deals with unicode objects as I originally thought:
>>> import re >>> pages = [u"ああああ", 'WikiStart'] >>> pattern = r'\b(?P<autowiki>' + '|'.join([re.escape(page) for page in pages]) + r')\b' >>> pattern u'\\b(?P<autowiki>\\\u3042\\\u3042\\\u3042\\\u3042|WikiStart)\\b' >>> re.search(pattern, u' \u3042\u3042\u3042\u3042 ', re.UNICODE).span() (1, 5) >>> re.search(pattern, u' Foo\u3042\u3042\u3042\u3042Bar ', re.UNICODE) is None True
So the original code should theoretically work.
Ah, I've just seen this: "Japanese words don't separate with blank."
Well, \b is not supposed to correspond only to blanks, but to "... whitespace or a non-alphanumeric, non-underscore character.". Nevertheless this reminded me that Japanese sentences look like a stream of characters with no obvious separator between words (at least to the untrained eye ;-) ).
So it looks like the intended behavior here is actually to extract a specific sequence of alphanumeric characters part of a larger sequence of characters, in the same way as one would extract 'WikiStart' from 'TheWikiStartPage' in English. Then I agree that the only way would be to optionally remove the \b markers.
Wouldn't that be enough? I still don't see the motivation for #T7552.
comment:6 Changed 5 years ago by redboltz
Unicode regex operates correctly.
The reason of using re.LOCALE is below.
In the _prepare_rules function, WikiParser makes regex based on the pattern.
An important point is the order of 'syntax'.
Plugin's syntax is ordered after internal syntax.
Syntax of the plug-in is arranged behind internal syntax.
Example.
(?:((?<)+(?:@)))
Japanese wiki page name matches to internal syntax(i0) instead of autowikify syntax(i8).
If the re.LOCALE flag is set, it matches to autowikify syntax(i8) according to the expectation.
Check the below code.
# -*- coding: utf-8 -*- import re import locale locale.setlocale(locale.LC_ALL, 'Japan') def replace(fullmatch): """Replace one match with its corresponding expansion""" replacement = handle_match(fullmatch) if replacement: return _markup_to_unicode(replacement) def handle_match(fullmatch): for itype, match in fullmatch.groupdict().items(): # if match and not itype in self.wikiparser.helper_patterns: if match: # Check for preceding escape character '!' print "match:" + itype + "," + match str = ur"(?:((?<>>IMAGE)))" rules = re.compile(unicode(str), re.UNICODE|re.LOCALE) print "re.UNICODE|re.LOCALE" line = u"あいうえお" result = re.sub(rules, replace, unicode(line)) line = u"PageNameA" result = re.sub(rules, replace, unicode(line)) line = u"ああ" result = re.sub(rules, replace, unicode(line)) rules = re.compile(unicode(str), re.UNICODE) print "re.UNICODE" line = u"あいうえお" result = re.sub(rules, replace, unicode(line)) line = u"PageNameA" result = re.sub(rules, replace, unicode(line)) line = u"ああ" result = re.sub(rules, replace, unicode(line)) str = ur"(?:(?P<bolditalic>!?''''')|(?P<bold>!?''')|(?P<italic>!?'')|(?P<underline>!?__)|(?P<strike>!?~~)|(?P<subscript>!?,,)|(?P<superscript>!?\^)|(?P<inlinecode>!?\{\{\{(?P<inline>.*?)\}\}\})|(?P<inlinecode2>!?`(?P<inline2>.*?)`)|(?P<i8>(?P<autowiki>PageNameA|あいうえお|ああ))|(?P<i0>!?(?<!/)\b\w(?<)+(?:@\d+)?(?:#[\w:](?<!\d)(?:[\w:.-]*[\w-])?)?(?=:(?:\Z|\s)|[^:a-zA-Z]|\s|\Z))|(?P<i1>!?\[\w(?<>>IMAGE+\}))" rules = re.compile(unicode(str), re.UNICODE) print "re.UNICODE and i8 before i0" line = u"あいうえお" result = re.sub(rules, replace, unicode(line)) line = u"PageNameA" result = re.sub(rules, replace, unicode(line)) line = u"ああ" result = re.sub(rules, replace, unicode(line))
Result.
re.UNICODE|re.LOCALE re.UNICODE match:i0,あいうえお <= unexpected match:i8,PageNameA match:autowiki,PageNameA match:i8,ああ match:autowiki,ああ re.UNICODE and i8 before i0
Japanese string "ああ" matches both re.UNICODE and re.UNICODE|re.LOCALE.
But string "あいうえお" matches only re.UNICODE|re.LOCALE.
It depends on string.
Probably, this behavior is concerned with the below. But I'm not sure.
Make \w, \W, \b, \B, \d, \D, \s and \S dependent on the Unicode character properties database. New in version 2.0.
There is an approach of arranging i8 in front of i0 if re.LOCALE is not set.
However, I am not predictable of the side effect.
Any ideas?
comment:7 Changed 5 years ago by cboos
So if I understand you correctly, when using the re.UNICODE flag only, "あいうえお" is matched as a regular wiki page name and not as an autowiki name. But why should that be an issue, as in both cases you'd get a link to that wiki page?
comment:8 follow-up: ↓ 9 Changed 5 years ago by redboltz
I think trac internal wiki-link doesn't work for page "あいうえお".
And I checked it.
Autowikify plugin's page_formatter is below.
def _page_formatter(self, f, n, match): page = match.group('autowiki') return Markup('<a href="%s" class="wiki">%s</a>' % (self.env.href.wiki(page), escape(page)))
It uses 'autowiki' tag.
The trac internal wiki link system might function only when it occasions about CamelCase and it describes explicitly like below.
[wiki:pagename]
Should I add any changes to something plugin?
comment:9 in reply to: ↑ 8 Changed 5 years ago by cboos
I think trac internal wiki-link doesn't work for page "あいうえお".
I'm afraid I'm not able to follow you... In comment:6, you justify the need for re.LOCALE by saying that without that flag, "あいうえお" gets matched by the internal wiki name regexp i0 (that's what:
re.UNICODE match:i0,あいうえお <= unexpected
shows).
Now you say that the internal wiki name regexp doesn't work for that page, which I can understand if (and only if) that name is part of some longer sentence, like in "あああああいうえおああああああ" (maybe an actual real example would help here). But in that situation, the autowikify regexp should match, provided the \b markers are dropped as discussed in comment:4 and comment:5.
comment:10 Changed 5 years ago by redboltz
There is a possibility that I do not understand enough either.
I think there are 2 topics.
It seems that there is a difference in recognition for the first topic.
- Why is it insufficient to match it to 'i0'?
- The function 'handle_match' is called.
def handle_match(self, fullmatch): for itype, match in fullmatch.groupdict().items(): if match and not itype in self.wikiparser.helper_patterns: # Check for preceding escape character '!' if match[0] == '!': return escape(match[1:]) if itype in self.wikiparser.external_handlers: => external_handler = self.wikiparser.external_handlers[itype] return external_handler(self, match, fullmatch) else: internal_handler = getattr(self, '_%s_formatter' % itype) return internal_handler(match, fullmatch)
- 'i0' external_handler is the function 'wikipagename_link'.
# Regular WikiPageNames def wikipagename_link(formatter, match, fullmatch): if not _check_unicode_camelcase(match): => return match return self._format_link(formatter, 'wiki', match, self.format_page_name(match), self.ignore_missing_pages)
- In the function 'wikipagename_link', Japanese string "ああああ" is judged not camelcase.
- After all, it is not wiki link, and a plain string "ああああ" is returned.
- What is the behavior expected when Japanese wiki-page-name is part of some longer sentence ?
- In Japanese, it is necessary to match it.
- In addition, wiki pagename in regex pattern should be the order of length.
- The patch is being made now.
Changed 5 years ago by redboltz
comment:11 Changed 5 years ago by redboltz
I said..
In addition, wiki pagename in regex pattern should be the order of length.
The patch is being made now.
I made the patch.(namesort.diff)
This operates correctly though there might be a possibility of a further improvement in the usage of the collection class of python.
comment:12 Changed 20 months ago by rjollos
- Cc rjollos added
comment:13 in reply to: ↑ 2 ; follow-up: ↓ 14 Changed 20 months ago by rjollos
- Cc jun66j5 added
Replying to kondo@t.email.ne.jp:
For example, page u'\u3042\u3042\u3042\u3042' does't autowikify.
I've tested AutoWikifyPlugin at r11819 with Trac 0.11, and a wiki page named ああああ is NOT autowikified (this is a clean Trac install with Genshi 0.6.0). On a clean 0.12 Trac install with Genshi 0.6.0 but no Babel, the wiki page named ああああ is autowikified. The same behavior is seen for other wiki page names that contain unicode characters, such as ÄÄÄÄ.
Page name is below same as u'\u3042\u3042\u3042\u3042'.(Can you see?)
ああああ
I don't see attachment:namesort.diff as the solution. The problem with removing the word boundaries from the regex is that on a Trac install with a wiki page named aaaa, aaaaa will be rendered as
So, two issues remain:
- Why does this work with Trac 0.12 but not 0.11? I'm really not too concerned about this, and would just suggest anyone experiencing the problem to upgrade.
- comment:4 says Japanese words don't separate with blank. I'm not sure how to deal with that issue because I don't think we want to remove the word boundaries from the regex. We could add an option for that, but I think someone that understands the language and Python locale issues should deal with that. I'd likely just make a mess of the situation.
So I'll leave this ticket open for now, but anyone experiencing issues should first upgrade to r11819 or later.
comment:14 in reply to: ↑ 13 Changed 20 months ago by redboltz
comment:15 follow-up: ↓ 16 Changed 20 months ago by rjollos
I'm pleasantly surprised to get a reply on such an old ticket :)
What version of Trac are you running? Are you able to test out the latest version of AutoWikifyPlugin?
comment:16 in reply to: ↑ 15 ; follow-up: ↓ 17 Changed 20 months ago by redboltz
I'm pleasantly surprised to get a reply on such an old ticket :)
What version of Trac are you running? Are you able to test out the latest version of AutoWikifyPlugin?
I'm using the TracLightning.
It is Japanese translation version that based on Trac 0.12.2. It is a kind of all-in-one package for windows. It's also includes the autowikify plugin and my patch is included in this package. I know it just now.
For testing, I replaced TracLightning version of autowikify with trac-hacks trunk version.
It works correctly in English wiki page, but doesn't link automatically to Japanese wiki page.
comment:17 in reply to: ↑ 16 ; follow-up: ↓ 18 Changed 20 months ago by rjollos?
comment:18 in reply to: ↑ 17 ; follow-up: ↓ 19 Changed 20 months ago by redboltz?
Ah, I understood what you mean now. I tested it just now. The space-delimited Japanese wiki page name is autowikified correctly.
comment:19 in reply to: ↑ 18 Changed 20 months ago by rjollos
Ah, I understood what you mean now. I tested it just now. The space-delimited Japanese wiki page name is autowikified correctly.
Okay, thanks a lot for testing. I'll make sure we have a solution within a week. If nothing else, I'll just add an option for specifying whether the word boundaries are whitespace-separated. Better, we might be able to have the locale determine this implicitly. Best, Japanese Trac developer jun66j5 will chime in and tell us what the best solution is ;)
comment:20 Changed 20 months ago by rjollos
- Owner changed from athomas to rjollos
- Status changed from new to assigned
comment:21 Changed 20 months ago by jun66j5
I worked in.
If the leading or trailing characters of a page name are CJK characters, it generates the regexp without \b.
For details, please see unit tests.
I don't think it's the best solution, however, I think it works well in the most cases.
comment:22 Changed 19 months ago by rjollos
comment:23 Changed 19 months ago by rjollos
Jun, thanks for the patch. I'm still trying to understand it completely. I gave you commit access in case you want to push the changes yourself, otherwise I'll get to it sometime this weekend.
comment:24 follow-up: ↓ 25 Changed 19 months ago by jun66j5
Thanks, Ryan!
I would like to push by myself. Could you please grant the right?
comment:25 in reply to: ↑ 24 Changed 19 months ago by rjollos
comment:26 Changed 19 months ago by jun66j5
- Resolution set to fixed
- Status changed from assigned to closed
The re.escape() is necessary to ensure page names with characters that are regex operators don't break the regular expression.
Are you running the latest version of Trac? Can you paste a page name that doesn't work? | http://trac-hacks.org/ticket/2252 | CC-MAIN-2014-10 | refinedweb | 2,324 | 60.72 |
- NAME
- VERSION
- SYNOPSIS
- DESCRIPTION
- METHODS
- ADDITIONAL EXAMPLES
- BUGS AND CAVEATS
- SEE ALSO
- AUTHORS
- LICENSE
NAME
RMI::Client - connection to an RMI::Server
VERSION
This document describes RMI::Client v0.10.
SYNOPSIS
# simple $c = RMI::Client::ForkedPipes->new(); # typical $c = RMI::Client::Tcp->new(host => 'server1', port => 1234); # roll-your-own... $c = RMI::Client->new(reader => $fh1, writer => $fh2); # generic $c->call_use('IO::File'); $c->call_use('Sys::Hostname'); $remote_obj = $c->call_class_method('IO::File','new','/tmp/myfile'); print $remote_obj->getline; print <$remote_obj>; $host = $c->call_function('Sys::Hostname::hostname') $host eq 'server1'; #! $remote_hashref = $c->call_eval('$main::h = { k1 => 111, k2 => 222, k3 => 333}'); $remote_hashref->{k4} = 444; print sort keys %$remote_hashref; print $c->call_eval('sort keys %$main::h'); # includes changes! $c->use_remote('Sys::Hostname'); # this whole package is on the other side $host = Sys::Hostname::hostname(); # possibly not this hostname... our $c; BEGIN { $c = RMI::Client::Tcp->new(port => 1234); $c->use_lib_remote; } use Some::Class; # remote!
DESCRIPTION
This is the base class for a standard RMI connection to an RMI::Server.
In most cases, you will create a client of some subclass, typically RMI::Client::Tcp for a network socket, or RMI::Client::ForkedPipes for a private out-of-process object server.
METHODS
Calls "use lib '$path'" on the remote side.
$c->call_use_lib('/some/path/on/the/server');
Uses the Perl package specified on the remote side, making it available for later calls to call_class_method() and call_function().
$c->call_use('Some::Package');
call_class_method($class, $method, @params)
Does $class->$method(@params) on the remote side.
Calling remote constructors is the primary way to make a remote object.
$remote_obj = $client->call_class_method('Some::Class','new',@params); $possibly_another_remote_obj = $remote_obj->some_method(@p);
call_function($fname, @params)
A plain function call made by name to the remote side. The function name must be fully qualified.
$c->call_use('Sys::Hostname'); my $server_hostname = $c->call_function('Sys::Hostname::hostname');
call_sub($subname, @params)
An alias for call_function();
call_eval($src,@args)
Calls eval $src on the remote side.
Any additional arguments are set to @_ before eval on the remote side, after proxying.
my $a = $c->call_eval('@main::x = (11,22,33); return \@main::x;'); # pass an arrayref back push @$a, 44, 55; # changed on the server scalar(@$a) == $c->call_eval('scalar(@main::x)'); # ...true!
use_remote($class)
Creases the effect of "use $class", but all calls of any kind for that namespace are proxied through the client. This is the most transparent way to get remote objects, since you can just call normal constructors and class methods as though the module were local. It does means that ALL objects of the given class must come from through this client.
# NOTE: you probably shouldn't do this with IO::File unless you # _really_ want all of its files to open on the server, # while open() opens on the client... $c->use_remote('IO::File'); # never touches IO/File.pm on the client $fh = IO::File->new('myfile'); # actually a remote call print <$fh>; # printing rows from a remote file require IO::File; # does nothing, since we've already "used" IO::File
The @ISA array is also bound to the remote @ISA, but all other variables must be explicitly bound on the client to be accessible. This may be changed in a future release.
Exporting does work. To turn it off, use empty braces as you would empty parens.
$c->use_remote('Sys::Hostname',[]);
To get this effect (and prevent export of the hostame() function).
use Sys::Hostname ();
use_lib_remote($path)
Installs a special handler into the local @INC which causes it to check the remote side for a class. If available, it will do use_remote() on that class.
use A; use B; BEGIN { $c->use_remote_lib; }; # do everything remotely from now on if possible... use C; #remote! use D; #remote! use E; #local, b/c not found on the remote side
bind($varname)
Create a local transparent proxy for a package variable on the remote side.
$c->bind('$Some::Package::somevar') $Some::Package::somevar = 123; # changed remotely $c->bind('@main::foo'); push @main::foo, 11, 22 33; #changed remotely
ADDITIONAL EXAMPLES
create and use a remote hashref
This makes a hashref on the server, and makes a proxy on the client:
my $remote_hashref = $c->call_eval('{}');
This seems to put a key in the hash, but actually sends a message to the server to modify the hash.
$remote_hashref->{key1} = 100;
Lookups also result in a request to the server:
print $remote_hashref->{key1};
When we do this, the hashref on the server is destroyed, as since the ref-count on both sides is now zero:
$remote_hashref = undef;
put remote objects from one server in a remote hash on another
$c1 = RMI::Client::Tcp->new(host => 'host1', port => 1234); $c2 = RMI::Client::Tcp->new(host => 'host2', port => 1234); $c3 = RMI::Client::Tcp->new(host => 'host3', port => 1234);
$o1 = $c1->call_class_method('IO::File','new','/etc/passwd'); $o2 = $c2->call_class_method('IO::File','new','/etc/passwd');
$h = $c3->call_eval('{ handle1 => $_[0] }', $o1);
$h->{handle2} = $o2;
making a remote CODE ref, and using it with local and remote objects
my $local_fh = IO::File->new('/etc/passwd'); my $remote_fh = $c->call_class_method('IO::File','new','/etc/passwd'); my $remote_coderef = $c->call_eval(' sub { my $f1 = shift; my $f2 = shift; my @lines = (<$f1>, <$f2>); return scalar(@lines) } '); my $total_line_count = $remote_coderef->($local_fh, $remote_fh);
BUGS AND CAVEATS
See general bugs in RMI for general system limitations
SEE ALSO
RMI, RMI::Client::Tcp, RMI::Client::ForkedPipes, RMI::Server. | http://web-stage.metacpan.org/pod/RMI::Client | CC-MAIN-2020-05 | refinedweb | 893 | 50.77 |
mask password and store as string
This work for me .
How would I type y = x + 3/4 - 2 in c++ lang.?#include <iostream>
using namespace std;
[code]int main()
{
int x , y;
cout<<"The value of \"x\" is...
User to exit the programelse if (choice==5)
{
return 0;
} this code exit the program when user press 5 .
Are you lookin...
User to exit the programint main()
{
int choice;
cout << "1.Hello world \n"<<"...\n"<<"5. Exit the program\n";
cin>...
Nested While loop?okay , my problem was in variable declaration , i declarate the variable that i used on inner loop ,... | http://www.cplusplus.com/user/cppbeginer123/ | CC-MAIN-2014-15 | refinedweb | 101 | 87.62 |
First of all I want to thank Sean Ewington for his great initiative to write Beginner's Walk for Web Development article. I have decided to write some articles on state management There are a few article on Code project on State Management, basically on Session, Caching, Cookies, etc. Though all are very good article, still I have planned for write some article on state management. and I believe that should definitely helps to all the Beginners. And I have organized the content in a way that it would be helpful to not only beginners also to advance user also.
In this article, I will cover the fundamentals of State Management and Details of View State.
Web is Stateless. It means a new instance of the web page class is re-created each time the page is posted to the server. As we all know HTTP is a stateless protocol, its can't holds the client information on page. As for example , if we enter a text and client on submit button, text does not appear after post back , only because of page is recreated on its round trip.
Stateless
HTTP
As given in above pages, page is recreated before its comes to clients and happened for each and every request. So it is a big issue to maintain the state of the page and information for a web application. That is the reason to start concept of State Management. To overcome this problem ASP.NET 2.0 Provides some features like View State, Cookies, Session, Application objects etc. to manage the state of page.
State Management
View State, Cookies, Session, Application objects
There are some few selection criteria to selected proper way to maintain the state, as there are many way to do that. Those criteria are:
So, when ever you start to think about state management, you should think about above criteria. based on that you can choose the best approaches for manages state for your web application.
There are two different types of state management:
View State
Hidden Field
Cookies
Control State
Session
Application Object
Caching
Database
Client Side state management does not use any server resource , it store information using client side option. Server Side state management use server side resource for store data. Selection of client side and server side state management should be based on your requirements and the selection criteria that are already given.
View State is one of the most important and useful client side state management mechanism. It can store the page value at the time of post back (Sending and Receiving information from Server) of your page. ASP.NET pages provide the ViewState property as a built-in structure for automatically storing values between multiple requests for the same page.
View State
post back (Sending and Receiving information from Server)
ViewState
Example:
If you want to add one variable in View State,
ViewState["Var"]=Count;
For Retrieving information from View State
string Test=ViewState["TestVal"];
Sometimes you may need to typecast ViewState Value to retreive. As I give an Example to strore and retreive object in view state in the last of this article.
This are the main advantage of using View State:
This are the main disadvantages of using View State:
I already describe the criteria of selecting State management. A few point you should remember when you select view state for maintain your page state.
You won't need view state for a control for following cases,
View State stored the value of page controls as a string which is hashed and encoded in some hashing and encoding technology. It only contain information about page and its controls. Its does not have any interaction with server. It stays along with the page in the Client Browser. View State use Hidden field to store its information in a encoding format.
Hidden
Suppose you have written a simple code , to store a value of control:
ViewState["Value"] = MyControl.Text;
Now, Run you application, In Browser, RighClick > View Source , You will get the following section of code
RighClick
View
Source
Fig : View state stored in hidden field
Now , look at the value. looks likes a encrypted string, This is Base64 Encoded string, this is not a encoded string. So it can easily be decoded. Base64 makes a string suitable for HTTP transfer plus it makes it a little hard to read . Read More about Base64 Encoding . Any body can decode that string and read the original value. so be careful about that. There is a security lack of view state.
security lack
We can store an object easily as we can store string or integer type variable. But what we need ? we need to convert it into stream of byte. because as I already said , view state store information in hidden filed in the page. So we need to use Serialization. If object which we are trying to store in view state ,are not serializable , then we will get a error message .
Serialization
Just take as example,
//Create a simple class and make it as Serializable
[Serializable]
public class student
{
public int Roll;
public string Name;
public void AddStudent(int intRoll,int strName)
{
this.Roll=intRoll;
this.Name=strName;
}
}
Now we will try to store object of "Student" Class in a view state.
Student
//Store Student Class in View State
student _objStudent = new student();
_objStudent.AddStudent(2, "Abhijit");
ViewState["StudentObject"] = _objStudent;
//Retrieve Student information view state
student _objStudent;
_objStudent = (student)ViewState["StudentObject"];
If you want to trace your view state information, by just enable "Trace" option of Page Directive
Trace
Now Run your web application, You can view the details of View State Size along with control ID in Control Tree Section. Don't worry about "Render Size Byte" , this only the size of rendered control.
Control Tree
Render Size Byte
You can enable and disable View state for a single control as well as at page level also. To turnoff view state for a single control , set EnableViewState Property of that control to false. e.g.:
EnableViewState
TextBox1.EnableViewState =false;
To turnoff the view state of entire page, we need to set EnableViewState to false of Page Directive as shown bellow.
Even you disable view state for the entire page , you will see the hidden view state tag with a small amount of information, ASP.NET always store the controls hierarchy for the page at minimum , even if view state is disabled.
For enabling the same, you have to use the same property just set them as True
as for example, for a single control we can enabled view state in following way,
TextBox1.EnableViewState =true;
and for a page level,
As I already discuss View state information is stored in a hidden filed in a form of Base64 Encoding String, and it looks like:
Base64 Encoding
Many of ASP.NET Programmers assume that this is an Encrypted format, but I am saying it again, that this is not a encrypted string. It can be break easily. To make your view state secure, There are two option for that,
Encrypted format
First, you can make sure that the view state information is tamper-proof by using "hash code". You can do this by adding "EnableViewStateMAC=true" with your page directive. MAC Stands for "Message Authentication Code"
"hash code"
EnableViewStateMAC=true
"Message Authentication Code"
A hash code , is a cryptographically strong checksum, which is calculated by ASP.NET and its added with the view state content and stored in hidden filed. At the time of next post back, the checksum data again verified , if there are some mismatch, Post back will be rejected. we can set this property to web.config file also.
hash code
checksum
Second option is to set ViewStateEncryptionMode="Always" with your page directives, which will encrypt the view state data. You can add this in following way
ViewStateEncryptionMode="Always"
It ViewStateEncryptionMode has three different options to set:
ViewStateEncryptionMode
Always, mean encrypt the view state always, Never means, Never encrypt the view state data and Auto Says , encrypt if any control request specially for encryption. For auto , control must call Page.RegisterRequiresViewStateEncryption() method for request encryption.
Always
Never
Auto
Page.RegisterRequiresViewStateEncryption()
we can set the Setting for "EnableViewStateMAC" and ViewStateEncryptionMode" in web.config also.
EnableViewStateMAC"
ViewStateEncryptionMode"
Note : Try to avoid View State Encryption if not necessary , because it cause the performance issue.
Note :
That's all for view state. Hope you have enjoyed this article, please don't forget to give me your valuable suggestions. If anything need to update or changed please post your comments and please give me suggestion.
Written on Saturday, 29th November, 2008
Small Correction on Monday December. | https://www.codeproject.com/Articles/31344/Beginner-s-Guide-To-View-State?msg=4353011 | CC-MAIN-2017-47 | refinedweb | 1,444 | 62.38 |
Module to simplify usage of WeedFS in python.
Project description
Class to simplify communication with Weed-FS
Installation
From PyPI:
pip install pyweed
Tests
Install dependencies:
pip install -r test_requirements.txt
Run tests:
python setup.py tests
Or using nose:
nosetests
Note
Functional tests assumes that there is WeedFS master running on localhost:9333 (defaults). If it’s not then there will be errors in tests.
Usage
Upload file to weedFS
from pyweed import WeedFS # File upload w = WeedFS("localhost", 9333) # weed-fs master address and port fid = w.upload_file("n.txt") # path to file # Get file url file_url = w.get_file_url(fid) # Delete file res = w.delete_file(fid) # res is boolean (True if file was deleted)
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/pyweed/0.3.5/ | CC-MAIN-2019-09 | refinedweb | 143 | 58.48 |
IPython works with the Matplotlib plotting library, which integrates Matplotlib with IPython's display system and event loop handling.
To make plots using Matplotlib, you must first enable IPython's matplotlib mode.
To do this, run the
%matplotlib magic command to enable plotting in the current Notebook.
This magic takes an optional argument that specifies which Matplotlib backend should be used. Most of the time, in the Notebook, you will want to use the
inline backend, which will embed plots inside the Notebook:
%matplotlib inline
You can also use Matplotlib GUI backends in the Notebook, such as the Qt backend (
%matplotlib qt). This will use Matplotlib's interactive Qt UI in a floating window to the side of your browser. Of course, this only works if your browser is running on the same system as the Notebook Server. You can always call the
display function to paste figures into the Notebook document.
With matplotlib enabled, plotting should just work.
import matplotlib.pyplot as plt import numpy as np
x = np.linspace(0, 3*np.pi, 500) plt.plot(x, np.sin(x**2)) plt.title('A simple chirp');
These images can be resized by dragging the handle in the lower right corner. Double clicking will return them to their original size.
One thing to be aware of is that by default, the
Figure object is cleared at the end of each cell, so you will need to issue all plotting commands for a single figure in a single cell.
IPython's
%load magic can be used to load any Matplotlib demo by its URL:
# %load """ Plot demonstrating the integral as the area under a curve. Although this is a simple example, it demonstrates some important tweaks: * A simple line plot with custom color and line width. * A shaded region created using a Polygon patch. * A text label with mathtext rendering. * figtext calls to label the x- and y-axes. * Use of axis spines to hide the top and right spines. * Custom tick placement and labels. """()
Matplotlib 1.4 introduces an interactive backend for use in the notebook,
called 'nbagg'. You can enable this with
%matplotlib notebook.
With this backend, you will get interactive panning and zooming of matplotlib figures in your browser.
%matplotlib notebook
plt.figure() x = np.linspace(0, 5 * np.pi, 1000) for n in range(1, 4): plt.plot(np.sin(n * x)) plt.show() | https://nbviewer.jupyter.org/github/ipython/ipython/blob/rel-4.1.1/examples/IPython%20Kernel/Plotting%20in%20the%20Notebook.ipynb | CC-MAIN-2018-13 | refinedweb | 398 | 75.4 |
In this article we will aim to get a basic java application up and running that is capable of interacting with MongoDB. By itself that is not really a tall task and perhaps you could get that in under 10 minutes. Click here or click here or click here, for some excellent material. However, I wanted to push it a bit further.
I want to add ORM support. I have chosen Morphia for this article. I also want to add DAO pattern, unit testing, and logging. In short, I want to it feel, “almost like” the kind of code that most of us would have written for enterprise applications using, let’s say Java, Hibernate and Oracle. And, we will try to do all this in under 30 minutes.
My intention is to give a reassurance to Java + RDBMS developers that Java + NoSQL is not very alien. It is similar code and easy to try out. It is perhaps pertinent to add at this point that I have no affinity to NoSQL and no issues with RDBMS. I beieve they both have their own uses ( click here for some excellent material). As a technologist, I just like knowing my tools better so that I can do justice to my profession. This article is solely aimed at helping likeminded people to dip their toes in NoSQL.
Ok, enought talk. Let’s get started. You will need a few softwares / tools before you follow this article. Download and install MongoDB server, if you have not already done so. I am assuming you have Java, some Java IDE and a build and release tool. I am using jdk 7, Eclipse (STS) and Maven 3 for this article.
I start by creating a vanilla standard java application using Maven. I like using a batch file for this.
File: codeRepo=dbLayer002 pause
Import it in Eclipse. Use Maven to compile and run just to be sure.
mvn -e clean install.
This should compile the code and run the default tests as well. Once you have crossed this hurdle, now let’s get down to some coding. Let’s create an Entity object to start with. I think a Person class with fname would serve our purpose. I acknowledge that it is trivial but it does the job for a tutorial.
File: /dbLayer002/src/main/java/org/academy/entity/Person.java
package org.academy.entity; public class Person { private String fname; [...] }
I have not mentioned the getters and setters for brevity.
Now let us get the MongoDB java driver and attach it to the application. I like have Maven do this bit for me. You could obviously do this bit manually as well. Your choice. I am just lazy.
File: /dbLayer002/pom.xml
[...] <!-- MongDB java driver to hook up to MongoDB server --> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>2.7.3</version> </dependency> [...]
This will allow us to write a util class for connecting to MongoDB server instance. I am assuming you have a server up and running in your machine with default settings.
File: /dbLayer002/src/main/java/org/academy/util/MongoUtil.java
public class MongoUtil { private final static Logger logger = LoggerFactory .getLogger(MongoUtil.class); private static final int port = 27017; private static final String host = "localhost"; private static Mongo mongo = null; public static Mongo getMongo() { if (mongo == null) { try { mongo = new Mongo(host, port); logger.debug("New Mongo created with [" + host + "] and [" + port + "]"); } catch (UnknownHostException | MongoException e) { logger.error(e.getMessage()); } } return mongo; } }
We will need logger setup in our application for this class to compile. Click here for my article around logging. All we need to do is to hook up Maven with the correct dependencies.
File: /dbLayer002/pom.xml
[...] <slf4j.version>1.6.1</slf4j.version> [...] <!-->
And also, we will need to specify, exactly what to log.
File: /dbLayer002/src/java
At this point, you already have an Entity class and a utility class to hook up to the database. Ideally I would go about writing a DAO and then somehow use the ORM to join up the DAO with the database. However, Morphia has some excellent DAO support. Also it has some annotations to tie up the Entity with database elements. So, although I would have liked the Entity and DAO to be totally agnostic of the ORM and database, it is not the case here. I know on the face of it, it sounds like Morphia or MongoDB is forcing me to deviate from good code structure, let me hasten to add, that it is not any worse than other ORMs e.g. Hibernate with Annotations would have also forced me to make the same kind of compromise.
So, let’s bring in Morphia in the picture. Enters the stage our ever helpful tool, Maven. A bit of an avoidable hitch here. When I was writing this document I could not get the version of Morphia that I wanted in the central Maven repository. So, I had to configure Maven to use the Morphia repository as well. Hopefully this is just a temporary situation.
File: /dbLayer002/pom.xml
[...] <!-- Required for Morphia --> <repositories> <repository> <id>Morphia repository</id> <url></url> </repository> </repositories> [...] <!-- Morphia - ORM for MongoDB --> <dependency> <groupId>com.google.code.morphia</groupId> <artifactId>morphia</artifactId> <version>0.98</version> </dependency>
As I mentioned above, Morphia allows us to annotate the Entity class (much like Hibernate annotations). So, here is how the updated Entity class looks like.
File: /dbLayer002/src/main/java/org/academy/entity/Person.java
[...] @Entity public class Person { @Id private ObjectId id; [...]
And now we can also add a DAO layer and lean on the BasicDAO that Morphia provides.
File: /dbLayer002/src/main/java/org/academy/dao/PersonDAO.java
public class PersonDAO extends BasicDAO<Person, ObjectId> { public PersonDAO(Mongo mongo, Morphia morphia, String dbName) { super(mongo, morphia, dbName); } [...]
The beauty of the BasicDAO is that just by extending that, my own DAO class already has enough functionality to do the basic CRUD operations, although I have just added a constructor. Don’t believe it? Ok, lets write a test for that.
File: /dbLayer002/src/test/java/org/academy/dao/PersonDAOTest.java
public class PersonDAOTest { private final static Logger logger = LoggerFactory .getLogger(PersonDAOTest.class); private Mongo mongo; private Morphia morphia; private PersonDAO personDao; private final String dbname = "peopledb"; @Before public void initiate() { mongo = MongoUtil.getMongo(); morphia = new Morphia(); morphia.map(Person.class); personDao = new PersonDAO(mongo, morphia, dbname); } @Test public void test() { long counter = personDao.count(); logger.debug("The count is [" + counter + "]"); Person p = new Person(); p.setFname("Partha"); personDao.save(p); long newCounter = personDao.count(); logger.debug("The new count is [" + newCounter + "]"); assertTrue((counter + 1) == newCounter); [...]
As you might have already noticed. I have used JUnit 4. If you have been following this article as is till now you would have an earlier version of JUnit in your project. To ensure that you use JUnit 4, you just have to configure Maven to use that by adding the correct dependency in pom.xml.
File: /dbLayer002/pom.xml
<!-- Unit test. --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency>
You are good to go. If you run the tests they should pass. Of course you could / should get into your database and check that the data is indeed saved. I will refer you to the MongoDB documentation which I think are quite decent.
Last but not least, let me assure you that BasicDAO is not restrictive in any way. I am sure puritans would point out that if my DAO class needs to extend the BasicDAO that is a limitation on the source code structure anyway. Ideally should not have been required. And I agree with that. However, I also want show that for all practical purposes of DAO, you have sufficient flexibility. Let’s go on and add a custom find method to our DAO, that is specific to this Entity i.e. Person. Let’s say we want to be able to search on the basis of firstname and that we want to use regular expression for that. Here is how the code will look like.
File: /dbLayer002/src/main/java/org/academy/dao/PersonDAO.java
public class PersonDAO extends BasicDAO<Person, ObjectId> { [...] public Iterator<Person> findByFname(String fname){ Pattern regExp = Pattern.compile(fname + ".*", Pattern.CASE_INSENSITIVE); return ds.find(entityClazz).filter("fname", regExp).iterator(); } [...] }
Important to reemphasize here that, I have just added a custom search function to my DAO, by adding precisely three lines of code (four if you add the last parentheses). In my books, that is quite flexible. Being true to my unflinching love for automated testing, lets add a quick test to check this functionality before we wrap up.
File: /dbLayer002/src/test/java/org/academy/dao/PersonDAOTest.java
[...] Iterator<Person> iteratorPerson = personDao.findByFname("Pa"); int personCounter = 0 ; while(iteratorPerson.hasNext()){ personCounter ++; logger.debug("["+personCounter+"]" + iteratorPerson.next().getFname()); } [...]
Before you point out, yes, there are no assert() here, so this is not a real test. Let me assure you that my test class is indeed complete. It’s just that this snippet here does not have the assert function.
So, that’s it. You have used Java to connect to a NoSQL database, using an ORM, through a DAO layer (where you have used the ORM’s functionalities and done some addition as well). You have also done proper logging and unit testing. Not bad use of half an hour, eh? Happy coding.
Further reading
- A version of this article – slightly edited, is also available at this link at Javalobby.
Reference: MongoDB in 30 minutes from our JCG partner Partho at the Tech for Enterprise blog.
Good introduction! You have a very nice style of writing. I enjoy it.
Thanks mate. Do visit my blog at. I will love to hear some feedback.
Hi,
you can use “fongo” () for unitesting. | https://www.javacodegeeks.com/2012/07/mongodb-in-30-minutes.html | CC-MAIN-2017-09 | refinedweb | 1,648 | 58.99 |
Clodoaldo Pinto Neto wrote ..
> 2006/10/29, Graham Dumpleton <grahamd at dscpl.com.au>:
> > Clodoaldo Pinto Neto wrote ..
> > > 2006/10/29, Graham Dumpleton <grahamd at dscpl.com.au>:
> > >.
>
> It is exactly what MarshalCookie.parse() does:
But it is still an assumption because they aren't tagged as being of a
particular type. :-)
> def parse(Class, s, secret):
>
> dict = _parse_cookie(s, Class)
>
> for k in dict:
> c = dict[k]
> try:
> c.unmarshal(secret)
> except (CookieError, ValueError):
> # downgrade to Cookie
> dict[k] = Cookie.parse(Cookie.__str__(c))[k]
>
> return dict
>
> The problem that is happening is that one exception was not expected
> by the original code piece author. The exception is binascii.Error. It
> will happen whenever MarshalCookie.parse() tries to parse a Signed
> cookie. My proposed fix is just to import binascii and include the
> exception:
>
> try:
> c.unmarshal(secret)
> except (CookieError, ValueError, binascii.Error):
> # downgrade to Cookie
> dict[k] = Cookie.parse(Cookie.__str__(c))[k]
>
> This way MarshalCookie.get_cookies() will behave as per the documentation.
Yes and no. Yes one could do it, but after looking at it and thinking about
it overnight I would probably do it in a different place. Instead, one would
be better of first changing unmarshal() to:
def unmarshal(self, secret):
self.unsign(secret)
try:
data = base64.decodestring(self.value)
except binascii.Error:
raise CookieError, "Incorrectly Encoded Cookie: %s=%s" % (self.name, self.value)
self.value = marshal.loads(data)
and leave parse() as is.
The difference here is that you have split out the base64 decoding of
the value string from the actual unmarshalling of the data.
Next one has to contemplate whether one should for the marshal.loads()
call separately catch EOFError, ValueError or TypeError exceptions as
being indicative of badly formatted marshal data.
The reason for doing this would be that I could use a SignedCookie at
the same time where I decide to base64 encode the value myself. If I do
this and the SignedCookie uses the same secret, the data would get
past the signed check and the base64 decoding implemented by the
MarshalCookie but then fail on unmarshalling if the data wasn't actually
marshal data but some other format.
So, to be even more precise:
def unmarshal(self, secret):
self.unsign(secret)
try:
data = base64.decodestring(self.value)
except:
raise CookieError, "Value Not BASE64 Encoded: %s=%s" % (self.name, self.value)
try:
self.value = marshal.loads(data)
except (EOFError, ValueError, TypeError):
raise CookieError, "Cannot Unmarshal Cookie: %s=%s" % (self.name, self.value)
> > This is probably not a good way of doing
> > things. First off the application should only be decoding its own cookies
> > and not others which may have been sent to the site in general. Thus,
> allowing
> > one to say which cookies to decode is probably a better step.
>
> I'm not opposing the new names argument. I just don't know enough
> about mod_python to opine on it, although the names argument alone
> will not fix the issue: an *expected* error that should be handled by
> mod_python. Or better, the names argument will only fix the issue if
> it is passed *and* if none of the passed cookie names is a Signed
> cookie. A nice addition perhaps, but not a fix.
The other thing I believe also should be added is a new keyword
parameter called 'strict'. This would default to 0 to preserve existing
behaviour. So I could say:
cookies = Cookie.get_cookies(req, Cookie.MarshalCookie, names=['xxx'], strict=1)
If 'strict' is set to a truth value, then if a cookie fails to be decoded as
the intended type, it would not fallback to returning Cookie, but raise
again the original exception that cause the cookie not to be decoded.
The Session code would for example always use 'strict' to ensure that
SignedCookie doesn't fallback to 'Cookie', thus ensuring the extra
security of the 64 character vs 32 character string is used.
Graham | http://modpython.org/pipermail/mod_python/2006-October/022433.html | CC-MAIN-2018-39 | refinedweb | 648 | 58.79 |
I am trying to connect to a Postgres Database using sockets to enforce a particular TLS version from the client in order to verify that the Database does not accept connections from the client which uses an older version of TLS like tlsv1.1. The connection is failing on handshake with the following error :
python test2.py
Traceback (most recent call last): File "test2.py", line 12, in ssl_version=ssl.PROTOCOL_TLSv1_2) File "<>/python3.6/lib/python3.6/ssl.py", line 1232, in get_server_certificate with context.wrap_socket(sock) as sslsock: File "<>/python3.6/lib/python3.6/ssl.py", line 407, in wrap_socket _context=self, _session=session) File "<>/python3.6/lib/python3.6/ssl.py", line 817, in init self.do_handshake() File "<>/python3.6/lib/python3.6/ssl.py", line 1077, in do_handshake self._sslobj.do_handshake() File "<>/python3.6/lib/python3.6/ssl.py", line 689, in do_handshake self._sslobj.do_handshake() ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:852)
The following is a snippet of the code:
import socket import ssl hostname = <DB_Endpoint> context = ssl.create_default_context() with socket.create_connection((hostname, 8200)) as sock: with context.wrap_socket(sock, server_hostname=hostname) as ssock: print(ssock.version())
PS: I am just trying to figure out a way to test if the Postgres Server rejects a connection from a client which only has
| https://proxieslive.com/connecting-to-a-postgres-database-over-ssl-using-sockets-in-python/ | CC-MAIN-2020-40 | refinedweb | 220 | 54.18 |
You.
Cocoon is officially defined as an XML publishing engine, and while technically correct, the description does not do the product justice. The best way to understand Cocoon is to view it as a framework for generating, transforming, processing, and outputting data. Think of Cocoon as a machine that receives data from a wide variety of sources, applies various processing to it, and spits data out in the desired format. Figure 1 helps illustrate this view.
We could also define Cocoon as a data flow machine. That is, when you use Cocoon, you define the data paths or flows that produce the pages that make up your Web application. Even a simple hello-world.html page has a data flow defined to serve the page.
I could spend this entire article discussing Cocoon's architecture, but it boils down to a few basic principles:
- Cocoon handles all data internally as SAX (Simple API for XML) events; any non-XML input data converts to an XML representation.
- Components called generators—because they generate SAX events—handle data input.
- Components called serializers handle data output—they write the data out to the client (that is, browser, file, and so on).
- The developer combines generators, serializers, and other components to form processing flows called pipelines. All pipelines are defined in a file called the sitemap.
- URI (Uniform Resource Identifier) patterns identify pipelines, but URIs are completely decoupled from physical resources.:
- Using components called transformers: They do exactly what their name implies: they transform incoming data according to the rules they are given. The classic example is the
TraxTransformer, which you can see in action in the pipeline above.
- In the pipeline using various components that help choose the correct processing path based on various request/session/URI settings.
- In the pipeline based on stock or custom Java-processing units called actions.
- Using input files that mix Java and content—these are called Extensible Server Pages (XSPs).
This article covers this list's last two approaches: XSPs and actions. If you develop with Cocoon to any extent, you'll end up using them and probably liking them. Plus, you'll be happy to know that in both cases, you are essentially programming within a servlet context. More correctly, both components (in fact, all Cocoon components) have access to request, response, session, and context objects. Much of the logic you implement interacts with these objects in some way..
eXtensible Server Pages
XSPs are an innovation of the Cocoon project. You can compare them to JSPs (JavaServer Pages) because they mix logic and content and can import functionality via taglib-like files called logicsheets. XSPs represent a pipeline's start; that is, they actually convert on the fly into generators that then produce the data for the rest of the pipeline to use.
Let's start with a simple example, called
sample1.xsp:
<?xml version="1.0"?> <xsp:page <xsp:logic> Date now = new Date(); String msg = "Boo!"; </xsp:logic> <content> <title>Welcome to Cocoon</title> <paragraph> This is an XSP. You can see how we it contain both logic (inside the <xsp:logic> tags) and content. In the logic block above, we created a Date object whose value is <xsp:expr>now</xsp:expr>. Oh, we also had a special message for you: <xsp:expr>msg</xsp:expr> </paragraph> </content> </xsp:page>
First note that this document's root tag is
<xsp:page>. This tag defines the XSP's language (either Java or JavaScript) and lists the namespaces of all the logicsheets being used. (When you see logicsheet, think taglib—I'll discuss this concept more later.) Next comes a
<xsp:logic> block in which we set two Java variables. These blocks—you can have more than one—can appear anywhere you need them and can contain all sorts of Java code. Finally, we have our content, starting with the root user tag, which, in our case, is
<content>. Inside this content, however, we can access the variables we set at the beginning using the special tag
<xsp:expr>.
Remember, an XSP is actually a generator. Cocoon turns it into a Java source file, compiles it, and then executes it. (If you want to see an XSP's complete Java source file, look under your servlet container's work directory. If you use Tomcat 4.0.4, for example, this file will typically be under a directory like
$CATALINA_HOME/work/Standalone/localhost/cocoon/cocoon-files/org/apache/cocoon/www.) The XML data produced during execution then passes to the rest of the pipeline's components.
To see this XSP in action, let's create the following pipeline:
<map:pipeline <map:generate <map:serialize </map:pipeline>
Here, we use a special generator, the
ServerPagesGenerator, to process our simple XSP. Rather than doing anything with the data, we simply return it to the client in raw XML form. Note the use of the special
{1} variable reference: it refers to the substitution value indicated by the wildcard character at the start of the pipeline. In other words, if we point our browser to
sample1.xsp in our Web application, the value of
{1} will be
sample1, since
{1} is substituted for the wildcard character
*. This feature results in a more generic pipeline and will serve for the rest of this article's XSP examples.
With an XML-aware browser like Internet Explorer, we will see
sample1.xsp's output shown in Figure 2.
Remember that XSPs, like most Cocoon components, have access to request, response, session, and context objects. These objects are actually Cocoon encapsulations of
HttpServletRequest,
HttpServletResponse,
HttpSession, and
HttpServletContext and are called
Request,
Response,
Session, and
Context, respectively. The Cocoon versions provide access to most of the methods in the official versions.
XSPs prove especially useful for retrieving data from a database. When you think about it, database data makes great XML data, since it is naturally organized into rows and columns. However, JDBC (Java Database Connectivity) does not make for economical code. XSPs, on the other hand, can make your life much easier when retrieving data, thanks to the
ESQL logicsheet. Besides hiding the gory JDBC details, the
ESQL logicsheet allows you to encapsulate your rows and columns with custom tags. You can implement nested queries and run database update commands as well.
Suppose we want to store a list of Cocoon resources in a database table. First, we define the table and then use an XSP to retrieve the rows found when a user searches by keyword. Later, we'll build a form to add new rows.
The table definition and rows are shown below. I use MySQL, so please make the appropriate DDL (data description language) changes if you use a different database. In case you haven't, you must configure a connection pool in Cocoon for your database. See "Sidebar 1: Databases and Cocoon" for more information.
use test; create table Resources ( ResourceURL varchar(255) not null, ResourceName varchar(64) not null ); insert into Resources values ('', 'Cocoon Home Page'); insert into Resources values ('', 'Cocoon portal - first look'); insert into Resources values ('', 'Cocoon 2.0 Tips and Tricks'); insert into Resources values ('', 'Deploying Cocoon 2 in JBoss'); insert into Resources values ('', 'Integrating Apache, Tomcat 3.2.x and Cocoon 2.0 on Windows'); insert into Resources values ('', 'Integrating Tomcat 4.0.x and Cocoon 2.0 on Unix'); insert into Resources values ('', 'Integrating Tomcat 4.0.x and Cocoon 2.0 on Windows'); insert into Resources values ('', 'Creating a Navigation Menu'); insert into Resources values ('', 'Your Guide to Apache Cocoon'); insert into Resources values ('', 'Logicsheet Development');
With our table built and Cocoon properly configured, we can write a simple XSP: | https://www.javaworld.com/article/2074557/web-app-frameworks/transform-data-into-web-applications-with-cocoon.html | CC-MAIN-2018-47 | refinedweb | 1,278 | 55.74 |
Introducing the Amara XML Toolkit
January 19, 2005
As part of my roundup of Python data bindings, I introduced my own Anobind project. Over the column's history, I've also developed other code to meet some need emphasized in one of the previous articles. I recently collected all of these various little projects together into one open source package of XML processing add-ons, Amara XML Toolkit. Amara is meant to complement 4Suite in that 4Suite works towards fidelity to XML technical ideals, while Amara works towards fidelity to Python conventions, taking maximum advantage of Python's strengths. The main components of Amara XML Toolkit are the following:
- Bindery: data binding tool. The code that was formerly available standalone as "Anobind" but with extensive improvements and additions, including a move of the fundamental framework from DOM to SAX.
- Scimitar: an implementation of the ISO Schematron schema language for XML. It also used to be a standalone project, which I've announced here in the past. It converts Schematron files to standalone Python scripts.
- domtools: helper routines for working with Python DOMs, many of which first made their appearance in previous articles such as "Generating DOM Magic" and "Location, Location, Location."
- saxtools: helper frameworks and routines for easier use of Python's SAX implementation, many of which first made their appearance in previous articles such as " Decomposition, Process, Recomposition".
- Flextyper: implementation of Jeni Tennison's Data Type Library Language (DTLL) (on track to become part 5 of ISO Document Schema Definition Languages (DSDL). You can use Flextyper to generate Python modules containing data types classes that can be used with 4Suite's RELAX NG library, although it won't come into its full usefulness until the next release of 4Suite.
In this article I introduce parts of Amara, focusing on several little, common tasks
it's
supposed to help with. Some of these are tasks you will recognize from earlier articles
in
this column. Amara requires Python 2.3 or later and 4Suite 1.0a4 or later. I used
Python
2.3.4 to run all listings presented, working with Amara 0.9.2. With the prerequisites
in
place, installation is the usual matter of
python setup.py install.
Best of SAX and DOM
The very first sample task needs very little preamble. See listing 1, a form of the address label example I so often use. is code to print out all people and their street addresses.
Listing 2 (listing2.py): Amara Pushdom code to print out all people and their street addresses
from amara import domtools for docfrag in domtools.pushdom('/labels/label', source='labels.xml'): label = docfrag.firstChild name = label.xpath('string(name)') city = label.xpath('string(address/city)') print name, 'of', city
The code is extremely simple, but it does print what a quick glance might lead you to expect:
$ python listing2.py Thomas Eliot of Stamford Ezra Pound of Hailey Langston Hughes of Harlem
The trick is how it does this.
domtools.pushdom is a generator which yields a
DOM document fragment at a time, such that the entire document is broken down into
a series
of subtrees given by the pattern passed in:
/labels/label. The full document is
never in memory (in fact, the code never takes up much more memory than it takes to
maintain
a DOM node for a single
label element. If, as the comment in listing 1
suggests, there were 10,000 more label elements, the memory usage wouldn't be much
greater;
although, if your loop iterates faster than Python can reclaim each discarded node,
you
might want to add an explicit
gc.collect() at the end of the loop. Each node
yielded by the generator is a basic Domlette node, with all the usual properties and
methods
this makes available, including the useful
xpath() method.
Compare listing 2 above to listing 4 of "Decomposition, Process, Recomposition" and you'll get a sense of how this wrappering of ideas from that article simplifies things.
If DOM Is Too Lame for You
Pythonic APIs are meant to make life easier for the many users who find DOM too arcane and alien for use in Python. Almost all of the earlier article on Anobind is still valid in Amara. The biggest change is in the imports. I also added some concessions to people who really don't want to worry about URL and file details and the like; the eight lines of listing 1 from the earlier article can now be reduced to two lines (the top two of listing 3). Listing 3 is an example of how I could use Amara Bindery to display names and cities from listing 1, the functional equivalent of listing 2.
Listing 3: Amara Bindery code to print out all people and their street addresses
from amara import binderytools container = binderytools.bind_file('labels.xml') for l in container.labels.label: print l.name, 'of', l.address.city
binderytools.bind_file takes a file name, parses the file, and returns a data
binding, rooted at the object
container, which represents the XML root node.
Each element is a specialized object that permits easy access to the data using Python
idioms, with object property names based on the names of XML tags and attributes.
In a
typical expression of the prevalent attitude in the Python community, one blogger
called it
"turning XML into something useful."
The Natural Next Step: Push Binding
One possible problem with listing 3 is that the entire XML document is converted to Python objects, which could mean a lot of memory usage for large documents, for example, if labels.xml were expanded to have 10,000 entries in label elements. Amara Bindery does mitigate this a little bit by using SAX to create data bindings, but this may not be good enough. What would be great is some way to use the pushdom approach from listing 2 while still having the ease-of-use advantage of Amara Bindery. This option is available as the Push binding, illustrated in listing 4.
Listing 4: Amara Push binding code to print out all people and their street addresses
from amara import binderytools for subtree in binderytools.pushbind('/labels/label', source='labels.xml'): print subtree.label.name, 'of', subtree.label.address.city
You use patterns just as in listing 2 to break up the document, and just as in listing
2,
binderytools.pushbind is a generator that instantiates part of the document
at a time, thus never using up the memory needed to represent the entire document.
This
time, however, the values yielded by the generator are subtrees of an Amara binding
rather
than DOM nodes, so you can use the more natural Python idioms to access the data,
if you
prefer.
Modification
Amara Bindery makes it pretty easy to modify XML objects in place and reserialize them back to XML. As an example, listing 5 makes some changes to one of the label elements and then prints the result back out.
Listing 5: Amara Bindery code to update an address label entry
from amara import binderytools container = binderytools.bind_file('labels.xml') #Add a quote to the Langston Hughes entry #The quote text to be added new_quote_text = \ u'\u2026if dreams die, life is a broken winged bird that cannot fly.' #The ID of Hughes's entry id = 'lh' #Cull to a list of entries with the desired ID lh_label = [ label for label in container.labels.label if label.id == 'lh' ] #We know there's only one, so get it lh_label = lh_label[0] #Now we have an element object. Add a child element to the end #xml_element is a factory method for elements. #Specify no namespace, 'quote' local name #Append the result to the label element lh_label.xml_append(container.xml_element(None, u'quote')) #Now set the child text on the new quote element #Notice how easily the new quote element can be accessed lh_label.quote.xml_children.append(new_quote_text) #Change the added attribute #Even easier than adding an element lh_label.added = u'2005-01-10' #Print the updated label element back out print lh_label.xml() #If you want to print the entire, updated document back out, use #print container.xml()
Again, the code's comments should provide all the needed explanation.
Taming SAX
Sometimes, though perhaps rarely, you may need to process huge files that cannot easily
be
broken into simple patterns. You may need to write SAX code, but of course as discussed
often in this column, SAX isn't always an easy tool to use. Amara provides several
tools to
help make SAX easier to use, including a module
saxtools.xpattern_sax_state_machine which can write SAX state machines for
you, given patterns. In fact, this module is used in
domtools.pushdom and
binderytools.pushbind. There is also a framework, Tenorsax, to help
effectively linearize SAX logic. With Tenorsax, you register callback generators rather
than
callback functions, and, using the magic of Python generators, each callback actually
receives multiple SAX events within its logic, so you can use local variables and
manage
state more easily than in most SAX code. Listing 6 is an example using Tenorsax to
also go
through the labels XML file and print names and addresses. Tenorsax is overkill for
such a
purpose, and you've already seen how to accomplish it much more easily with Amara,
but it
should illustrate the workings of Tenorsax.
Listing 6: Tenorsax code to print out all people and their street address
import sys from xml import sax from amara import saxtools class label_handler: def __init__(self): self.event = None self.top_dispatcher = { (saxtools.START_ELEMENT, None, u'labels'): self.handle_labels, } return def handle_labels(self, end_condition): dispatcher = { (saxtools.START_ELEMENT, None, u'label'): self.handle_label, } #First round through the generator corresponds to the #start element event yield None #delegate is a generator that handles all the events "within" #this element delegate = None while not self.event == end_condition: delegate = saxtools.tenorsax.event_loop_body( dispatcher, delegate, self.event) yield None #Element closed. Wrap up return def handle_label(self, end_condition): dispatcher = { (saxtools.START_ELEMENT, None, 'name'): self.handle_leaf, (saxtools.START_ELEMENT, None, 'city'): self.handle_leaf, } delegate = None yield None while not self.event == end_condition: delegate = saxtools.tenorsax.event_loop_body( dispatcher, delegate, self.event) yield None return def handle_leaf(self, end_condition): element_name = self.event[2] yield None name = u'' while not self.event == end_condition: if self.event[0] == saxtools.CHARACTER_DATA: name += self.params yield None #Element closed. Wrap up print name, if element_name == u'name': print 'of', else: print return if __name__ == "__main__": parser = sax.make_parser() #The "consumer" is our own handler consumer = label_handler() #Initialize Tenorsax with handler handler = saxtools.tenorsax(consumer) #Resulting tenorsax instance is the SAX handler parser.setContentHandler(handler) parser.setFeature(sax.handler.feature_namespaces, 1) parser.parse('labels.xml')
Tenorsax allows you to define a hierarchy of generators which handle subtrees of
the
document. Each generator gets multiple SAX events. Tenorsax takes advantage of the
fact that
Python generators can be suspended and resumed. Each time a Tenorsax handler generator
yields, it is suspended, and when the next SAX event comes along, it's resumed. The
current
event information is always available as
self.event. Tenorsax allows you to
define dispatcher dictionaries which map SAX event details to subsidiary generators.
The
current subsidiary generator is called
delegate in listing 6, because the
relationship between a generator and its subsidiaries basically forms a delegation
pattern.
Tenorsax automatically creates and runs the delegates within the main event loop,
while not self.event == end_condition. The body of this loop is usually a
call back to the Tenorsax framework, although you can also add specialized logic for
the
events that you want each generator to handle itself.
end_condition is provided
by Tenorsax so that generators know when to quit. For a start element, the end condition
is
set up to be the event that marks the corresponding end element.
handle_leaf is
an example of linear logic across SAX events.
It aggregates text from multiple character events into one string, either the contents
of
the
name element or the
city element. It builds this using a local
variable, which is not possible with regular SAX. Usually, you'd have to use a class
variable that is governed by a state machine (so that it is not grabbing text from
the wrong
events). Listing 6 is certainly much more ponderous than all the other sample code
so far.
Again, you would not usually use the heavy artillery for Tenorsax unless you had logic
that
was very hard to force into one of the other facilities in Amara.
Wrapping Up
There is a lot more to Amara XML Toolkit than I can cover in this article. The aim of the project is versatility—giving the developer many flexible ways of processing XML using idioms and native advantages of Python. Because of the popularity of languages such as Java, many XML standards have evolved in directions that don't match up with Python's strengths. Amara looks to bridge that gap. If you're curious about the project name, see this posting.
As often happens in the holiday season, activity has been a bit slow. Holiday revels are also a good excuse for an announcement entitled "xsdb does XML, SQL is dead as disco." Seems Aaron Watters's xsdb project, "a framework for distributing querying and combining tabular data over the Internet," has been renamed "xsdbXML." The announcement is a bit sketchy on the role of XML, but looking at the use cases, it seems xsdbXML is based on pure XML expressions of relational tables, meaning it effectively short-circuits SQL (which is, after all, but one realization of the relational calculus, and one that many relational purists consider flawed). The queries are also expressed in XML. This is a very interesting project, and coming from the brains behind Gadfly, you can expect the highest technical standards. Perhaps less whimsical announcements will help it gain the notice it deserves.
Walter Döwald announced XIST 2.8. "XIST is an extensible HTML/XML generator written in Python. XIST is also a DOM parser (built on top of SAX2) with a very simple and Pythonesque tree API." This release now requires Python 2.4 and there have been some API changes. See the announcement.
Dave Kuhlman announced generateDS 8a. generateDS is a data binding that generates Python data structures from a W3C XML Schema. I covered generateDS an earlier article. This release adds support for mixed content, structured type extensions (limited support), attribute groups, and substitution groups (limited support). See the announcement. | http://www.xml.com/pub/a/2005/01/19/amara.html | CC-MAIN-2017-22 | refinedweb | 2,414 | 55.95 |
In this post we’re going to look at generic interface polymorphism in C#. Let’s start by defining a couple of example classes.
public class Message { public virtual string Text { get; set; } } public class DatedMessage : Message { public DateTime DateReceived { get; set; } }
We’ll also define an interface that serves as a queue to hold messages.
public interface IMessageQueue<T> { void Add(T message); T Read(); }
And finally we’ll write two implementations of
IMessageQueue. One for
Message objects and one specifically for
DatedMessage objects.
public class MessageQueue : IMessageQueue<Message> { readonly Queue<Message> messages = new Queue<Message>(); public void Add(Message message) { messages.Enqueue(message); } public Message Read() { return messages.Dequeue(); } } public class DatedMessageQueue : IMessageQueue<DatedMessage> { readonly Queue<DatedMessage> messages = new Queue<DatedMessage>(); public void Add(DatedMessage message) { messages.Enqueue(message); } public DatedMessage Read() { return messages.Dequeue(); } }
Enough preparation, let’s get going. If we take a look at our
MessageQueue class, we can easily see that it can hold both
Message and
DatedMessage objects. This makes perfect sense, because all
DatedMessages are by definition
Messages. Taking this one step further, we should therefore be allowed to do the following.
static void Main(string[] args) { var datedMessages = new DatedMessageQueue(); datedMessages.Add(new DatedMessage("Hello world", DateTime.Now)); var messages = (IMessageQueue<Message>)datedMessages; // ... }
However, while this code compiles, an invalid cast exception is thrown when we attempt to make our cast. But why? As all
DatedMessages are
Messages, an implementation of
IMessageQueue<DatedMessage> should equally be treatable as an implementation of
IMessageQueue<Message>, shouldn’t it?
In fact the answer to this question is no, and it’s not terribly difficult to see why. If this cast were legal, then nothing would prevent us from doing the following.
static void Main(string[] args) { var datedMessages = new DatedMessageQueue(); datedMessages.Add(new DatedMessage("Hello world", DateTime.Now)); var messages = (IMessageQueue<Message>)datedMessages; messages.Add(new Message("Hello Message")); //... }
While all
DatedMessages are also
Messages, not all
Messages are
DatedMessages. If the above code were allowed to execute, we would be attempting to add a Message to what is in reality a
DatedMessage-typed backing store—that is, a
DatedMessageQueue that uses a
Queue<DatedMessage> to internally hold its messages.
But what if you really do want to be able to perform this cast? Well, there is indeed a way to allow it. We simply need to guarantee that we will never add any additional elements to an
IMessageQueue. We do this by removing our
Add method, and by applying the
out keyword to our generic parameter.
public interface IMessageQueue<out T> { T Read(); }
The out keyword indicates that objects of type T will only ever come out of an instance of the interface. More specifically, it prohibits us from implementing any methods which take an instance of
T as an input parameter. Note that nothing prevents us from adding a message to an instance of our
MessageQueue or
DatedMessageQueue classes (which is why logically we cannot by default cast a
DatedMessageQueue to a
MessageQueue). We simply cannot add a message to an instance of
IMessageQueue itself.
So, what have we seen so far? Well, we’ve seen that by default a generic interface cannot be downcast to less-specific versions of itself due to the risk of an incompatible type being added to an internal backing store. However we’ve also seen that by forbidding any such addition by way of the out keyword we can allow such downcasting to occur.
This concept of downcasting is called covariance, as the direction of the cast goes along with the standard inheritance flow of more specific objects being treated as more general objects. To be precise, we say that the
out keyword makes
IMessageQueue covariant in T.
Now, let’s code a new interface, this time for a class which will write the same text to a bunch of message objects.
public interface IBatchMessageWriter<T> { void AddToBatch(T message); void Write(string text); List<T> GetMessages(); } public class BatchMessageWriter : IBatchMessageWriter<Message> { readonly List<Message> messages = new List<Message>(); public void AddToBatch(Message message) { messages.Add(message); } public void Write(string text) { foreach (var message in messages) { message.Text = text; } } public List<Message> GetMessages() { return messages; } }
Now, because we can add any
Message object to our Batch Message Writer, it logically follows that we can equally add any object whose class derives from
Message. After all, a
Message derivative is still a
Message at its core. Going one step further with this logic, we should then therefore be able to do the following.
static void Main(string[] args) { var writer = new BatchMessageWriter(); var datedMessageWriter = (IBatchMessageWriter<DatedMessage>)writer; // ... }
But just as in our first example, this code throws an invalid cast exception—and for a similar reason. If this cast were allowed, nothing would prevent us from calling
GetMessages, which would return a list of
DatedMessage objects. If we had previously added any plain
Message objects to the interface implementation by way of the
Add method, we would be attempting to cast these
Message objects to
DatedMessage objects, which is not allowed.
However once again, there is a way to permit this cast. We simply need add the
in keyword to the generic type argument
T in the interface definition.
in is the opposite of
out, in as much as it indicates that objects of type
T can only be used as input parameters to the interface. It therefore prohibits us from defining any method on the interface which returns
T. So if we want the above cast to be legal, we need to modify our
IBatchMessageWriter interface as follows.
public interface IBatchMessageWriter<in T> { void AddToBatch(T message); void Write(string text); }
It is important to note that, as with
out,
in doesn’t prevent us from adding a method to any class which implements
IBatchMessageWriter that returns an object of type
T. It simply prevents us from defining such a method on the interface itself.
So, to summarise, we’ve seen that applying the
in keyword to a generic type parameter on an interface allows the interface to be upcast to a more-specific version of itself. This makes sense, because a function that takes type T as input should also be able to take an object of any type that inherits from
T. The concept of a type being treatable as a more specific version of itself is known as contravariance, because it goes counter to the traditional inheritance flow where objects are treated as less-specific versions of themselves. | http://www.levibotelho.com/development/the-ins-and-outs-of-generic-interface-variance/ | CC-MAIN-2018-34 | refinedweb | 1,086 | 54.02 |
For the past week or so I have been playing around with Xamarin and creating an android app.
Well I now have an app in the Google Play Store. Check out.
Before you rush and download the app I must warn you that it doesn’t do much yet. It displays some content that is on my website and there are a few links to allow sharing of content. I have some ideas to display content from my blog and allow sharing. I also have some other ideas for apps that might actually be useful to people that are not me. If you have ideas or feature requests do let me know.
Ok how did I go about creating this app and getting it in the app store?
Xamarin is now part of Visual Studio so step one is install all the Xamarin features to Visual Studio and build an app.
Next I wanted to monitor my app. Now I know Application Insights doesn’t support apps so what tools are out there? HockeyAppis something I had heard of but they are in the process of being replaced with Visual Studio Mobile Centre.
It was relatively easy to hook up my app to Visual Studio Mobile Centre. First install the required nuget packages. Then add using statements and the following line to your MainActivity.cs file (these instructions are available on the Mobile Centre)
using Microsoft.Azure.Mobile;
using Microsoft.Azure.Mobile.Analytics;
using Microsoft.Azure.Mobile.Crashes;
using Microsoft.Azure.Mobile.Distribute;
using Microsoft.Azure.Mobile.Push;
MobileCenter.Start("[Unique ID]",typeof(Analytics), typeof(Crashes), typeof(Distribute), typeof(Push));
Now you can connect the Mobile Centre to your source code (VSTS in my case) and get it to run a build for every commit.
One complexity of the build is that you need to supply a keystore file (basically a certificate to digitally sign your app). I found the best way to do this was to use Visual Studio to create the file.
In VS2017 there is a option called Archive Manager under the tools menu. In here click the distribute button and select Ad-hoc. In the signing identity section you can create a keystore file. Enter a few details and a keystore file will be created in AppData\Local\Xamarin\Mono for Android\Keystore[keystore name][keystore name.keystore]
Once you have added the keystore file to your build you can enable the distribute option. Now you will get an email after every build with a link to install your app. You can also enable a build status icon like this
.
Every time your app crashes the details will be logged in the crashes section for you to explore and fix the issues.
The Analytics section allows you to explore how your app is being used. You can also add Analytics.TrackEvent(“Feature X”) to measure the usage of different features.
There are more things you can do which I will explore more at another time along with how to get your app into the Google Play Store.
The post Android App Development and the Visual Studio Mobile Centre appeared first on Funky Si's Tech Talk.
Discussion (0) | https://dev.to/funkysi1701/android-app-development-and-the-visual-studio-mobile-centre-2o2 | CC-MAIN-2021-17 | refinedweb | 532 | 65.93 |
Hi I was wondering how I could have a pause in the program for a certain amount of time. Something like this:
ignore the apvector and apstring stuff (it's a school program and they're gay and make me use it...ignore the apvector and apstring stuff (it's a school program and they're gay and make me use it...Code:#include <stdio.h> #include <time.h> #include <iostream> using namespace std; void wait ( int seconds ) { clock_t endwait; endwait = clock () + seconds * CLK_TCK ; while (clock() < endwait) {} } void main() { text=getfile(filename); cout << "Please wait"; foutopen(filename); for(int c=0;c<3;c++) { cout << ". "; wait(1); } letterfrequency(letfreq, text); getwords(words, text); sort(words,0,words.length()-1); apvector <int> wordfreq(words.length(),-1); wordfrequency(wordfreq, words); output(letfreq, wordfreq, words, filename); }
I found this wait function at cplusplus.com and it worked by itself but when i put it into this code it doesn't work right. Any help would be greatly appreciated | http://cboard.cprogramming.com/cplusplus-programming/76783-time-pause.html | CC-MAIN-2015-40 | refinedweb | 165 | 66.44 |
ListenerContextListener and HttpSessionListener.
Let us create a Servlet Listener that just counts the number of running http sessions and prints the details whenever a session gets created or destroy.
We will use Eclipse for developing our application and Apache Tomcat for deploying and running our application.
Step 1: Create dynamic web project in Eclipse
Create Dynamic Web Project in Eclipse and name it SessionListener
Starts eclipse and create a new dynamic web project with name SessionListener. Select Target runtime environment. I have selected Apache Tomcat v6.0, you can select any Tomcat version that you have installed. Click on Finish.
Step 2: Create package & HTTP Session Listener class
Create package and session listener class
Create a package for Session Listener in your source folder of Project. I have created a package
net.viralpatel.servlet.listener. Inside the package, create a Java class file called
SessionListener.java.
Copy following content into newly created SessionListener class.
SessionListener.java
package net.viralpatel.servlet.listener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class SessionListener implements HttpSessionListener { private int sessionCount = 0; public void sessionCreated(HttpSessionEvent event) { synchronized (this) { sessionCount++; } System.out.println("Session Created: " + event.getSession().getId()); System.out.println("Total Sessions: " + sessionCount); } public void sessionDestroyed(HttpSessionEvent event) { synchronized (this) { sessionCount--; } System.out.println("Session Destroyed: " + event.getSession().getId()); System.out.println("Total Sessions: " + sessionCount); } }
In this listener example, we have implemented an interface
javax.servlet.http.HttpSessionListener and override its methods
sessionCreated and
sessionDestroyed.
The
sessionCreated() method will be called by the servlet container whenever a new session is created for this application. An object of javax.servlet.http.HttpSessionEvent class is passed as an argument to the sessionCreated method. This object can be used to get the session related information including session ID. In our example we have used a counter sessionCounter which counts the number of live session at any given point of time. Whenever a new session is created, this count gets incremented.
The
sessionDestroyed() method will be called by the servlet container whenever an existing session is invalidated. We have used this method in our example to decrement the session count and display the ID of session being destroyed.
Step 3: Create Http Session Listener entry in Web.xml
Open Web.xml file from WEB-INF directory of your Project and add following entry for listener tag.
In this entry, we have added SessionListener class in Web xml. Hence for every session creation and invalidation, the methods will be called by servlet container.
Step 4: Create JSP files for session tracking
We will create a small web application to test the functionality of Session Listener. There will be 3 JSP files, index.jsp will display a list of users. These users are stored in a session variable. The AddUser.jsp will add the user in the session variable. And the DestroySession.jsp will invalidate the session. Create three JSPs and copy following content into it.
index.jsp
AddUser.jsp
<%@page import="java.util.ArrayList"%> <%@page import="java.util.List"%> <% String username = request.getParameter("user"); List
users = (List )session.getAttribute("users"); if(null == users) { users = new ArrayList (); } users.add(username); session.setAttribute("users", users); response.sendRedirect("index.jsp"); %>
DestroySession.jsp
Step 5: Execute the web application
We are done with the coding part of HTTP Session Listener example. Now execute the project by Run -> Run As -> Run on server (shortcut Alt+Shift+X, R).
Check the console you will see the output that we print using System.out.
Add users and see the list of users added and also check the console output to see the logs for session creation and session count.
Once you click Destroy Session, the session gets invalidated and the session count is decremented.
Download Source code
Download WAR file with Source code (4.14kb)
Feel free to change the code and experiment with session listener
Hi Veeral,
in index.jsp , for the line List user = (List)session.getAttribute(“username”); it says “Type safety: Unchecked cast from Object to List” error. ????
Hi Veeral,
sorry the above comment has been modified …. for the line List user = (List)session.getAttribute(“username”); it says Type safety: Unchecked cast from Object to List” error. ????
Also, in index.jsp you’ve written, List users = (List)session.getAttribute(“users”);
please explain where did we set the attribute “users” and in this jsp file how would the container know that session is an object of HttpSession as in this file we never declared it ….
Sorry if I am being pain, but I am new …
@digant: session is an implicit object defined by container in JSP. You can directly use it in JSP without declaring it. I will suggest you to refer
The user object is set in session in AddUser.jsp
In the sessionDestroyed method do we need to explicity call invalidate method or will it be invalidated automatically. I have a case where even after session being getting destroyed, the servlet gives the same session id.
if users close their browser window,sessions get invalidated automatically..and in that case sessionDestroyed() method never get called..is there ne solution of it??
pls post..as soon as possible..thankx in advance..
What would be the time delay between actual session invalidation and session destruction. Is it always consistent?
very nice and well explained tutorial, thanks a lot man.
SessionListen
when ever i put this code in my web.xml file it give error like
init:
deps-module-jar:
deps-ear-jar:
deps-jar:
library-inclusion-in-archive:
library-inclusion-in-manifest:
compile:
compile-jsps:
Incrementally deploying
Completed incremental distribution of
Incrementally redeploying
Start is in progress…
start?path=/WWAtlas
FAIL – Application at context path /WWAtlas could not be started
G:\Dhiren\workspace\WWAtlas\nbproject\build-impl.xml:706: The module has not been deployed.
BUILD FAILED (total time: 3 seconds)
when i removethis its work fie
pleas any one can give me solutin for that..its very helpful for me.
Thisnt is very much important for us.
There is a huge delay for invoking the sessionDestroyed method. Is there a way to reduce it?
Is the session is automatically created here??
Is there no need of HttpSession session=request.getSession()??
is it necessary to use filters and listeners to handle session?isn’t it possible to set and get attributes procedure?
Thank you for your post!. I could resolve a long pending problem using the listener code sample you presented in this post.
I want to invoke sessionDestroyed method on close of browser tab (or browser )? Please guide me on how to that.How does my servler know that any one of the logged in users has closed browser tabs?
Great! thanks.
complete, concise and thank you
Hi,
What are the areas where we can use SessionListner? Why do we need this? Any real life example would be great.
Please revert. | https://viralpatel.net/blogs/jsp-servlet-session-listener-tutorial-example-in-eclipse-tomcat/ | CC-MAIN-2019-09 | refinedweb | 1,141 | 52.26 |
"Bob Pearson" <rpearson@systemfabricworks.com> wrote on 2011/08/02 23:14:39:>> Hi Joakim,>> Sorry to take so long to respond.No problem but please insert you answers in correct context(like I did). Thismakes it much easier to read and comment on.>> Here are some performance data collected from the original and modified> crc32 algorithms.> The following is a simple test loop that computes the time to compute 1000> crc's over 4096 bytes of data aligned on an 8 byte boundary after warming> the cache. You could make other measurements but this is sort of a best> case.>> These measurements were made on a dual socket Nehalem 2.267 GHz system.Measurements on your SPARC would be good too.>> #ifdef CONFIG_CRC32_PERFTEST> #include <linux/time.h>>> static u8 __attribute__((__aligned__(8))) test_buf[4096];>> /* need to convince gcc to not optimize out all the crc calls as dead code> */> u32 crc;>> static int __init crc32_init(void)> {> int i;> struct timespec start, stop;> u64 nsec_le;> u64 nsec_be;>> for (i = 0; i < 4096; i++)> test_buf[i] = i;>> crc = crc32_le(0, test_buf, 4096);> crc = crc32_le(crc, test_buf, 4096);>> getnstimeofday(&start);> for (i = 0; i < 1000; i++)> crc = crc32_le(crc, test_buf, 4096);> getnstimeofday(&stop);>> nsec_le = stop.tv_nsec - start.tv_nsec +> 1000000000 * (stop.tv_sec - start.tv_sec);>> crc = crc32_be(0, test_buf, 4096);> crc = crc32_be(crc, test_buf, 4096);>> getnstimeofday(&start);> for (i = 0; i < 1000; i++)> crc = crc32_be(crc, test_buf, 4096);> getnstimeofday(&stop);>> nsec_be = stop.tv_nsec - start.tv_nsec +> 1000000000 * (stop.tv_sec - start.tv_sec);>> pr_info("crc32: nsec_le = %lld nsec_be = %lld\n", nsec_le, nsec_be);>> return 0;> }>> module_init(crc32_init);> #endif /* CONFIG_CRC32_PERFTEST */>> Here are the timings.>> CRC_?E_BITS crc_le(nsec) crc_be(nsec)> orig crc32.c 8 5842712> 5829793>> new crc32.c 64 2877530> 2862515> new crc32.c 32 5174400> 5105816 (Equiv. to orig. BITS = 8)I really can't wrap my head around why your 32 bits version is faster than thecurrent one. Especially as you say that 2D array is a little faster that 1D array.The current impl. already uses a 2D array. Can you identify what makes you versionfaster?>> Modify all 'i' loops from for (i = 0; i < foo; i++) { ... } to for (i = foo> - 1; i >= 0; i--) { ... }That should be (i = foo; i ; --i) { ... }> + count down 64 2837860> 3230438>> 2865727 3264033 (repeat)> + count down 32 5177334> 5070337> Results seem ambiguous on Nehalem. Slight improvement in> some cases. 12% worse in one case.>> Modify main loop to use pre-increment instead of post-increment.> + pre-increment 64 2872502> 2767601> + pre-increment 32 5100579> 5090453> Small scale improvements for each case. Will add to next> drop.>> Do both count down and pre increment> + ct down + pre-inc 64 3329125> 3367815> + ct down + pre-inc 32 5065308> 5089825> Got significantly worse for 64 bit slightly better for> 32.>> Separately I looked at the difference between 1D and 2D arrays and 1D arrays> are a few % faster. The difference is that the loader computes the base> address at compile time. In the 2D case you have to add an offset to a> parameter that was passed in to the body routine which is a runtime> addition.I image the difference is even bigger on RISC archs like PowerPC and SPARC asthese may need 2 insns to load an address. A relocatable kernel would be evenworse I think.>> The first comment below relates to the behavior of gen_crc32table.c which> always printed out 256x4 byte table entries at a time. The CRC32_?E_BITS = 2> and 4 cases only read the first 4 and 16 table entries respectively so if> you are trying to make a really small image you can save most of 1KB by> shortening the table.Surely this could be fixed without moving to 1D arrays?>> I think I just caused more confusion below. The point is that the two> routines crc32_le and crc32_be take a byte string as argument which is> invariant under big/little endian byte order and produce a u32 which is just> an integer. All the byte swapping in the code is implementation detail and> has no effect on the result. The caller should just do what you normally do> with an integer when you use it in a network message e.g. call htonl or> equivalent before putting it in a packet.>> Last point below. The existing code fails sparse with __CHECK_ENDIAN__.> (There are several other sparse fails in lib as well BTW.) I cleaned up> these warnings by forcing everything to u32.What about unrolling the 32 bit variant instead of doing 64 bit? The 64 bitvariant looks like an unrolled 32 bit variant:+ q = *++p32 ^ crc;+ i3 = q;+ i2 = q >> 8;+ i1 = q >> 16;+ i0 = q >> 24;+ crc = t3_be[i3] ^ t2_be[i2] ^ t1_be[i1] ^ t0_be[i0];+ q = *++p32 ^ crc;+ i3 = q;+ i2 = q >> 8;+ i1 = q >> 16;+ i0 = q >> 24;+ crc = t3_be[i3] ^ t2_be[i2] ^ t1_be[i1] ^ t0_be[i0];I have a really hard time accepting the code duplication your patch introduces.Can you not find a way to add whatever changes you want into the current impl. ?Finally, your last patch does to much. Changing the unit test code shouldbe a separate patch. Restructuring the code is another one and 64 bit supportshould be a separate patch too. Jocke>> I will include Andrew's comments with the above and send out another patch> soon.>> Regards,>> Bob Pearson>> > -----Original Message-----> > From: Joakim Tjernlund [mailto:joakim.tjernlund@transmode.se]> > Sent: Monday, August 01, 2011 4:20 AM> > To: frank zago; Andrew Morton; Bob Pearson> > Subject: Re: [PATCH] add slice by 8 algorithm to crc32.c> >> >> > Hi Bob, Frank and Andrew> >> > I just got back from vacation and noticed this patch in the kernel mail> archive.> > I have pasted some> > bits from there and commented too.> >> > > Hello,> > >> > > Added support for slice by 8 to existing crc32 algorithm. Also> > > modified gen_crc32table.c to only produce table entries that are> > > actually used.> >> > Hmm, I don't get this. What entries are unused?> >> > > The parameters CRC_LE_BITS and CRC_BE_BITS determine> > > the number of bits in the input array that are processed during each> > > step. Generally the more bits the faster the algorithm is but the> > > more table data required.> > >> > > Using an x86_64 Opteron machine running at 2100MHz the following table> > > was collected with a pre-warmed cache by computing the crc 1000 times> > > on a buffer of 4096 bytes.> > >> > > BITS Size LE Cycles/byte BE> > Cycles/byte> > > ----------------------------------------------> > > 1 873 41.65> > 34.60> > > 2 1097 25.43> > 29.61> > > 4 1057 13.29> > 15.28> > > 8 2913 7.13> > 8.19> > > 32 9684 2.80> > 2.82> > > 64 18178 1.53> > 1.53> > >> > > BITS is the value of CRC_LE_BITS or CRC_BE_BITS. The old> > > default was 8 which actually selected the 32 bit algorithm.> In> > > this version the value 8 is used to select the standard> > > 8 bit algorithm and two new values: 32 and 64 are> introduced> > > to select the slice by 4 and slice by 8 algorithms> respectively.> > >> > > Where Size is the size of crc32.o's text segment which> > includes> > > code and table data when both LE and BE versions are set to> > BITS.> >> > I miss the numbers from the current 32 bits impl. How does this new impl.> > for 32 bits compare to the current impl?> >> > >> > > The current version of crc32.c by default uses the slice by 4 algorithm> > > which requires about 2.8 cycles per byte. The slice by 8 algorithm is> > > roughly 2X faster and enables packet processing at over 1GB/sec on a> > typical> > > 2-3GHz system.> > > --- lib/crc32.c> > > +++ lib/crc32.c> > >> > > ...> > >> > > @@ -28,14 +31,17 @@> > > #include <linux/init.h>> > > #include <asm/atomic.h>> > > #include "crc32defs.h"> > > -#if CRC_LE_BITS == 8> > > -# define tole(x) __constant_cpu_to_le32(x)> > > +> > > +#include <asm/msr.h>> > > +#if CRC_LE_BITS > 8> > > +# define tole(x) (__force u32) __constant_cpu_to_le32(x)> > > #else> > > # define tole(x) (x)> > > #endif> > >> > > -#if CRC_BE_BITS == 8> > > -# define tobe(x) __constant_cpu_to_be32(x)> > > +#if CRC_BE_BITS > 8> > > +# define tobe(x) (__force u32) __constant_cpu_to_be32(x)> > > #else> > > # define tobe(x) (x)> > > #endif> > > @@ -45,54 +51,228 @@ MODULE_AUTHOR("Matt Domsch> > <Matt_Domsch@> > > MODULE_DESCRIPTION("Ethernet CRC32 calculations");> > > MODULE_LICENSE("GPL");> > >> > > -#if CRC_LE_BITS == 8 || CRC_BE_BITS == 8> > > +#if CRC_LE_BITS > 8> > > +static inline u32 crc32_le_body(u32 crc, u8 const *buf, size_t len)> > > +{> > > + const u8 *p8;> > > + const u32 *p32;> > > + int init_bytes, end_bytes;> > > + size_t words;> > > + int i;> > > + u32 q;> > > + u8 i0, i1, i2, i3;> > > +> > > + crc = (__force u32) __cpu_to_le32(crc);> > > +> > > +#if CRC_LE_BITS == 64> > > + p8 = buf;> > > + p32 = (u32 *)(((uintptr_t)p8 + 7) & ~7);> > > +> > > + init_bytes = (uintptr_t)p32 - (uintptr_t)p8;> > > + if (init_bytes > len)> > > + init_bytes = len;> > > + words = (len - init_bytes) >> 3;> > > + end_bytes = (len - init_bytes) & 7;> > > +#else> > > + p8 = buf;> > > + p32 = (u32 *)(((uintptr_t)p8 + 3) & ~3);> > > + init_bytes = (uintptr_t)p32 - (uintptr_t)p8;> > > + if (init_bytes > len)> > > + init_bytes = len;> > > + words = (len - init_bytes) >> 2;> > > + end_bytes = (len - init_bytes) & 3;> > > +#endif> >> > The difference in the above code is just two constants. Should be possible> > to avoid code duplication.> >> > > +> > > + for (i = 0; i < init_bytes; i++) {> >> > All for(..) loops should be changed to:> > for (i = init_bytes; i ; --i)> > This is easier for gcc to optimize. Always compare to zero when possible.> >> > > +#ifdef __LITTLE_ENDIAN> > > + i0 = *p8++ ^ crc;> > > + crc = t0_le[i0] ^ (crc >> 8);> > > +#else> > > + i0 = *p8++ ^ (crc >> 24);> > > + crc = t0_le[i0] ^ (crc << 8);> > > +#endif> > > + }> > >> > Better to hide in macro as current code do.> > ...> >> > > + for (i = 0; i < words; i++) {> > > +#ifdef __LITTLE_ENDIAN> > > +# if CRC_LE_BITS == 64> > > + /* slice by 8 algorithm */> > > + q = *p32++ ^ crc;> > > + i3 = q;> > > + i2 = q >> 8;> > > + i1 = q >> 16;> > > + i0 = q >> 24;> > > + crc = t7_le[i3] ^ t6_le[i2] ^ t5_le[i1] ^> > t4_le[i0];> > > +> > > + q = *p32++;> > > + i3 = q;> > > + i2 = q >> 8;> > > + i1 = q >> 16;> > > + i0 = q >> 24;> > > + crc ^= t3_le[i3] ^ t2_le[i2] ^ t1_le[i1] ^> > t0_le[i0];> >> > I am not convinced that converting the table matrix to several arrays is> faster.> > Now you have to load 8 addressed and then index them instead of just one> > address.> >> > Also, this looks more like unrolling the 32 bit variant. Are you sure that> you> > wont get just as good results by just unrolling the 32 bit variant?> >> > You also lost the pre increment which was faster on RISC archs like> ppc(sparc> > too?)> > last time I tested crc32 speed.> >> > > +# else> > > + /* slice by 4 algorithm */> > > + q = *p32++ ^ crc;> > > + i3 = q;> > > + i2 = q >> 8;> > > + i1 = q >> 16;> > > + i0 = q >> 24;> > > + crc = t3_le[i3] ^ t2_le[i2] ^ t1_le[i1] ^> > t0_le[i0];> > > +# endif> >> > ...> > > General comment. The use of le/be in this and the previous version of> > > crc32.c is confusing because it does not refer to little/big endian cpu> > > architecture but rather to the arbitrary choice made by different> protocols> > > as to whether the bits in a byte are presented to the CRC in little/big> > > *BIT* order. Some protocols (e.g. Ethernet, InfiniBand) process the bits> > > starting from the LSB and some (e.g. atm) process the bits in MSB order.> > > These routines (crc32_le and crc32_be) compute the CRC as a u32 in cpu> > byte> > > order. The caller has to then get the CRC into the correct order for> > > inclusion into the message. As a result there are four versions of the> >> > No, the caller does not have get the CRC into correct order, this is done> by> > crc32 code.> >> > > calculation:> > > BE bit order on BE byte order cpu, BE bit order on LE byte order cpu,> etc.> >> > What would be better? I don't see what to do. Linux requires both LE and> BE> > bit> > ordering. When we optimize heavily, CPU byte order becomes an issue that> > needs> > to be dealt with.> >> > > Some calculations are simplified by arranging the bits sequentially in> > WORDS> > > when we are going to process them in a certain order within each byte.> This> > > means that the tables used to compute crc32_be are easier to use in BE> > byte> > > order and that tables used to compute crc32_le are easier to use in LE> byte> > > order. That is the logic behind the following weird looking macros which> are> > > kept the same as the previous version except for the inclusion of> __force> > to> > > pass sparse with -D__CHECK_ENDIAN__.> >> > Don't understand, how is you code any different from what we have today?> >> > Jocke>> | https://lkml.org/lkml/2011/8/4/137 | CC-MAIN-2015-32 | refinedweb | 1,975 | 73.58 |
pthread_atfork - register fork handlers
[THR]
#include <pthread.h>.
Upon successful completion, pthread_atfork() shall return a value of zero; otherwise, an error number shall be returned to indicate the error.
The pthread_atfork() function shall fail if:
- [ENOMEM]
- Insufficient table space exists to record the fork handler addresses.
The pthread_atfork() function shall not return an error code of [EINTR].
None.
None.
There are at least two serious problems with the semantics of fork() in a multi-threaded program. One problem has to do with state (for example, unsatisfactory routines).. The parent process may avoid this by explicit code that acquires and releases locks critical to the child via pthread_atfork(). In addition, any critical threads need.
None.
atexit(), fork(), the Base Definitions volume of IEEE Std 1003.1-2001, <sys/types.h>
First released in Issue 5. Derived from the POSIX Threads Extension.
IEEE PASC Interpretation 1003.1c #4 is applied.
The pthread_atfork() function is marked as part of the Threads option.
The <pthread.h> header is added to the SYNOPSIS. | http://pubs.opengroup.org/onlinepubs/007904975/functions/pthread_atfork.html | CC-MAIN-2014-15 | refinedweb | 168 | 60.61 |
Created on 2015-01-17 13:51 by last-ent, last changed 2016-02-02 21:37 by last-ent.
Use of http.server.BaseHTTPRequestHandler for exploratory or simple usage, SimpleHTTPRequestHandler provides a good platform to start on. However, the current code in SimpleHTTPRequestHandler's send_head is tightly coupled together as a single unit.
This patch aims to break send_head down into composable parts so that any developer can subclass SimpleHTTPRequestHandler to create one's own HTTPRequestHandler class with their own custom behaviour without having to rewrite a lot of repeated code.
For example consider a developer wanting to address two usecases
* Use SimpleHTTPRequestHandler, but use index.html from a different directory.
* For certain GET urls, call on a specific function to response.
* Use custom html page instead of index.html
class CustomHTTPRequestHandler(SimpleHTTPRequestHandler):
def do_GET(self):
if self.path =='/':
f = self.home_head()
elif self.path in self.custom_paths:
f = self.special_head()
else:
f = self.send_head()
# ...
# Standard Code
As a result of the patch, in above scenario instead of copy-pasting logic for browser redirection, getting object for file or directory and, applying headers upon success; Developer can use methods redirect_browser, get_dir_or_html_dir_path and, apply_headers to reduce the code.
Basically, applying DRY principle.
Note: Since this is but refactoring of existing code without any new functionality being added, no test cases are provided.
> + base_files = ['index.html', 'index.html']
I guess this should be ['index.htm', 'index.html'].
Changing base_files to point @ ['index.htm', 'index.html']
@vadmium: My Mistake. It should read "file path" not "file object". (500 error when submitting to review page.)
Renaming get_html_or_dir_path to get_path_or_dir for accurate description.
Also renaming copyfile to more pythonic copy_file.
I am having some issues with replying to comments on review page. It is giving 500 error hence posting replies here.
@berker.peksag: Thanks! I will add the methods' documentation & examples into the Doc/library/http.server.rst. As well as include a few unit tests.
I searched through github and there doesn't seem to be many examples of "BaseHTTPRequestHandler copyfile". Still if you feel it is better not to make this change, I will revert it back.
I have submitted the contribuer-form on the same day as I submitted this patch. Waiting for it to be accepted.
Thanks again.
Following is updated patch with
* Refactored code with helper functions
* Unit Tests
* Documentation - Explanation + Examples
SimpleHTTPRequestHandler's copyfile has been renamed to copy_file but not shutils'.
Thanks for the work! I'm not sure why the last patch doesn't appear on Rietveld, so (unfortunately) here's the result of my review. I've only covered functional aspects in this run at it:
+ base_files = ['index.html', 'index.htm']
Can you use "index_files"? That's the commonly used term to refer to these files.
- def copyfile(self, source, outputfile):
+ def copy_file(self, source, outputfile):
As Berker mentioned, we can't just rename this as it's not backwards compatible. Standard library modules aren't the only dependency. Such a change would cause breakage in, say, any 3rd party code that subclasses SimpleHTTPRequestHandler. This should remain as copyfile.
+ def redirect_browser(self, path, parts):
Can "_browser" be dropped here? This applies to all clients, not only browsers. Additionally, I think that the name is a little misleading. I think it would be better to have a generic public redirect(<url>, status=http.FOUND) method and then an internal _resolve_path() that calls into the redirect method using the Apache-like logic. It also seems like the path parameter is unused so should be dropped.
+ def get_path_or_dir(self, path):
I think the content of this method should be changed to result in consistent output. Right now, you're either returning a file path /or/ a BytesIO object containing the full output of the directory listing. It might make sense to have a single method that takes the path and produces consistent BytesIO object, regardless of whether it's a directory or a file path.
+ self.send_response(301)
Please use the http.HTTPStatus enum for status codes (i.e. http.HTTPStatus.MOVED_PERMANENTLY)
+ def apply_headers(self, f, path)
I don't think that this makes sense as a public API as it is as it only accounts for a 200 response. What if any error conditions are raised with the given file? As this is functionality specific to the single case in which it's used, I think this should either be left as-is, made more generic to handle header values based on any potential state of the file object, or made into a private helper method (indicated by a single underscore prefix to the method name).
Also, you should be able to derive the path from the file parameter (f.name), so I'm not sure that the extra path parameter is necessary.
+ def get_response(self, tail=False)
tail should default to None here, otherwise it's a little confusing as to why a parameter that /looks/ like it should be a bool actually expects a string value.
@demian: That's a tall order! :)
I would love to use HTTPStatus but for some reason http/__init__.py is devoid of code related to it -
I wasn't sure why this change was made because it like feels a step backwards. Will someone else be reverting it back or should I just include it in this patch or create another one?
As for rest of your comments, I will make the necessary changes and put up next patch.
@demian: If you don't mind, could you please elaborate a bit more on `_resolve_path()` you mentioned in the review/comment? Or maybe link me to the type of behaviour you mentioned? I will accordingly make the changes. As for self.apply_headers, I will see if I can make it more generic. As it stands, I have tried not to make any radical changes in existing logic; This being my first patch and all.
> I would love to use HTTPStatus but for some reason http/__init__.py is devoid of code related to it -
See the default branch:
> @demian: If you don't mind, could you please elaborate a bit more on `_resolve_path()` you mentioned in the review/comment?
Sure. In your patch, you have redirect_browser (or redirect if you
renamed it), which sounds like it's allowing for a very generic event to
happen: executing a redirect based on a passed in path. What I would
expect from calling into this is that the input path would be used as
the Location header in the resulting response. For example (using the
code as-is):
self.redirect_browser('')
The above would result in the response Location header being set to
input URL. What it's actually doing is a very specific thing:
Redirection if the final char in the input URL is '/', which is
something that I don't think needs to be exposed as part of the public API.
So, my recommendation is to do something like this:
def redirect(self, url, status=http.HTTPStatus.FOUND):
self.send_response(status)
self.send_header('Location', url)
self.end_headers()
Add a private helper method:
def _resolve_path(self, url):
parts = urllib.parse.urlsplit(url)
[...snip...]
return new_path_with_appended_slash
And in the body of send_head, do something like:
resolved_path = self._resolve_path(path)
if path != resolved_path:
self.redirect(resolved_path)
> As it stands, I have tried not to make any radical changes in existing
logic; This being my first patch and all.
The tough thing with adding public API in general is that you have to
consider both API readability as well as various use cases, not only the
one that you're specifically writing code for. To make your first patch
a little easier, you /could/ change the public API methods that you've
added to private helper methods and rename them as it makes sense. At
least in that way, you don't need to worry about making the methods
generic and writing tests for each where functionality is enhanced. In
reality, it seems that that's exactly what you're trying to achieve:
Helper methods where you're grouping logical bodies of code rather than
a full blown public API change (but I could be misunderstanding your
intentions there).
Hope that all makes sense.
New patch for review! Let me know if anything is missing.
Based on the comments of many good netizens,
I have further updated the patch.
Thanks for the extra effort on this to satisfy multiple people's opinions. It's never an easy thing, especially when dealing with a decentralized group. My following comments are largely based on the public API. I haven't done a full review of the changes made to the tests.
All extraneous spaces should be removed. For example the first line here:
+
+ redirect_path = self._redirect_path(path)
+ if redirect_path:
> Lists the files we want the server to check and render to client. We can add/remove file names as required. Order of files denotes priority. Defaults to ['index.htm', 'index.html']
I think this might read a little better as:
"Overridable index files. If any of these files are present in a request pointing to a directory on the server's file system, the contents of the file will be returned. Otherwise, a directory listing will be returned. Defaults to ['index.htm', 'index.html']. Order of files denotes priority.
That said, I'm not a wordsmith so there may be a (much) better way of structuring this.
> +class HTTPStatusType(Enum):
This doesn't sit quite well with me and I think it really should be removed. There are very few cases (if any) that I can think of where this would be useful. Cases where I've encountered the need for a range check generally is around subsets (i.e. 200 and 201 mean entirely different things and /shouldn't/ be globbed together). Additionally (this is subjective), I find it a little strange that the value of an enum is a range.
If for some reason it stays, I think the values should at least be sets allowing for O(1) lookup.
> + def redirect(self, url, status=HTTPStatus.MOVED_PERMANENTLY):
There should be an assertion in this block that the status is one of the redirect codes (301, 302, 308). Calling redirect('/foo', status=200) doesn't make sense.
>+ if os.path.isfile(path):
+ return self.get_file(path)
+
+ # `path` has file with filename in self.index_files
+ for index_file in self.index_files:
+ index = os.path.join(path, index_file)
Before the directory-related logic executes, you could add a check in for isdir() and short circuit with a 404 rather than relying on an index file not being found and then running into list_directory(), which would result in a 404 with the message "No permission to list directory", which isn't actually correct in the case where the directory doesn't exist.
> get_status_type, apply_success_headers, apply_headers
I think that these three methods should be removed as they're superfluous, make the code less readable and is inconsistent with how responses and headers are sent throughout the rest of server.py. The general practice is:
self.send_response()
self.send_header()
self.send_header()
self.end_headers()
The code in this patch should match that.
get_status_type is not needed as it /should/, if anything, be a single line passthrough to a reverse lookup mapping. Iterating over each enum followed by an iteration over each value is not optimal behaviour (O(N) rather than O(1)).
Latest patch with simpler(?) logic?
@Demian: This is a tough task! And I appreciate your kind words.
I have gone through your comments and I have made a few changes as per your suggestion but I have refrained from a few as well.
> get_status_type, apply_success_headers, apply_headers
The reason I wrote these three methods is that when a new dev wants to try out the library, he shouldn't have to handcode all the boilerplate. It makes no sense to to re-write this part of code for each new implementation. It can always be overwritten when required and it follows existing functionality.
But I understand your idea of what should be part of Public API and I have changed the access levels of most of such methods to class methods.
I have updated `get_status_type` to be of O(1) (hopefully) and removed HTTPStatusType.
I think since it is quite easy to overwrite `apply_headers` & `_get_status_type`, the default implementation can be straight up used by anyone with no modification and still yield satisfactory behaviour.
As for Doc, I really have no idea how to make it better. Maybe someone else can submit a patch later on? Or if you are fine, I will include your own Doc.
Thanks again.
Thanks for the updated patch. I will tweak the docs before I commit the patch.
Thanks for the update! I wasn't expecting this to be such a friendly & positive experience. Glad to be proven wrong :)
Here is an enhancement to the existing SimpleHTTPServerTestCase.test_get() test case, that demonstrates the current implementation breaks serving index.html files by default.
I have updated the patch such that for any directory, if they have a file with name in index_files, it will be served by default. Also a few tweaks.
Here is another addition to the existing test suite to detect the bug with the duplicate 404 Not Found responses. It relies on running the non-Windows, non-root test that says
# chmod() doesn't work as expected on Windows, and filesystem
# permissions are ignored by root on Unix
In other words, you trigger it by requesting an unreadable file or directory.
Thanks for your replies to my comments, I think I am understanding your point of view better now. You want functions to either return a file object, or to mutate the connection and send part of the response, but not both (except for sending an error response):
* get_file() returns a file object only
* redirect() sends response headers only
I am trying find a neater way to avoiding calling apply_headers() when list_directory() has already sent the headers. How do you feel about calling apply_headers() from inside get_file_or_dir() and get_index_file()? Or at least put a big fat warning saying get_file_or_dir() may or may not have already sent the headers, indicated by the type of file returned.
Another option might be to split list_directory() into a get-file stage and an apply-headers stage. But in my experience the headers to send are usually tightly coupled with the content body. In this case both vary depending on the redirect, generated directory, or static file cases.
@vadmium: Thanks for the suggestion - I opted for the first one. While I wasn't happy with it being called twice, wasn't getting an idea of how to address it. Am I supposed to include your patch as part of my patch? I am not much knowledgeable about the protocol to follow in such cases, so I haven't included it.
You’re welcome to merge my test patch into yours if you want to. Or I could open a separate issue for it, I don’t mind.
No I think it's better if you put up a separate patch. That way any questions other reviewers will have, you will be better suited to answer them.
Cheers!
Opened Issue 23440 for my test changes
Hello,
Since this patch is in acceptable state, should the Status or Resolution be changed so that it is flagged to be merged into Python 3.5?
Thanks.
Ent, thanks for all your work on this, and thanks to Demian and Martin for their reviews. In the meantime, the Python 3.5 release cycle has reached feature code cutoff so, at this point, generally only bug fixes are being accepted into 3.5, which means this refactoring will likely land in 3.6. The next step is for a core developer to do a final review and then decide whether to commit it. Berker has been commenting on this issue so perhaps he will have time to handle it as 3.6 gets underway. (http is one of the modules/packages in the standard library where currently no core developer has volunteered to be its "expert" so we all share responsibility for it as time and interest permits.)
Ned is correct. I started to review the patch, but couldn't find time to do a complete review. I'll take a look at it in a week or two. Thanks!
Thanks Ned & Berker,
I can only imagine the amount of work the core devs have to deal with.
Hope my patch makes it through in next version.
Regards,
Ent
Hi,
Is it possible for this patch to be reviewed now?
Regards,
Ent | https://bugs.python.org/issue23255 | CC-MAIN-2021-17 | refinedweb | 2,775 | 65.42 |
i am getting below errori am getting below error
import java.text.NumberFormat; import java.text.ParseException; import java.text.ParsePosition; public class Parsing { public static void main(String[] av) throws ParseException { String input="11 ss"; ParsePosition pp=new ParsePosition(0); NumberFormat.getInstance().parse(input,pp); if (pp.getIndex() != (input.length() - 1)) throw new RuntimeException("failed to parse"); } } the code does is get the default Locale NumberFormat instance and uses it to try to parse the input String. The EN_US pattern is something like "###,###.###" where there are some number of digits left and right of the decimal point with comma as the group separator and period as the decimal point. The exact pattern doesn't matter because the input contains non-numeric characters (" ss") that violate the pattern.
When you run this code, it stops parsing the input on the space at position 2. The parse method sets the index of the ParsePosition object supplied to the value 2 (because that's the first character it could not parse) and returns a Number object with the int value 11. So far, everything is just fine and you could go about your business with the parsed value of 11. What the code expects, however, is that it should be able to parse the entire input String as a number, not just part of the value. That's where the check for pp.getIndex() != (input.length() - 1) comes in. If the check fails, the full String was not parseable as a number, then the RuntimeException is thrown.
Having said that, this particular example contains an error. The only successful parse that avoids an exception is when the input String is some number of pattern characters followed by a single non-pattern character. For example, the values: 123,456x, 33.75y, 3,475.99z, 11% all parse without throwing a RuntimeException. The check for a fully-parseable input should have been pp.getIndex() != input.length() as the parse method sets the index of ParsePosition to the index of the next character to parse when it consumes all the input so if the length of the input is 5 and all the characters are parsed, the ParsePosition.index will be the index 5 (characters at indexes 0-4 were all digits).
Regards,
Jim
The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.
Open in new window
intValue cannot be resolved or is not a field
11
if i change my code like below
Open in new window
how do i get
11 13 15
and how do i get
ss aa
please advise
Open in new windowThe output of which is:
Open in new window
what above two lines do?
one just prints all numbers other prints all strings by separating with " "
How the incrementer is increasing after it is being set to 0 as below?
ParsePosition pp = new ParsePosition(0);
Number number = NumberFormat.getInstance()
>> How the incrementer is increasing ...
ParsePosition is constructed with an index (current parse position of the input) of 0 so NumberFormat knows to start with the first character of the input string. As it parses the input, NumberFormat updates the index in the supplied ParsePosition object to represent its progress. As the javadoc for getIndex() says: "On input to a parse method, this is the index of the character at which parsing will begin; on output, it is the index of the character following the last character parsed." This is how the parse method provides additional information to the client beyond the actual return value of the method.
Jim
Experts Exchange Solution brought to you by
Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.Start your 7-day free trial
This happens behind the scenes which we cannot see in the code right?
please advise
Regards,
Jim | https://www.experts-exchange.com/questions/28745431/parse-example.html | CC-MAIN-2018-51 | refinedweb | 675 | 62.88 |
C Program for Infix to Postfix Conversion. Here we covert the infix expression to postfix expression by using stack. for example a*b-c/d is the infix expression, and equivalent postfix expression is: ab*cd/-.
***********************************************************/
#define SIZE 50 /* Size of Stack */
#include <ctype.h>
char s[SIZE];
int top = -1; /* Global declarations */
push(char elem) { /* Function for PUSH operation */
s[++top] = elem;
}
char pop() { /* Function for POP operation */
return (s[top--]);
}
int pr(char elem) { /* Function for precedence */
switch (elem) {
case '#':
return 0;
case '(':
return 1;
case '+':
case '-':
return 2;
case '*':
case '/':
return 3;
}
}
main() { /* Main Program */
char infx[50], pofx[50], ch, elem;
int i = 0, k = 0;
printf("nnRead the Infix Expression ? ");
scanf("%s", infx);
push('#');
while ((ch = infx[i++]) != ' ') {
if (ch == '(')
push(ch);
else if (isalnum(ch))
pofx[k++] = ch;
else if (ch == ')') {
while (s[top] != '(')
pofx[k++] = pop();
elem = pop(); /* Remove ( */
} else { /* Operator */
while (pr(s[top]) >= pr(ch))
pofx[k++] = pop();
push(ch);
}
}
while (s[top] != '#') /* Pop from stack till empty */
pofx[k++] = pop();
pofx[k] = ' '; /* Make pofx as valid string */
printf("nnGiven Infix Expn: %s Postfix Expn: %sn", infx, pofx);
})
8 comments on “C Program for Infix to Postfix Conversion.”
program for postfix evaluation with output
Here’s link for C Program for postfix expression evaluation
I will add the sample output in few days. Meanwhile, if it’s urgent drop an email to [email protected] or get it touch with us using our Facebook Page.
not understandable for diploma level students please design another web for diploma level students please
Hi,
I am sorry if some of the program seem complex for you. I am happy to help you. Please get in touch over email or Facebook. Thanks.
Facebook Page:
can you please combine both postfix evaluation and infix to postfix programs and upload?
Hi Kushboo,
Thanks for asking. I’d be really happy to do that. I will create a new post with what you have asked and share link here.
I appreciate your patience.
Hi Khushboo,
I have posted the program you requested here. C Program For Infix To Postfix Conversion and Evaluation of postfix expression
You can also check it on our Facebook Page and share it. You can also start a discussion there. | https://c-program-example.com/2011/10/c-program-for-infix-to-postfix-conversion.html | CC-MAIN-2019-35 | refinedweb | 375 | 64.1 |
Myicq 19 Posted August 15, 2016 (edited) Just a small example, hope it will be useful to someone. (and not too trivial / simple) If the method can be improved, I would be happy to learn about it. Task : take a csv file with data, possibly organized in sets. Each line contains 1..n sets of data. Think 1 line of is a paper of labels. Each paper may have 1.. n labels where each label is 1 or more fields. Transform this to different column count of data set. Purpose is to transform customer data into different applications where different organization of data is needed. Source can of course be 1 column only. Example Spoiler;123;TEST1;;122;TEST1;124;TEST1;;121;TEST1;125;TEST1;;126;TEST1 This is 3 lines with 2 set of data each. Each data set has 3 items. If this is transformed into 4 columns, result should be Spoiler;123;TEST1;;122;TEST1;;124;TEST1;;121;TEST1;125;TEST1;;126;TEST1 The code: Spoiler expandcollapse popup; convert column count X to Y ; A,B ; C,D ; E,F ; ; to ; A,B,C ; D,E,F ; ----------- ; needed for function ; (library routine) #include <File.au3> ; how many columns in OUTPUT $no_of_col_out = 5 ; how many columns in input data, each set. $col_in_each_set = 3 ; separator for INPUT (each line fields split by this) $input_separator = ";" ; separator for OUTPUT $out_separator = ";" ; input file name $ifn = "myinputfile.txt" ; this is a variable for data $aData = "" ; we read ALL datafile into ONE array of arrays. ; each line is an array and element in $aData $readResult = _FileReadToArray($ifn, $aData,2, $input_separator) ; we open file for output here $of = FileOpen("out.txt", 2) ; overwrite mode ; this is the main loop ; go over each line in field $internal_column_counter = 1 for $i = 0 to UBound($aData)-1 ; then loop over each field in the line local $a = $aData[$i] for $j = 0 to UBound($a)-1 FileWrite($of, $a[$j]) ; output FIRST field ; if we reach number of fields in total (sets * fields per set) in a line, ; write a newline ; and start over if $internal_column_counter = $no_of_col_out * $col_in_each_set then FileWrite($of, @CRLF) $internal_column_counter = 1 else ; else just write a separator for next field FileWrite($of, $out_separator) $internal_column_counter+=1 EndIf Next Next ; add missing separators ; but not on lines that are blank ; ensures that files have same amount of fields on each line. if $internal_column_counter >1 then local $missing_columns_count = ($no_of_col_out * $col_in_each_set)-$internal_column_counter for $i = 1 to $missing_columns_count FileWrite($of, $out_separator) Next FileWrite($of, @CRLF) endif ; clean up FileClose($of) Is this example script too simple to be allowed here ? Edited August 15, 2016 by Myicq Updated script. Added clarification. I am just a hobby programmer, and nothing great to publish right now. Share this post Link to post Share on other sites | https://www.autoitscript.com/forum/topic/184110-convert-csv-coloumn-count/ | CC-MAIN-2018-39 | refinedweb | 463 | 61.77 |
TAP query¶
A library to query TAP servers¶
Contents
TAP is a relatively complex protocol to execute potentially long-running (ADQL) queries on remote servers. As a part of the GAVO VOTable library, we provide a shallow client that speaks TAP. It is the intention of this document to keep the TAP spec from your reading list. If it doesn’t do that, complain, and we’ll try to fix it.
Obtaining the library¶
See the GAVO VOTable Library documentation
For the impatient¶
All you need to query a server is its access URL. What we need here is
the root of the hierarchy, i.e., without any
sync or
async.
For the typcial case of a sync query, here’s the pattern to retrieve a sequence of dictionaries, one per result line, using sync querying:
from gavo import votable res = votable.ADQLSyncJob( "", "SELECT * FROM TAP_SCHEMA.tables" ).run() data, metadata = votable.load(res.openResult()) for row in metadata.iterDicts(data): print row
Here’s a variation using async querying (meaning: your query can take a long time if necessary), and yielding a numpy record array:
from gavo import votable from numpy import rec accessURL = "" query = "SELECT TOP 3 * FROM TAP_SCHEMA.tables" job = votable.ADQLTAPJob(accessURL, query) try: job.run() data, metadata = votable.load(job.openResult()) finally: job.delete() ra = rec.fromrecords(data, dtype=votable.makeDtype(metadata))
Note, however, that with record arrays NULL values will cause the whole thing to fail. So, if you are after record arrays, our advice is to install astropy and write:
from cStringIO import StringIO from astropy.table import Table from gavo import votable accessURL = "" query = "SELECT TOP 3 * FROM TAP_SCHEMA.tables" job = votable.ADQLTAPJob(accessURL, query) try: job.run() table = Table.read(StringIO(job.openResult().read()), format="votable") finally: job.delete() print table
More on dataIterator and metadata can be found in the GAVO VOTable library documentation.
The ADQLTAPJob¶
The class you will usually deal with is ADQLTAPJob, which is constructed with the endpoint URL and the query. The construction will access the, which means it may very well raise network-related exceptions.
You can pass a
userParams dictionary to the constructor. This is
intended for tho TAP parameters (in particular,
FORMAT,
MAXREC,
RUNID or service-defined ones). You should not use
userParams
for
UPLOAD but instead use the
addUpload method described below.
You can also change the parameters later using
setParameter(key, value). This again causes a server connection
to be made, as are accesses to ADQLTAPJob’s properties, viz.,
executionDuration– the number of seconds after which the server will kill your job. Simply assign some integer to change it, though of course the server might not let you.
destruction– a
datetime.datetime(in UTC) at which the job will be completely removed (i.e., even the results) from the remote server. Again, you can assign
datetimeinstances to try and change it.
phase– the current phase of the job. This is a string containing magic values; the possible values are PENDING, QUEUED, EXECUTING, COMPLETED, ERROR, ABORTED (these are also available as symbols in tapquery – this provides some ward against typos). Most of them are pretty self-explanatory, except that PENDING means you still can change the query, whereas QUEUED jobs are, well, in the server’s queue and cannot be changed any more. You should not assign to
phasemanually.
quote– returns an estimate of the number of seconds your job will execute on the remote machine. This is, of course, a guess even under the most favorable circumstances. Some servers choose to not even try to guess, in which case you’ll get a None. This cannot be assigned to.
parameters– a dictionary containing your parameters. You cannot assign to parameters, and changing things here has no effect. Use setParameter(key, value) instead.
Running a job¶
Once you have constructed (and possibly modified) a job, call
start()
to tell the remote server to put it into its execution queue.
You can then poll the job’s phase (now and then):
job = votable.ADQLTAPJob(...) job.executionDuration = 6000 job.start() while job.phase not in set([tapquery.ERROR, tapquery.COMPLETED]): time.sleep(10)
You can call
abort() to kill a running job, and you can call
delete() when done. As a matter of fact, although server operators
will eventually destroy your job anyway, it’s common courtesy to clean
up behind you unless you have good reason to keep the result data. So
the recommended pattern is:
job = votable.ADQLTAPJob(...) try: ... do your thing ... finally: job.delete()
Now, doing the polling by hand is tedious, and this there is a function
waitForPhases(phases, ...) that takes a set of phases to wait for,
and then polls at increasing intervals (that you could control though
the method’s further arguments; see API docs for details).
But really, the
run method is what you’d usually use; it has the
added advantage that it raises a
RemoteError or a
RemoteAbort exception
if something went wrong on the server side. So, the standard pattern is:
job = votable.ADQLTAPJob(...) try: ... add uploads, set parameters if you must ... ... change UWS parameters (executionDuration, destruction, etc) ... job.run() ... read results ... finally: job.delete()
TAP parameters¶
The following parameters are defined by the TAP spec:
FORMAT– the format you want to retrieve the data in. This defaults to votable, and you should probably keep that default with this library (since, if you have it, you can parse VOTables, right?). Other possibile values include csv, tsv, fits, text, or html. Servers must support VOTables, the other formats are optional
MAXREC– a limit as to how many rows are to be returned. This basically works like the
TOPphrase in ADQL and is rather superfluous when using ADQL.
RUNID– some identifier you can pass. It could be used for tracking and similar. The server should include it in results. If you don’t know what it’s for, you probably don’t need it.
LANG– the query language. In this library, it defaults to
ADQL. Let’s see if the library is flexible enough to support other languages (which are not specified yet).
REQUEST– specifies the operation you want from the server.
"doQuery"is what
ADQLTAPJobfills in for you, and it’s what you should leave it at.
QUERY– the query you are posing.
ADQLTAPJobspecifies it for you, but if you really wanted to, you could override it (e.g., using
setParameter.
UPLOAD– table uploads and such. While you could manipulate this manually, don’t. Use the
addUploadmethod.
Getting results¶
Right now, this library heavily leans towards ADQL. When doing ADQL
queries, there is only one result. You can access it using the
openResult() method, which returns a file-like object (actually,
it’s what
urllib.urlopen returns) that you can read your results
from. Since successful ADQL queries return single-table VOTables, you
can feed this directly to votable.load(f):
data, metadata = votable.load(job.openResult())
ADQL TAP results are simple web resources. To get their URLs, there’s
the
getResultURL method. This is particularly useful with uploads
(see below).
More complex query patterns could yield more results; in that case,
you will have to inspect
job.results, which is a list of triples of
an access URL, an opaque string-typed id, and a UWS “result type” that
you probably can safely ignore.
Errors¶
All exceptions originating in the library are subclasses of
tapquery.Error. For simple applications, this is also available as
votable.TAPQueryError.
The API docs list some exceptions you should expect; also, of course, all kinds of network-related exceptions could come out of the library. No serious attempt is being made to catch such exceptions and translate them. If something is wrong network-wise, we feel it’s better to freely admit this.
TAP-level errors (like syntax errors in the query, timeouts, and the
like) leave error information server-side. Rather than inspecting the
exception objects, you should use the
getErrorFromServer method on
the ADQLTAPJob.
In this, proper TAP error messages (those coming back as VOTables) are parsed out, data that’s not parseable as a TAP error message is returned as-is; thus the string returned may be long (e.g., some fancy 404 HTML page).
Uploads¶
TAP allows uploads to servers, although not all services actually support this (you can use a service’s capabilities to figure that out; we may add support for parsing those if there’s demand).
Services that do support it let you at least upload using URLs to
VOTables or upload VOTables inline. Both cases are supported in
ADQLTAPJob’s
addUpload(name, data) method.
name is the name
that the table will be visible as later. Use something that works as a
regular SQL identifier here.
data can be either a string (which is then interpreted as the URL to
take the upload from) or a file-like object (that is then turned into an
inline upload). In both cases, only VOTable is (reliably) supported as
the upload format.
Note that URLs of previous results work as upload URLs. Here’s an example of how that might look like, where this retrieves all objects in PPMXL in the vicinity of a detection of a neutrino:
from gavo import votable accessURL = "" job1 = votable.ADQLTAPJob(accessURL, "SELECT nualpha, nudelta FROM amanda.nucand WHERE nch>100") job1.run() job2 = votable.ADQLTAPJob(accessURL, "SELECT DISTINCT TOP 10000 raj2000, dej2000, pmRA, pmDE" " FROM ppmxl.main" " JOIN TAP_UPLOAD.nupos" " ON (1= CONTAINS(POINT('ICRS',raj2000,dej2000)," " CIRCLE('ICRS', nualpha , nudelta, 0.25)))") job2.addUpload("nupos", job1.getResultURL()) job2.run() dataIterator, metadata = votable.load(job2.openResult()) job1.delete() job2.delete() print list(dataIterator)
Sync Querying¶
TAP also supports a synchronous querying mode; for simple, quick
queries, this is simpler and has less overhead. So, if you are certain
that your query will run quickly and the result set is small, you can
use the ADQLSyncJob. This works mostly like the ADQLTAPJob, except of
course everything that deals with remote state management basically is a
no-op. Instead, either
run or
start just query the remote
server and return when the server is done. For convenience, they return
the job itself, so that you can say things like:
print votable.ADQLSyncJob( "", "SELECT * FROM TAP_SCHEMA.tables" ).run().openResult().read()
All “unpredictable” exceptions on sync jobs are raised from within
run; these will usually be
tapquery.WrongStatus or
tapquery.NetworkError exceptions, for when the TAP server has
complained or something was wrong on the way between the client and the
server.
The
WrongStatus instances have a payload attribute that contains any
message body the server might have sent with the headers; frequently
this contains explanations what may have gone wrong. Since no http
headers are available, there’s no saying what format the error message
came in. Tell us if that bugs you.
The error associated with the exception object will usually not be
particularly useful. Instead, obtain an error message from the server
using the
getErrorFromServer method like for ADQLTAPJobs. | https://dachs-doc.readthedocs.io/tapquery.html | CC-MAIN-2020-29 | refinedweb | 1,829 | 67.04 |
I have to make a high score display on the game over and menu scene, Right now I have just once you die, it displayes the score you had gotten from that run and then it deletes it (I assume because the data of the score is not being saved antywhere). I have no idea how to use player prefs but basically, from what I gather, I need to save the scores I get and then make the one with the highest value display. I have no idea how.. :( Here is my score script please help (Java and the name is GlobalScore): static var CurrentScore : int; var InternalScore : int;
var ScoreText : GameObject;
function Update () {
InternalScore = CurrentScore;
ScoreText.GetComponent.<Text>().text = "" + InternalScore;
}
Thanks!
Answer by LucyLuna
·
Apr 14, 2017 at 04:46 AM
Hope this helps: make an empty gameObject , then add the script below :
public class ScoreManager{
public static ScoreManager instance;
public int highestScore;
void Awake(){
if (instance == null) {
instance = this;
}
if (instance != this) {
Destroy (gameObject);
}
if (PlayerPrefs.HasKey ("score")) {
highgestScore = PlayerPrefs.GetInt ("score");
} else {
highgestScore = 0;
}
DontDestroyOnLoad (gameObject);
}
//it will save the score
public void Save(){
PlayerPrefs.SetInt ("score", highestScore);
}
}
Now , assign the highestScore when you want (i.e gameover)
if(currentScore > ScoreManager.instance.highestScore){
ScoreManager.instance.highestScore = currentScore;
ScoreManager.instance.Save();
}
Cheers. Wink
I made a new c# script, named it ScoreManager. I made a empty gameObject on the gameover scene and attached the script. Im getting the errors: The name "Destory, gameObject, highgestScore, highgestScore (again), DontDestroyOnLoad, and gameObject (again), "does not exist in the current context". And also, I have no idea what to do with the second part of your response, ex: where to put it, etc. Thanks for replying! Please help more Lucy!
Oops, I almost forgot
//without this , everything will be incorrect
public class ScoreManager : MonoBehavior{
}
and the second part is put where you want to end your game. For example: when your character collide with something that kills him, add the code there. Or when you exit the game ... etc. Hope that helps :)
Do you have this for java? It seems to be.
Highscore not working
0
Answers
when i reload the scene the score number remains the same and doesnt revert back to zero
1
Answer
How do I access playerprefs from another script?
1
Answer
Highscore with player prefs help. (JAVASCRIPT)
0
Answers
Highscore and PlayerPrefs unity C#
1
Answer | https://answers.unity.com/questions/1340378/help-making-a-high-score-with-player-prefsdisplayi.html | CC-MAIN-2020-05 | refinedweb | 399 | 64.91 |
pcap_lookupdev.3pcap - Man Page
find the default device on which to capture
Synopsis
#include <pcap/pcap.h> char errbuf[PCAP_ERRBUF_SIZE]; [DEPRECATED] char *pcap_lookupdev(char *errbuf);
Description
This interface is obsoleted by pcap_findalldevs(3PCAP). To find a default device on which to capture, call pcap_findalldevs() and, if the list it returns is not empty, use the first device in the list. (If the list is empty, there are no devices on which capture is possible.)
If pcap_init(3PCAP) has been called, this interface always returns NULL., or if pcap_init(3PCAP) has been called, NULL is returned and errbuf is filled in with an appropriate error message. errbuf is assumed to be able to hold at least PCAP_ERRBUF_SIZE chars.
See Also
pcap(3PCAP)
Bugs
The pointer returned by pcap_lookupdev() points to a static buffer; subsequent calls to pcap_lookupdev() in the same thread, or calls to pcap_lookupdev() in another thread, may overwrite that buffer.
In WinPcap and Npcap, this function may return a UTF-16 string rather than an ASCII or UTF-8 string. | https://www.mankier.com/3/pcap_lookupdev.3pcap | CC-MAIN-2021-21 | refinedweb | 171 | 61.87 |
Hi Mark,
Mark Willburger <Mark_Willburger@?.com> writes:
> 1) is there a way to get the absolute timestamp (time since 1970 for
> example)
For getting the miliseconds since Jan 1st 1970 you can e.g. put the
following code in _server script_:
from java.util import Date
d = Date()
ms = d.getTime()
rc.setLocal("ms1970", ms)
> 2) can a single instance of qftest run/control more than one program
> concurrently?
Yes, that's possible. Basically the "client" attribute specifies which client will be
controlled by the respective node (e.g. see 16.6.2 Start SUT client node).
You can simply start and control a second programm by using a different "client"
name.
A special form of running multiple clients is load testing as discribed in
manual "Chapter 14 Performing GUI-based load tests".
Best regards,
Karl
--
Karlheinz Kellerer Karlheinz.Kellerer@?.de
Quality First Software GmbH
QFS
Los geht's
Support
Über QFS
Kontakt
© 2018 QFS GmbH | https://www.qfs.de/qf-test-mailingliste-archiv-2006/lc/2006-msg00105.html | CC-MAIN-2018-09 | refinedweb | 156 | 67.96 |
I’ve become rather pedantic about my coding style over the years. I’ve worked in a number of people’s code, and have always felt most comfortable in the core NT code because of the consistency of formatting, naming, etc… This is a coding style that we often call "Cutler Normal Form" in deference to Dave Cutler.
Despite this I recently made a change in the way I place my braces around blocks of code. CNF says that braces go at the end of the line that will execute the code block, as follows:
if (foo) { do something; } else { do something else; }
I used to really like this style. It made it clear to me when the statement being evaluated was continued into the next block. Of course I always use braces, even when I only want one statement in the if or else clause, so this was a quick way to look and be sure i’d set things up correctly.
I’ve now transitioned over to:
if (foo) { do something; } else { do something else; }
This was the preferred style of the folks in the UMDF group when I joined the project. It took me a while to warm up to this. However i eventually found two things that i like about it.
First it leaves more open white space. In my "old age" (i.e. mid thirties) i find that i like more whitespace in my code. It improves the readability for me, and makes me work harder to keep my functions fitting on a single page – which is a good threshold for whether they’re understandable or not.
The second is that it makes it much, much easier to put part of the block under an IFDEF. This to me was the winner. Now i can do:
#if bar if (foo) { do something specific to bar; } else #endif { do something else; }
Rather than:
#if bar if (foo) { do something specific to bar; } else // note that there would otherwise be a { here #endif { do something else; }
Or even worse:
#if bar if (foo) { do something specific to bar; } else { #else { #endif do something else; }
Perhaps it’s a silly thing to change something as fundamental(ist) as brace formatting style to get around a little inconsistency in how you preprocess out part of a conditional. But i like consistency … the hairs on the back of my neck go up when i see code that’s not in my normal format. So in the end this made me more comfortable.
This has come up quite a bit for me when debugging something or refactoring something. When refactoring i’ll frequently #if out a chunk of impacted non-critical functionality (usually replaced with a failure case) until i’m ready to deal with that chunk of code. For debugging it can be useful to do the same thing if you’re trying to track down the cause of a crash and are at your witts end.
And I’ve come to find it prettier.
-p
PingBack from
I’ve always preferred the more expanded version, though in very simple cases I’ll write one-liners:
if(value > 100) value = 100;
I consider that better than the four-liner (including braces) and it clearly shows that only one instruction will occur.
I’m still waiting on a mainstream app/plugin that transparently formats code according to the user (maybe at the checkout point?). Having code formatted as you like to see it has a massive impact on how easy it is to read and modify.
I’d also been a CNF patriot … until I moved over and spent a while in C# and now I’m a fan of the new way, that is, the way you describe.
if (bar)
{
foo();
}
else
{
dang();
}
There’s a couple of other CNF things I’m a fan of, such as, braces always. That is, it doesn’t matter if it’s a single line body or multi line, you always use braces, never ever
if (bar)
foo();
else
dang();
I’ve been playing in open source for a while now and it takes me back to my old unix days but, those with coding styles in the current open source (linux) world seem to be very heavy proponents of NOT using braces for single line bodies. (I haven’t actually gone and read the linux kernel programming style guidelines but they do exist). Certainly in the last couple of days as I’ve been heavily adding print statements (for debugging) to some code it would have been easier to just add the print rather than the print AND the braces as I try to work out where the heck this code is going. So, I’ll remain a proponent of braces everywhere.
Another CNF’ism that I quite like is not to assume a boolean result (actually prohibited in C#). That is, use
if (foo == NULL)
{
return ERROR_SOMETHING_BAD;
}
rather than
if (!foo)
{
return ERROR_SOMETHING_CONFUSING;
}
Of course Dave is also a fan of always comparing to zero so you find a lot of
if (foo != FALSE)
which I found hard to read for a long time. But, the code produced for that is always likely to be better than for
if (foo == TRUE)
You’ll never get me to produce my locals in alphabetical order though 🙂
Say hi to the little un for me.
-P (the other)
Peter's a topic stealing stealer person. So rather than pout about how he's stolen my thunder
I am a bit older than you, in my 50’s and have been coding for over 30 years. I used to think that the difference in bracing styles was a generational thing, i.e the old guys, like me, liked the more expanded style, while the young Turks liked the more compact style. It is nice to see some of you younger guys agreeing with us dinosaurs.
As a coder in his 60’s I concur with sidnsd and the general theme. There ia a little program called astyle that does reformat code for you.
Enjoy!
btw
btw
value = max (value, 100); // neat and concise
Agree with this formating style, but with "else" I put it on the same line as the closing }.
"I'll remain a proponent of braces everywhere." Same here. | https://blogs.msdn.microsoft.com/peterwie/2008/02/04/pedantic-coder-where-do-braces-go/ | CC-MAIN-2016-44 | refinedweb | 1,056 | 73.92 |
On this post we are going to start developing our first game. The game we will be writing is going to be an adventure with ASCII graphics, meaning that we will present our world using console output. On the posts that will follow we will expand on this game, divert it to something different and maybe even start using real graphics.
Our goal for this post, is to print a basic map and move our character using console input in the form of north-south-east-west [nsew].
#define
#define is another pre-processor directive. Like we saw before, pre-processor is a program that runs before the compiler and performs text related tasks. #define defines text replaces.
#define SEARCH REPLACE
Every occurrence of SEARCH will be replaced with REPLACE
#define MAX 5 int main(){ int x = MAX; return 0; }
On the example above, the compiler ‘sees’:
#define MAX 5 int main(){ int x = 5; return 0; }
#defines have a lot of disadvantages but are very easy to use. For small programs they cannot inflict a lot of harm. However, the dumb and simple nature of the pre-processor can lead to some odd error messages, since no type or other checking is performed during that step. There are better alternatives to #defines that we will be seeing later on.
If
When running a program, we need to able to run code only under certain conditions. This is achieved using the if control structure:
if(boolean_expression) single_statement; if(boolean_expression) single_statement; else another_statement; if(boolean_expression){ block_of_code; } else { another_block_of_code; } if(boolean_expression){ block_of_code; } else if(different_boolean_expression) single_statement; else if(different2_boolean_expression) single_statement; else { block_of_code; }
If boolean_expression evaluates to true, then the code will run, otherwise the code will be skipped.
There are two versions, the one uses a code block ({}) and the other a single statement. Code blocks are very similar to statements, with the difference that they don’t return anything. Ifs also have else sections that run when the condition expression is evaluated to false. Else section is optional and can be omitted.
if(…){} is also a statement. That way you can chain else blocks in order to create an else if structure, that multiple conditions are checked back-to-back. We could argue that all versions are special cases of a general rule.
With some thought, it is easy to come to the conclusion, that if we reach to check a condition, all the previous conditions in the if,else if block have to be false.
The following code checks if the variable x is in (-infinity, -100],(-100,0),[0,infinity) sets and prints an appropriate message
if(x <= -100){ std::cout << "x in (-infinity, -100]" } else if(x < 0) std::cout << "x in (-100, 0)"; else std::cout << "x in [0, +infinity)";
Notice that, we do not have to check for both the edges of the sets, since the one of the edges was checked on the previous else if section.
while
While is like if, but it runs on a loop. While the condition is true, the block continues to run.
while(boolean_expression) expression;
Of course, expression can be a single statement, a code block, can be an if, or even another while!
A common use for while, is to iterate over a number sequence like i=0,1,2,3,4,5,6,…,M-1. Code for such iteration given below
int i = 0; while(i < M) std::cout << i++;
In C and C++ it is standard practice to start counting from 0 and check with less operator. It will be much clearer why later on, when we take a look on pointers.
Mini-boss
If we wanted to print the numbers i=1,…M instead of i=0,..M-1, what changes we should do on the previous snippet of code?
for
The previous while structure is so common, that there is a loop structure mostly for that! Meet for:
for(initial_expression; check_expression; at_end_of_iteration) expression; for(int i = 0;i < M;++i){ std::cout << i << "\n"; }
At the start of the loop, the initial expression is evaluated. Then, before entering the loop the check_expression is evaluated and if it true, then the loop continues, else it stops. At the end of every iteration and before the check, the third part of for is evaluated.
Mini-boss
rewrite the previous for, using while
do … while
Another loop structure is do .. while. I personally don’t use it very much, but here you go:
do { block_of_code; } while(boolean_expression);
Block of code is run at least once. Then the boolean_expression is evaluated. If it is true, it continues. Execution of the loop is stopped otherwise.
What you have to keep in mind is that all loop structures can be rewritten to an equivalent one, using a different loop structure.
break, continue
You can ‘escape’ from a loop early using the break; statement. You can also skip an iteration and go to the next using the continue; statement.
int x = 0; while(true){ if(x++ > 10) break; std::cout << x << "\n"; } for(int i=0; i < 20; ++i){ if(i == 10) continue; std::cout << i << "\n"; }
Reading from console
You should have learnt by now that console output uses std::cout and operator <<. Like cout, cin supports multiple types. Just keep in mind, that getting types mixed up (like providing character input when expecting number) can lead to the program breaking at the point of no return.
std::cin >> variable_to_be_read_into;
Game loops
A very important concept of video games and a lot of other programs, is that of the game loop. During every iteration of the game loop, a frame is simulated and drawn on display. The game loop keeps running until we exit the game.
while(true){ check_input; simulate_world; update_display; }
At check_input phase, we process inputs from the player. Then we simulate the “world” of our game. At the end, we update the display. Of course, there are more sophisticated versions of this loop, but the idea remains mostly the same.
modulo
An useful operator is modulo. It is the remainder of the integer division between two numbers and it is the operator %. For example:
std::cout << (10 % 3);//1 std::cout << (11 % 3);//2 std::cout << (12 % 3);//0
As you can see it loops around. In order to produce a sequence of numbers like this: 0,1,2,...,N,0,1,2,...,N,...
You can write code like this:
for(int i=0; i<100000; ++i){ std::cout << (i % (N+1)); }
The first version of the game
Now that we have covered all the base knowledge required, we can move on to the actual game code
#include <iostream> #define MAP_SIZE_X 5 #define MAP_SIZE_Y 4 #define EMPTY_TILE_SYMBOL '.' #define DOOR_TILE_SYMBOL '$' int main() { int character_x = 2; int character_y = 2; char character_symbol; int exit_x = 3; int exit_y = 1; std::cout << "Welcome to the dungeon\n"; std::cout << "Choose your character:"; std::cin >> character_symbol; bool done = false; while(!done){ //print map for(int j=0;j<MAP_SIZE_Y;++j){ for(int i=0;i<MAP_SIZE_X;++i){ if(character_x == i && character_y == j) std::cout << character_symbol; else if(exit_x == i && exit_y == j) std::cout << DOOR_TILE_SYMBOL; else std::cout << EMPTY_TILE_SYMBOL; } std::cout << "\n"; } char dir; std::cout << "Choose direction [nsew]:"; std::cin >> dir; if(dir == 'n'){ character_y--; if(character_y < 0) character_y = 0; } else if(dir == 's'){ character_y = (character_y + 1) % MAP_SIZE_Y; } else if(dir == 'w'){ character_x--; if(character_x < 0) character_x = 0; } else if(dir == 'e'){ character_x = (character_x + 1) % MAP_SIZE_Y; } else std::cout << "Invalid direction\n"; if(character_x == exit_x && character_y == exit_y) done = true; } std::cout << "You exited the dungeon\n"; return 0; }
Mini-boss
what parts of the code above correspond to the phases of a game loop?
Mini-boss
try giving "ne" as a single input. What happens and why.
Boss
try editing the file to make the map bigger, change symbols and make the game run for maximum of 5 frames; after that it should stop the loop. | http://easymode.chpetrou.net/c-cpp-l04-control-structures/ | CC-MAIN-2018-51 | refinedweb | 1,322 | 60.14 |
I’m trying something slightly different this time. Joe (the author) has reacted to specific points of my review, and I think it makes sense to show those reactions. I’d originally hoped to present them so that you could toggle them on or off, but this blog server apparently wants to strip out scripts etc, so the comments are now permanently visible.
Resources
- Buy from Amazon or Barnes and Noble
- Author’s web site
- Apress page (errata submissions etc)
Introduction and disclaimer
As usual, I first need to give the disclaimer that as the author of a somewhat-competing book, I may be biased and certainly will have different criteria to most people. In this case the competition aspect is less direct than normal – this book is “LINQ with the C# 3 bits as necessary” whereas my book is “C# 2 and 3 with LINQ API where necessary”. However, it’s still perfectly possible that a potential reader may try to choose between the two books and buy just one. If you’re in that camp, I suggest you buy my book try to find an impartial opinion instead of trusting my review.
A second disclaimer is needed this time: I didn’t buy my copy of this book; it was sent to me by Apress at the request of Joe Rattz, specifically for review (and because Joe’s a nice guy). I hope readers of my other reviews will be confident that this won’t change the honest nature of the review; where there are mistakes or possible improvements, I’m happy to point them out.
Content, audience and overall approach
This book is simply aimed at existing C# developers who want to learn LINQ. There’s an assumption that you’re already reasonably confident in C# 2 – knowledge of generics is taken as read, for example – but there is brief coverage of using iterator blocks to return sequences. No prior experience of LINQ is required, but the LINQ to XML and LINQ to SQL sections assume (not unreasonably) that you already know XML and SQL.
The book is divided into five parts:
- Introduction and C# 3.0 features (50 pages)
- LINQ to Objects (130 pages)
- LINQ to XML (152 pages)
- LINQ to DataSet (42 pages)
- LINQ to SQL (204 pages)
The approach to the subject matter changes somewhat through the book. Sometimes it’s a concept-by-concept “tutorial style” approach, but for most of the book (particularly the LINQ to Objects and LINQ to XML parts) it reads more like an API reference. Joe recommends that readers tackle the book from cover to cover, but that falls down a bit in the more reference-oriented sections.
[Joe] Early in the development of my book, a friend asked me if it was going to be a tutorial-style book or a reference book. I initially found the question odd because I never really viewed books as being exclusively one or the other. Perhaps I am different than most readers, but when I buy a programming book, I usually read a bit, start coding, and then refer to the book as a reference when needed. This is how I envision my book being used by readers and the type of book I would like for it to be. I see it as both a tutorial and a reference. I want it to be a book that gets used repeatedly, not read once and shelved. Some books work better for this than others. I rarely read a programming book cover to cover because I just don’t have time for that. I think ultimately, most authors write the book they would want to read, and that is what I did. I hope that if someone buys my book, in two years it will be tattered and worn from use as a reference, as well as read cover to cover.
I would disagree that the majority of the book reads like an API reference. Certainly, chapters 4 and 5 (deferred and nondeferred operators) work better as a reference because there isn’t a lot of connective context between the approximately 50 different standard query operators. At best it would be an eclectic tutorial with little continuity. So I decided to make those two chapters (the ones covering the standard query operators) function more like a reference. I knew that I (and hopefully my readers) would refer to it time and time again for information about the operators, and based on most of the reviews I have seen, this appears to have been a good choice. I know I refer to it myself quite frequently. I would not consider the chapters on LINQ to XML to be reference oriented although I could see why someone might feel they are. My discussion of LINQ to XML is tutorial based as I approach the different tasks a developer would need to accomplish when working with XML, such as how to construct XML, how to output XML, how to input XML, how to traverse XML, etc. However, within a task, like traversing XML, I do list the API calls and discuss them, so this is probably why it feels reference-like to some readers, and will function pretty well as a reference.
For example, take the ordering operators in LINQ – OrderBy, ThenBy, OrderByDescending and ThenByDescending. (Interestingly, one of the Amazon reviews picks up on the same example. I already had it in mind before reading that review.) These four LINQ to Objects operators take 15 pages to cover because every method overload is used, but a lot of it is effectively repeated between different examples. I think more depth could have been achieved in a shorter space by talking about the group as a whole – we only really need to see what happens when a custom comparison is used once, not four times – whereas every example of ThenBy/ThenByDescending used an identity projection, instead of showing how you can make the secondary ordering use some completely different projection (without necessarily using a custom comparer). Likewise I don’t remember seeing anything about tertiary orderings, or what the descending orderings tend to do with nulls, or emphasis on the fact that descending orderings aren’t just reversed ascending orderings (due to the stability of the sort – the stability was mentioned, but not this important corollary). Having an example for each overload is useful for a reference work, but not for a “read through from start to finish” book.
The set operators (Distinct, Except, Intersect, Union and SequenceEqual) as applied to DataSets suffer a similar problem – the five descriptions of why custom comparers are needed are all basically the same, and could be dealt with once. In particular, one paragraph is repeated verbatim for each operator. Again, that’s fine for a reference – but cutting and pasting like this makes for an irritating read when you see the exact same text several times in one reading session.
[Joe] A few readers have complained about some of the redundancies that you have pointed out, but I think most of the readers have appreciated my attempt to provide material for each operator/method. I think one of the words you will see most often in the Amazon reviews is “thorough”.
Now, it’s important that I don’t give the wrong impression here. This is certainly not just a reference book, and there’s enough introduction to topics to help readers along. If I’d been coming to C# 3 and LINQ without any other information, I think I’d have followed things, for the most part. (I’m not a fan of the way Joe presented the query expression translations, but I’m enormously pleased that he did it at all. I think I might have got lost at that point, which was unfortunately early in the book. It might have been better as just an appendix.) Anyone reading the book thoroughly should come away with a competent knowledge of LINQ and the ability to use it profitably. They may well be less comfortable with the new features of C# 3, as they’re only covered briefly – but that’s entirely appropriate given the title and target of the book. (To be blunt and selfish, I’m entirely in favour of books which leave room for more depth at a language level – that should be a good thing for sales of my own book!)
[Joe] Jon, if you only knew how difficult it was getting those query expression translations into the book. ;-) You can read in my acknowledgments where I specifically thank Katie Stence and her team for them. They were a very painful effort and in hindsight, I probably would not include them if I were to start the book from scratch. I agree with you that the translations are complex, as the book states. Perhaps the most important part of that section is when I state “Allow me to provide a word of warning. The soon to be described translation steps are quite complicated. Do not allow this to discourage you. You no more need to fully understand the translation steps to write LINQ queries than you need to know how the compiler translates the foreach statement to use it. They are here to provide additional translation information should you need it, which should be rarely, or never.”
However, I would personally have preferred to see a more conceptual approach which spent more time focused on getting the ideas through at a deep level and less time making sure that every overload was covered. After all, MSDN does a reasonable job as a reference – and the book’s web site could have contained an example for every overload if necessary without everything making it into print. The kind of thing I’d have liked to see explored more fully is the buffering vs streaming nature of data flow in LINQ. Some operators – Select and Where, for example – stream all their data through. They never keep look at more than one item of data at a time. Others (Reverse and OrderBy, for example) have to buffer up all the data in the sequence before yielding any of it. Still others use two sequences, and may buffer one sequence and stream the other – Join and Intersect work that way at the moment, although as we saw in my last blog post Intersect can be implemented in a way which streams both sequences (but still needs to keep a buffer of data it’s already seen). When you’re working with an infinite (or perhaps just very large – much bigger than memory) sequence you really need to be aware of this distinction, but it isn’t covered in Pro LINQ as far as I remember. In the interests of balance, I should point out that the difference between immediate and deferred execution is explained, repeatedly and clearly – including the semi-immediate execution which can occur sometimes in LINQ to SQL.
[Joe] I wanted my book to cover each overload because I can’t read MSDN in the bathroom, or when at the beach without an internet connection, or when curled up in a chair by the fireplace. I also wanted to provide examples for every method and overload because I find it frustrating when a book shows the simplest one and I have to figure out the one I need. Granted, depth could be added too, but you have to draw the line somewhere. Apress (at the time, not sure if this is still the plan) has the concept of three levels of book; Foundations, Pro, and Expert. I considered some information beyond the scope of the Pro level that my book is aimed at. The buffering versus streaming issue is an interesting one and would make an excellent additional column in Table 3-1, if I can get it to fit.
I’m unable to really judge the depth to which LINQ to SQL was explored, given that a lot of it was beyond my own initial knowledge (which is a good thing!). I’m slightly perturbed by the idea that it can be comprehensively tackled in a couple of hundred pages, whereas books on other ORMs are often much bigger and tackle topics such as session lifetimes and caching in much more depth. I suspect this is more due to the technologies than the writing here – LINQ to SQL is a relatively feature-poor ORM compared with, say, Hibernate – but a bit more attention to “here are options to consider when writing an application” would have been welcome.
Accuracy and code style
Most of Pro LINQ is pretty accurate. Joe is occasionally a bit off in terms of terminology, but that probably bothers most readers less than it bothers me. There are a few things which changed between the beta version of VS2008 against which the book was clearly developed and the release version, which affect the new features of C# 3. For instance, automatically implemented properties aren’t mentioned at all (and would have been much nicer to see in examples than public fields) and collection initializers are described with the old restrictions (the collection type has to implement ICollection<T>) rather than the new ones (the collection type has to implement IEnumerable and have appropriate Add methods). Other errors include trusting the documentation too much (witness the behaviour of Intersect) and an inconsistency (stating correctly that OrderBy is stable on one page, then incorrectly warning that it’s unstable on another). In my normal fashion, I’ll give Joe an exhaustive list of everything I’ve found and leave it up to him to see which he’d like to fix for the next printing, but overall Pro LINQ does pretty well. I suspect this may be partly due to covering a great deal of area but with relatively little depth and some repetition – Accelerated C# had a higher error rate, but was delving into more treacherous waters, for example.
[Joe] Since my book is not meant to be a C# 3.0 book, but rather a LINQ book, I only cover the new C# 3.0 features which were added to support LINQ. Since automatic properties were not one of those features, I do not cover them. You may notice that my chapter dedicated to the new C# 3.0 features is titled C# 3.0 Language Enhancements For LINQ. Just for your reader’s knowledge, the ordering is now specified to be stable. Initially it was unstable, and was later changed to be stable but I was told it would be specified to be unstable, but apparently at some point, the specification was changed to be stable. My book was updated but apparently I missed a spot.
Most of the advice given throughout the book is reasonable, although I take issue with one significant area. Joe recommends using the OfType operator instead of the Cast operator, because when a nongeneric collection contains the “wrong type of object,” OfType will silently skip it whereas Cast will throw an exception. I recommend using Cast for exactly the same reason! If I’ve got an object of an unexpected type in my collection, I want to know about it as soon as possible. Throwing an exception tells me what’s going on immediately, instead of hiding the problem. It’s usually the better behaviour, unless you explicitly have reason to believe that you will legitimately have objects of different types in the collection and you really want to only find objects of the specified type.
[Joe] Yes, I should have known better than to provide that advice (prefer OfType to Cast) without more explanation, more disclaimers, and more caveats. My preference would be to use Cast in development and debug built code for the exact reasons you mention, but to use OfType in production code. I would prefer my applications to handle unexpected data more gracefully in production than I would in development.
As well as “headline” pieces of advice which are advertised right up to the table of contents, there are many hints and tips along the way, most of which really do add value. I believe they’d actually add more value if they weren’t sometimes buried within reference-like material – but as we’ve already seen, my personal preference is for a more narrative style of book anyway.
The code examples are in “snippet” form (i.e. without
using directives, Main method declarations etc) but are complete aside from that. At the start of each chapter there’s a detailed list of which namespaces and references are involved, so there’s no guesswork required. In fact, I’d expect most of them to work in Snippy given an appropriate environment. Some examples are a bit longwinded – we only really need to see the 7 lines showing the list of presidents once or twice, not over and over again – but that’s a minor issue. Another niggle is Joe’s choices when it comes to a few bits of coding convention. There are various areas where we differ, but a few repeatedly bothered me: overuse (to my mind) of parentheses, “old-style” delegate creation (i.e. something.Click += new EventHandler(Foo) instead of just something.Click += Foo) and the explicit specification of type parameters on LINQ operators which don’t need them. Here’s one example which demonstrates the first and the last of these issues – as well as introducing an unnecessary cast:
XElement outOfPrintParticipant = xDocument
.Element(“BookParticipants”)
.Elements(“BookParticipant”)
.Where(e => ((string)((XElement)e).Element(“FirstName”)) == “Joe”
&& ((string)((XElement)e).Element(“LastName”)) == “Rattz”)
.Single<XElement>();
// This is what I’d have preferred
XElement outOfPrintParticipant = xDocument
.Element(“BookParticipants”)
.Elements(“BookParticipant”)
.Where(e => (string)e.Element(“FirstName”) == “Joe”
&& (string)e.Element(“LastName”) == “Rattz”)
.Single();
Check out the penultimate line of the original – a whopping 5 opening brackets and 6 closing ones. This issue looks even worse to me when it’s used to make
return and
throw look like method calls:
throw (new Exception(
String.Format(“Unexpected exception executing query [{0}].”, sqlQuery)));
// (Insert more code here) – same listing
return (result);
These just look odd and wrong. Of course they’re perfectly valid, but not pleasant to read in my view. On a more minor matter, Joe tends to close SQL connections, commands etc with an explicit
try/
finally block instead of the more idiomatic (to my mind)
using statement, but again that probably bothers me more than others.
The source code is all available on the web site, and it’s easy to find each listing. (The zip file is about 10 times larger than it needs to be because it contains all the bin/obj directories with all the compiled code in rather than just the source, but that’s a tiny niggle.)
Writing style
Joe’s writing style is very informal – or at least, while most of the text is in “normal” formal prose, there are plenty of informal pieces of writing there too. As readers of my book will know, I’m much the same – I try to keep things from getting too dry, despite that being the natural state for technical teaching. I have no idea how well I succeed for most readers, but Joe certainly manages. He occasionally takes it a little too far for my personal taste, usually around listing outputs. They’re often introduced as if Joe didn’t really know what the output would be, with a kind of “wow, it worked, who’d have thought?” comment afterwards. I suspect I’ve got some of this in my book too, but Joe lays it on a little too thickly for my liking. I don’t know whether it would be fairer to present a “medium-level” example of this rather than one which really grated, but this is the one (from page 257) made such an impression that I remembered it over 300 pages later:
This should output the language attribute. Let’s see:
language="English"
Groovy! I have never actually written the word groovy before. I had to let the spelling checker spell it for me.
Now, I really want to stress that that’s a “worst case” rather than the average case, and indeed many listings don’t have anything “cutesy” about them. I just wanted to give an example of the kind of thing that didn’t work for me.
[Joe] Let me see if I get this straight. So you are saying you got to learn something about LINQ and how to spell groovy, and it stuck for over 300 pages and you are upset? Man, you know how to spell groovy now, what’s the problem? 8-D Would it annoy you less if I told you that is a reference to Austin Powers? My book is riddled with references to movies and TV shows, and that one is for Austin Powers. Maybe you didn’t catch that, or maybe you don’t like Austin Powers, or maybe you just still don’t like it. One reader was irritated when I said “Dude, Sweet” because he didn’t recognize that as a reference to Dude, Where’s My Car. I have references to Office Space, Arrested Development, Bottle Rocket, Seinfeld, The Matrix, Wargames, Tron, etc. In fact, on page 455, I actually use the word “moo” instead of “moot” in reference to Friends. My copy editor actually corrected that for me, but once I explained it, she let me have it back. So if you see something goofy, like “groovy” just know it is a reference to something and begin your investigation in your spare time. And if you see an error, it is intentional to make sure you are paying attention. ;-) As you have already pointed out, technical writing can be dry. I made an effort to inject humor into the book in the form of references to pop culture, most specifically movies and television. Sometimes the reference is in a comment like “groovy”, and sometimes it’s in the sample data like a character’s name. Like any comedian, every joke or reference can’t be a hit with everyone. I will say though that I have heard more from those that recognized the references and appreciated them (which helps carry a reader through the lesser interesting parts) than I have from those that found them annoying.
What really did work was including hints and tips which explicitly said where Joe had received unexpected results with slightly different code. If anything is unexpected to the author, it may well be unexpected to readers too, so I really appreciated reading that sort of thing. (It would be wearing if Joe were stupid and expected all kinds of silly results, but that’s not the case at all.)
Conclusion
Pro LINQ is a good book. It has enough niggles to keep me from using superlatives about it, but it’s good nonetheless. It’s Joe’s first book (just like C# in Depth is the first one I can truly call “mine”) and I hope he writes more. Having read it from cover to cover, I think it’ll be more useful as a reference for individual methods (when MSDN doesn’t quite cut it) than to reread whole chapters, but that’s not a problem. My slight complaints above certainly don’t stop it from being a book I’m pleased to own.
[Joe] I’ll take it as a compliment that you think my book would be useful for those times that MSDN isn’t good enough!
This is the first LINQ book I’ve reviewed – I already have LINQ in Action, which is also on the list to review at some point. (I’ve read large chunks of it in soft copy, but I haven’t been through the finished hard copy yet.) It will be interesting to see how the two compare. Next up will probably be “Programming C# 3.0” by Jesse Liberty, however.
16 thoughts on “Book review: Pro LINQ – Language Integrated Query in C# 2008, by Joe Rattz”
The onclick handler got stripped by the weblog software, it seems.
(Hello, by the way, from an old friend from W2W. I’ve enjoyed reading your C# stuff for some time now.)
the link below should toggle the visibility of the comments.
It’s relatively simple stuff, but my CSS and JavaScript are not what
they might be – so let me know if it all goes pear-shaped
It seems to have gone pear-shaped. :)
On Safari (Mac), Opera (Mac), and IE8 (Windows), I was unabled to get the comments to be shown by clicking the “Show/hide comments” link.
On a related note, the comments _do_ show up in the RSS feed, but of course they are unformatted and so very difficult to distinguish from the main article. I’m a fan of summaries in RSS, at least in this sort of context where the article itself may be very long, and in this particular example using a summary would force readers to view the article as it was originally intended (i.e. without comments first, then going back and seeing the “director’s commentary” :) ).
Of course, I suppose that while the implementation is in fact pear-shaped, the RSS feed makes for a reasonable work-around. :)
By the way, just looking at the HTML source, it seems that the problem is as basic as the attached script simply being incomplete. It reads as follows:
function hideOrShowComments(link)
{
var divs = link.parentNode.parentNode.getElementsByTagName("div");
for (i=0; i
Note that it’s just stops. Probably there should have been a < where you have an angle-bracket. :)
Thanks for the review.
I really hope you do a review of CLR via C# 2ed (Jeffrey Richter) one day.
Peter
@peted: Yup, looks like it was stripping stuff. (Previously it was stripping input tags.) Oh, and it also changes double quotes into ampersand quot semi-colon. Grr.
It doesn’t help that of course the HTML I’m uploading works fine locally. It also doesn’t help that I’ve currently only got access to mobile broadband with a poor signal, and I’ve had guests round this evening… Oh, and whenever I post to the blog it spews out a cached copy for a while. Basically it’s a pain in the neck fixing problems like this :(
@Peter: Originally Joe had written “[Joe]” at the start of each of his comments. Keeping that in might help the RSS feed to be more useful… I’ll reinstate it now. And yes, I’ll get round to CLR via C# some time – I have it now. I didn’t realise it’s just the second edition of another title; I feel less guilty about not having read it before (as I’d read the first edition).
I’ve got another couple of Apress books on their way too, and Jesse Liberty’s “Programming C# 3.0”.
@Everyone: Bear with me while I try to get all this fixed. If I can’t sort it out, I’ll just make the comments show up the whole time, at least for now.
Jon
The show/hide comments link also doesn’t work on FF3. IE7 throws a javascript error and most of the page (everything after “Overture”) doesn’t render.
Ironically, I see that in my comment, the character entities have themselves not been quoted and so show up as the actual characters, not the XML entity code.
So where I wrote “there should have been a < where you have an angle-bracket", it should have actually said "there should have been a < where you have an angle-bracket". There was a similar alteration for the double-quotes, which I posted as " but which actually got displayed as ".
(I made an attempt to use an explicit character entity for the ampersand in the previous paragraph, but it remains to be seen whether that gets translated somehow too :) ).
As far as work-around goes until you can get the comment-hiding working right, you might consider placing all of the comments at the end of the post, with links to them via page-relative anchors. A little less elegant than in-line, but not terribly so and perhaps closer to your original intent than just having them shown all the time.
Okay, I’m giving up for the night. I’ve got close to getting it working by putting the script in an external file – but then I need to hook up the click event as well. I’ll have another go tomorrow. The roundtrip time for testing changes is just too painful at the moment.
Jon
The only thing that displays in MS Outlook 7007 RSS Feed reader is “Overture”. You have to takr the option to see the full article in a browser to read further
Mike
Really enjoyed that review Jon! I would certainly like to read more reviews written in that style.
I would also like to +1 Peter’s comment about reviewing CLR via C#, even though the book is now quite old.
@Mike: Not a lot I can do about that, I’m afraid. As we’ve seen with the comments debacle, I can’t control a lot with this blog :(
@Paul: Glad you enjoyed it. Looks like the “interleaved” comments aren’t too much of a problem. I don’t expect all authors will give full feedback, of course – but when they do (and if they don’t mind), I’ll post it in a similar way.
Next stop will almost certainly be “Programming C# 3.0” but I’ll try to do “CLR via C#” after that.
Jon
Looks like Google Reader only shows “Overture” too. I’ve really no idea why. I’ll get rid of all trace of the JavaScript etc and see if that helps.
“[Joe] My preference would be to use Cast in development and debug built code…but to use OfType in production code.”
Hiding errors in production is just as bad an idea as hiding them in development. If you expect all of the members of an enumeration to be of a particular type, and one or more members are actually of another type, that means reality is not lining up with your expectations, and there is probably a deeper bug somewhere. Hiding the problem doesn’t make it go away, it just makes it harder to find when you need to find it. Fail fast!
@David Nelson:
Well if you used Cast in development and testing, and the error wasn’t caught by the developer or QA, you missed your chance to fail fast. The next question becomes, what do you want the user experience to be? Sometimes users enter unanticipated input that programmers just don’t think to catch and bad things happen.
So if you have been editing in Visual Studio for a couple hours without saving (yeah, I know, who would do that?) and some error managed to slip through QA at Microsoft, you would prefer Visual Studio to just throw a fatal exception, shutdown the process, and lose all your work rather than just ignoring the problem?
I’m with David on this: throwing an exception is the right way to go. Throwing an exception is likely to make the user see an error message (hopefully a nice one, etc). That’s not great, but it’s *much* better than the system just proceeding as if nothing had gone wrong.
Note that throwing an exception doesn’t have to (and shouldn’t) mean shutting down the process without any chance to save things. However, I would far rather that than it *silently* losing data.
When something is seriously wrong (as it would have to be in this case), the whole operation should be aborted as quickly as possible rather than silently pretending to succeed. Using OfType here could hide the bug for months, leading to customer support calls which would quite possibly have no indications of problems in the logs, and be very hard to track down. An exception is brutal, but when the system is so badly hosed that you’ve got unexpected and incorrect data in it, proceeding as if nothing had happened is simply wrong IMO.
Jon
@Joe,
In that particular case, that’s what autosave is for :) There are two problems with the approach you are suggesting. First, hiding problems that seem innocuous can lead to further data corruption. For example, what if one of those instances in your enumeration, actually contained data that needed to be processed, but you ignored it because it was a different type? Now you have lost data, and no one even knows about it! Throwing an exception might also lose data (if the data being processed is not already stored persistently), but at least the user knows that a problem occurred and can take steps to correct it, outside of the context of your application if necessary.
Second, by hiding the problem where it occurred, you make it harder to determine whether there is actually a problem, and harder to track down the problem once someone figures out that a problem is actually occurring. Your assertion that once your code is in production “you missed your chance to fail fast” is incorrect. The point of failing fast is to make sure that the symptom occurs as close to the cause as possible, so that you can backtrack from the symptom to the cause as quickly and easily as possible. This is true whether the problem is occurring in development or in production. In fact it is even more important to fail fast in production, since getting the system back in proper working order as soon as possible is essential to customer relations (even if your customer is your boss). Having an application crash (with a friendly error message) may not be ideal, but if it helps correct the problem and get the system back in working order more quickly, it is worth it. | https://codeblog.jonskeet.uk/2008/09/21/book-review-pro-linq-language-integrated-query-in-c-2008-by-joe-rattz/?replytocom=10396 | CC-MAIN-2021-39 | refinedweb | 5,692 | 66.67 |
Hello, all.
I don't like to post anything on boards, but I am stumped here.
I have a program that will solicit a line of text from the user. It will then output the string later in the program (by passing a char * to a function).
The trouble comes in when main() ALSO calls a certain function that returns a type bool variable. When that function is called, the string does not output fully!
Please note that when I assign either 'true' or 'false' to the bool variable in main(), instead of getting the value from the return value of the type
bool function, the string outputs just fine.
What in the world could I possibly be missing?
For any interested, here is the code, with all comments that I thought would be pertinent. Note that if you comment the line:
use_num = use_number();
and uncomment the line:
use_num = true;
Then the program runs fine. How could this seemingly unrelated function call break the output of the string?
Code:// comparison.cpp // What changes the length of the string? #include <iostream> void get_a_string(char *); void print_a_string(char *, int i = 0); bool use_number(void); // This seems to be the "trouble causing" function, in that, // when it is called, the string pointed to by 'pt_line' // seems to decrease in length. int main(void) { using namespace std; char * pt_line = new char; // Get memory to put the string of text in. get_a_string(pt_line); // Solicit the string of text from the user, // and store it in the memory address pointed // to by 'pt_line'. bool use_num; //======================================================================================= // We can get a value for the variable 'use_num' two different ways. // // If we use the return value of the function 'use_number(void)' as the value for // 'use_num', then the string pointed to by 'pt_line' does not output correctly. Only // the first part of the line is outputted. // // If, however, we simply _assign_ a value to 'use_num', then the string IS outputted // correctly (its entire length is shown). // // So, uncomment out only ONE of the following lines of code, to make your choice. //======================================================================================= use_num = use_number(); // This way will cause the program to print out only // the first part of the string. //use_num = true; // This (other way) will cause the string to be // properly outputted. print_a_string(pt_line); return 0; } // Remember, the function prototype for this function is this: // // void print_a_string(char *, int i = 0); // // The idea is, that if only a char * is passed to this function, then the line of text // pointed to by the char * will be outputted only ONCE. // // However, if a second argument, of type int is passed to this function as well, and // it has a non-zero value, then the string pointed to by the type char * argument // be outputted a number of times equal to the number of times the function has been called by // main(). void print_a_string(char * pointer, int i) { using namespace std; static int times = 0; // the number of times this function // has been called. times++; if(i == 0) cout << pointer << endl; else { int j = 0; while(j < times) { cout << pointer << endl; j++; } } } void get_a_string(char * pointer) { using namespace std; cout << "Please enter a line of text:\n"; char ch; int i = 0; while((ch = getchar()) != '\n') { *(pointer + i) = ch; i++; } } bool use_number(void) { using namespace std; string usr_in; cout << "Do you want to use a number? [Y/n] "; getline(cin, usr_in); while((usr_in.size() != 1 && usr_in.size() != 0) || (usr_in != "y" && usr_in != "Y" && usr_in != "n" && usr_in != "N" && usr_in.size() != 0)) { cout << "\t## size of input == " << usr_in.size() << endl; cout << "Oh, c'mon now... Enter a y or an n...\n"; cout << "Do you want to use a number? [Y/n] "; getline(cin, usr_in); } if(usr_in == "y" || usr_in == "Y" || usr_in.size() == 0) return true; else if(usr_in == "n" || usr_in == "N") return false; else { cout << "Error in function use_number(), program is terminating...\n"; exit(EXIT_FAILURE); } } | http://cboard.cprogramming.com/cplusplus-programming/78345-string-not-fully-outputted-when-type-bool-function-called.html | CC-MAIN-2015-06 | refinedweb | 641 | 78.18 |
NAME
makepp_statements -- Various statements in a makefile
DESCRIPTION
A: autoload, B: build_cache, build_check, D: "define", E: export, G: global, I: ifdef, ifeq, ifmakeperl, ifndef, ifneq, ifnsys, ifntrue, ifperl, ifsys, iftrue, include, _include, L: load_makefile, M: make, makeperl, makesub, N: "no_implicit_load", P: perl, "perl_begin", prebuild, R: register_command_parser, register_input_suffix, register_parser, repository, runtime, S: signature, "sub", V: vpath.
Conditionals
Conditionals are special statements, which control what lines of the Makeppfile are actually seen. The simplest form (where
ifxxx stands for any of the conditional statements documented below) is:
ifxxx ... lines seen if the statement evaluates as true endif
or:
ifxxx ... lines seen if the statement evaluates as true else lines seen if the statement evaluates as false endif
There is also the possibility to do complex combinations like this:
ifxxx ... and ifxxx ... and ifxxx ... or ifxxx ... and ifxxx ... lines seen if the combined statements evaluate as true else ifxxx ... or ifxxx ... and ifxxx ... lines seen if the first combination evaluates as false and these combined statements evaluate as true else lines seen if the statements above evaluate as false endif
As is suggested by the indentation,
and has higher precedence than
or. In other words an
or elects between two groups of
and`s. There may be any number of
and ifxxx`s,
or ifxxx`s and
else ifxxx`s.
The
ifxxx conditional statements are unique in that they may occur in the middle of rule actions, as in the above example, without disrupting the rule.
- ifeq string1, string2
-
- ifneq string1, string2 two other acceptable syntaxes for the
ifeqand
ifneqstatements:
ifeq string1, string2 ifeq string1 string2
which are equivalent. Of course you can quote the strings as needed.
ifeqand its friends
ifneq,
ifdef,
ifndef,
ifperl,
ifmakeperl,
ifsysand
iftrueareoption instead of the
-goption. Furthermore, the program
stripis run on the resulting binary (in case you happened to link with some libraries that were compiled in debug mode).
Sometimes it is easier to use the
$(if)function or
$(perl)function function instead of a
ifeqstatement.
If you just want to see whether a symbol is blank or not, you only need to supply a single argument, like this:
ifneq $(EXE_SUFFIX) # what to do if $(EXE_SUFFIX) is not blank endif
- ifdef VARIABLE ...
-
- ifndef VARIABLE ...
These statements work analogously to the
ifeqand
ifneqstatements, except that they test whether any of the variables is defined or not any is (i.e. none is defined). A variable is defined if:
It was given a value with an assignment earlier in the makefile. See makepp_variables for details.
It was given a value as a Perl variable in a
perl_beginblock.
The variable is present in the environment.
The variable is present on the command line, e.g., to invoke your makefile, you typed
makepp CFLAGS=-O2
For example,
ifndef CFLAGS CFLAGS := -g endif
In this case,
CFLAGSis set to
-gonly if it wasn't already defined. Note that this statement could just as easily have been written using the
?=assignment, like this:
CFLAGS ?= -g
- ifperl perlcode
-
- ifmakeperl perlcode
These statements work analogously to the
ifeqand
ifneqstatements, except that the tests are in Perl. The first variant is plain Perl code, while the second variant first passes the statement through Make-style variable expansion.
VERSION := 3.0 # VERSION is automatically also a Perl variable: ifperl $VERSION <= 2 CPPFLAGS := -DNEW endif # quotes necessary for CFLAGS, because Perl sees only the value: ifmakeperl my $$x = '$(CFLAGS)'; $$x =~ /-g/ CFLAGS := -g -O2 endif
- ifsys wildcard ...
-
- ifnsys wildcard ...
Tests if the current system makepp is running on matches any of the wildcards or not any (i.e. none).
ifsys i[3-6]86 and ifsys Linux SunOS ... # An Intel platform with Linux or Solaris else ifnsys sparc power* ... # Nor Sparc or PowerPC endif
There are up to six different strings you can match against. The actual strings are not standardized. Three of them reflect what the Perl instance was built for (not necessarily the same as where it is running), and the others come from the system and all vary wildly in form. You can find all of what the current platform matches by typing the following command at the Shell:
perl -MConfig -e'print "$^O @Config{qw(archname myarchname)} "'; uname -mps
- iftrue expression
-
- ifntrue expression
Tests if the expression evaluates to some value other than zero or the empty string.
Other Multiline Statements
Conditionals may control a whole multiline statement, but they cannot be inside such a statement.
- define
-
- {export|global|override}* define
define VARIABLE [assignment-operator] variable value line 1 variable value line 2 endef
Defines $(VARIABLE)'s value to be all the lines between the
definestatement and the
endefstatement. See multiline variables. The keywords
exportand
globalmay not be given at the same time.
- perl_begin
This is the same as
perl, but using GNU make style statement syntax. This statement introduces a block of code which is interpreted verbatim by perl. It can be useful for defining functions, but you can do this more concisely with the
substatement. A block of Perl code in your makefile can be useful to perform actions that are easier in Perl than with makepp functions and rules.
The remainder of the line following the
perl_beginstatement is ignored. All text up until a line that begins at the left margin with
perl_end/) { # You could do this with: ifsysdifferentlyif perlcode
-
- makeperl perlcode
This is the same as
perl_begin, but using Perl-style braces. The first variant is plain Perl code, while the second variant first passes the statement through Make-style variable expansion. Note that the difficulty of parsing Perl's braces has lead to the following simple heuristic:
If a double opening brace is found on the same or next line, a double closing brace will terminate the block. It must be at the beginning of a line, but may be preceded by whitespace.
Else, if the closing brace is at the very end of the
perlline this is a one liner.
Otherwise the closing brace must be at the very beginning of a following line, i.e. no leading whitespace.
For an efficient way to call Perl scripts, see
run. Unlike the
$(perl)function, the return value of this block is ignored.
perl { print "passed this point in the makefile\n" } perl { print "and this one too\n"; } ifdef NOISY perl {{ print "as well as this one\n" }} endif
You can use the Perl debugger for your embedded code, by running makepp itself in the debugger, where ... are the arguments, if any, you normally pass:
perl -d -S mpp ...
It is hard to set breakpoints in Perl code that has not been loaded. You can work around this by putting this line into your embedded Perl, just before where you want to break:
$DB::single = 1;
Then you can type
cat the debugger's prompt, to continue till that point.
- sub
-
- makesub
This statement provides a way to define a Perl subroutine inside your makefile. The first variant is plain Perl code, while the second variant first passes the statement through Make-style variable expansion. The syntax is identical to that of the Perl sub statement, except that prototypes are meaningless.
For the three possibilities of putting the braces of the body, see the explanation at the
perlstatement. my $fh, $file or die "$file: $!\n"; local $/ = undef; # Slurp file in one read. <$fh>; } ifdef NEWSUB makesub f_VAR2 {{ $(VAR) * 2; }} endif makesub f_VAR1 { $(VAR) + 1 }
Now, with this function defined, you can write
X = $(file_contents filename) # equivalent to builtin $(&cat filename)
and the variable
$(X)will fetch the contents of the given file every time it gets expanded. Use
:=to do this exactly once, or
;=to do this at most once.
See makepp_extending for more details and examples.
Simple Statements
- autoload filename ...
Specifies one or more makefiles to load should an attempt to find a rule for a file in this directory otherwise fail. This is useful when the makefile has rules whose definitions depend (possibly indirectly) on a file in another directory that depends (possibly indirectly) on other files in this directory (built by rules that do not depend on the file in the other directory).
For example, your Makeppfile might look like this:
rules-to-build-files-that-otherdir/x-depends-on more_rules.makeppfile: otherdir/x action-to-build-more_rules.makeppfile autoload more_rules.makeppfile
Note that we cannot reliably replace
autoloadwith
includehere, because if something other than the rule for more_rules.makeppfile tries to build otherdir/x first, then more_rules.makeppfile will probably fail because otherdir/x won't exist yet, because there is already an attempt to build it underway when Makeppfile is implicitly loaded on its behalf.
WARNING: Be very careful about doing things in an autoloaded makefile that change the behavior of rules in the directory's other makefile(s), as this will cause that behavior to depend on whether or not some previously built target caused makefiles to be autoloaded.
- build_cache /path/to/build/cache
-
- [global] build_cache /path/to/build/cache
Specifies a path to a build cache. See makepp_build_cache for details. The build cache must already exist; see "How to manage a build cache" in makepp_build_cache for how to make it in the first place. A
build_cachestatement in a makefile overrides the
--build-cachecommand line option for rules in the makefile, but it may be overridden by the
:build_cacherule modifier on a per-rule basis.
The keyword
globalmay precede this statement with the same effect as the command line option, i.e. the build cache applies in every makefile. This should best be given in a RootMakeppfile to be certain it is seen early enough.
Specify
noneinstead of a path to a directory if you want to disable the build cache for all rules in this makefile.
- build_check build_check_method
-
- [global] build_check build_check_method
Specifies the default build check method for all rules in this makefile. See makepp_build_check for details. The
build_checkstatement overrides the
--build-check-methodcommand line option for all rules in the makefile, but may be overridden by the
:build_checkmodifier on a per-rule basis.
The keyword
globalmay precede this statement with the same effect as the command line option, i.e. the build check method applies in every makefile which does not specify its own. This should best be given in a RootMakeppfile to be certain it is seen early enough.
Specify
build_check defaultinstead of a name if you want to return to the default. With the keyword
globalthis means the
exact_matchmethod, else this reverts the current makefile to not having its own specific method.
- export VAR ...
-
- export assignment
export PATH := $(PWD):$(PATH)
Marks the given variables for export to subprocesses. See setting variables.
- global VAR ...
-
- global assignment
global MYPROJECT.INFO = info to be seen in all makefiles
Marks the given variables as global to all makefiles. See setting variables.
- include makefile
This inserts the contents of another makefile into the current makefile. It can be useful if you have boilerplate files with a number of rules or variables, and each directory only needs to make a few modifications. The
includestatement also used to be commonly used in traditional makes in conjunction with automatic include file scanners, but this is no longer necessary with makepp.
includef)
If you're working on a build that needs to work with both GNU make and makepp, sometimes it's convenient to have exactly identical makefiles but a different include file. For example, all of your makefiles may contain a line like this:
include $(TOPDIR)/standard_rules.mk
and you want standard_rules.mk to be different for GNU make and makepp. To facilitate this, the
includestatement first looks for a file with the suffix of .makepp before looking for the file you asked for. In this case, it would first look for a file called standard_rules.mk.makepp, and if that exists, it would load it instead of standard_rules.mk. This way, when you run the makefile with GNU make, it loads standard_rules.mk, but with makepp, it loads standard_rules.mk.makepp.
- _include makefile
A minor variant on
include, the
_includestatement includes the file if it exists but doesn't generate a fatal error if it does not. The
_includestatement used to be important for include file scanning with GNU make, but is seldom useful for makepp.
-looks for
Makeppfile,
makefile, or
Makefilein that directory.
Any variables you specify with the syntax
VAR=value(or
VAR="value1 value2") are passed to the loaded makefiles. They override any settings in those makefiles, just as if you had typed them on the command line.
Using
load_makefileis different from the command
include dir/makefile
in two ways. First,
load_makefiledoes
includestatement makepp_cookbook for info on building with multiple directories.
You cannot use
load_makefileto load several makefiles that apply to the same directory. Use
includefor several pieces of the makefile that apply to the same directory, and
load_makefilefor makefiles that apply to different directories.
- no_implicit_load
This statement turns off implicit loading of makefiles from a set of directories. This can be useful if you want to load makefiles automatically from most directories, but there are some directories which for various reasons you do not want makepp to attempt to update. (E.g., maybe the directory has a makefile for some other version of make which makepp does not understand.) For example,
no_implicit_load dir1 dir2/*
The above statement will turn off implicit loading for makefiles in
dir1and all of its subdirectories. It will also turn of implicit makefile loading for all subdirectories of
dir2(and all of their subdirectories), but not for
dir2itself..
- prebuild target
-
- make target
The arguments (which undergo Make-style variable expansion) are built immediately. This is useful when the list of targets that the Makefile can build depends on a generated file in another directory.
Currently, it will quietly fail to build targets if there is a dependency loop among the prebuilt targets and the Makefiles that must be loaded to build them, but that ought to be treated as an error.
- register_command_parser command_word parser
-
- register_parser command_word parser
When lexically analyzing rule actions, use parser for command_word, which may be the full path or just the basename. The basename is usually enough because the lexer tries both.
The parser may either be a classname with or without the leading
Mpp::CommandParser::. Such a class must have a member function called
factorythat returns an object of that class. If the classname contains colons, it must be quoted, so as not make this line look like a rule.
Or, because that class is usually not yet loaded, instead the factory function may reside in the Makefile namespace. These functions have a prefix of
p_which must not be given. This is the case of the builtin parsers.
The effect is comparable to the
:parserrule option. But for multi-command rules this is the better way.
- register_input_suffix command_word suffix ...
Add
suffix... to the list of input file suffixes recognized when an action beginning with
command_wordis parsed. The parser would normally pick this up via Mpp::CommandParser::input_filename_regexp, but it might instead ignore this entirely.
Parsers don't normally pick up all the arguments that aren't recognized as options, because they might be arguments of unrecognized options. (For example, i386v is not an input file of the command
gcc -b i386v foo.c.) Instead, they pick up only positional arguments that look like input filenames.
It is not unusual to use standard tools with site-specific nonstandard suffixes in order to signify that those files require special handling, such as different command options and/or postprocessing steps. For example:
register_input_suffix cpp .vpp %.v: %.vpp cpp $< > $@
- repository directory
-
- repository destdir=srcdir
Specifies one or more repository directories. The first repository specified has precedence over the others if the same file exists in multiple repositories and there is no build command for it. See makepp_repositories.
- runtime program,library
Store
libraryas a runtime dependency of
program. Both
programand
librarymay contain multiple words, in which case each word in
libraryis stored as a runtime dependency of each word in
program. When
programis added automatically as the executable dependency of a command by the
Mpp::CommandParserbase class, its runtime dependencies (if any) are added as well. In order for this to happen,
programmust be specified in the rule with a directory component, and without any shell meta characters. The purpose of this statement is to capture dependencies on libraries and other executables that are often loaded by the program, without having to specify them explicitly as dependencies of each rule that invokes
program, or to scan
programto determine those dependencies (which could be prohibitively difficult.)
Runtime dependencies are traversed recursively, so if
ahas a runtime dependency on
band
bhas a runtime dependency on
c, then any rule that uses
./awill have implicit dependencies on both
band
c(unless it uses a special
Mpp::CommandParserclass that overrides this behavior).
Note that missing dependencies won't necessarily be added after you add this statement to a makefile, unless the rule is re-scanned. Use the
--force-rescancommand line option to ensure that this happens.
- signature name
-
- [global] [override] signature name
signature md5 signature C signature c_compilation_md5 signature xml signature xml-space signature default
Sets the signature method for all rules following the
signaturestatement, for which no command parser chooses a method. You can override this for individual rules with the
:signaturerule modifier.
If you add the keyword
override, then this method will override even the the choice made by command parsers, but not those specified with the
:signaturerule modifier. If you add the keyword
global, the effect applies to all rules yet to be read, unless their makefile also has its own
signaturestatement. This is equivalent to the
--signaturecommand line option if given before any rule is read, e.g. in a RootMakeppfile to be certain it is seen early enough. Likewise the keywords
global overridefor this statement are equivalent to the
--override-signaturecommand line option.
Specify
signature defaultinstead of a name if you want to return to the default. With the keyword
globalthis means the simple modification time and file size method. Else this reverts the current makefile to not having its own specific method, using a global method if one was set.
For more information about signature methods, see makepp_signatures.
- vpath pattern directory ...
Fetch all files matching pattern from each given directory. Pattern may contain at most one
%wildcard. This uses the transparent repository mechanism (unlike gmake which rewrites filenames), but it does not recurse into subdirectories.
Commands
All builtin and self defined commands (see builtin commands and extending makepp), as well as external cleanly programmed Perl scripts can be used like statements. In this case they differ from rule actions in that they run in the same process as makepp and any input or output files are not noted as dependencies or as having been built by makepp.
As with all statements, they are considered as such, if they are indented less than the actions of the previous rule, if any.
This can be used for messages to be output while reading the makefile:
&echo The value of $$(VAR) is $(VAR)
Or instead of making many rules each depend on a directory creation rule, you can simply create it on the fly. Note that commands which create files are processed again every time the makefile is read., That's why we protect this one with a test -- though in this special case that would not be necessary, as this command would do no harm when repeated:
ifperl !-d 'include' &mkdir -p include # Create only if not present endif
AUTHOR
Gary Holt (holt-makepp@gholt.net) | https://metacpan.org/pod/makepp_statements | CC-MAIN-2016-44 | refinedweb | 3,249 | 53.71 |
I've been on the road for a couple of weeks, first at the Applied XML DevCon, then WinDev in Boston, then at the WS-I face-to-face last week in Miami. But now I'm back in the office with time to think and write...
At the end of October, I posted about OO and SO. Jon commented that it wasn't so much an issue of treating services like objects as of identifying information you want to operate on. I agree that you have to very careful to select identifiers whose meaning a service and a client can agree on and which will stable over time. (In fact, a lot of the work I did at MSDN was focused on solving this very problem.) But I do think that the object issue still exists...
As .NET Remoting demonstrates, you can use SOAP and WSDL to describe a rich distributed object system, including support for controlling object lifecycle from a client. But that doesn't mean that a Web service client can talk to you. In fact, in many cases, a remoting endpoint accessed via SOAP cannot be accessed using an ASMX client - a technology that shipped in the same release. Was the remoting stack doing anything wrong or illegal? Well, ignoring the cases where it refered to CLR namespaces as if they were well-known, the answer is no. What it did do, however, was make use of the legal extension points in XSD, WSDL and SOAP to include the information that a remoting client needed to achieve all kinds of rich interactions. Unfortunately, no other Web service kits knew about that special stuff, or what to do with it.
The most obvious problematic piece of this is instance lifecycle. So far, one of things that differentiates Web services from distributed object technologies is that, like traditional Web applications, Web services have been stateless (there is almost always state stored behind the Web service, but it isn't part of a service instance that's somehow bound to a specific client instance). It's interesting to note, then, the following paragraph from section 2 of the draft of WS-Addressing that was submitted to the W3C in August:
Endpoint references will be used instead of WSDL <service/> elements in the following cases:
This makes it sound like an endpoint reference is -- or can be -- an object reference, a la' DCOM, CORBA or Java RMI.
Of course, nothing requires that someone use an EPR that way. But if vendors provide tools that hide all this stuff (and surely that is their goal), someone might not even know. In that case, we'll end up in a world where developers have to look at Web services as a whole and then figure out which bits to use to get the loose architecture they want instead of the is-it-a-service-or-is-it-an-object-oh-who-cares thing they might accidentally end up with.
Lately, I’ve started to wonder how much of a risk there is in drawing too close a connection between Web services and objects. I heard someone say last week that if we, the industry, couldn’t get XML to object mappings working for all of XML Schema, then Web services would fail. I don’t believe that’s true. But I do worry that people who want to send XML messages will look at all the Web service infrastructure as it is presented in the tools and conclude that it’s really for distributed objects and that if you just want to do XML messaging, you should look elsewhere.
This concern has been amplified this week because I’ve been spending time looking at various standards for industry-specific messages. If two businesses want to integrate their systems using IFX, OFX, OAGIS, Accord, HL7, Parlay-X, etc, how they choose to transmit their messages including using Web services is really an implementation detail. Clearly Web services provide a range of benefits as an implementation technique, but Web services themselves are not the goal. It’s really about getting a message payload to the other party in a format that they can understand. That can be done in any number of ways.
If we focus all our energy on making messages and endpoints look like objects, we are likely to ignore the people who just want to make systems interoperate by sending XML from A to B. If people who want to do that look at Web services, think “Hmmm. That’s about objects. I want to send XML. I guess it isn’t for me.”, and move on to send raw XML over HTTP, message queues, email or whatever, then the WS stack will be irrelevant. Put another way, while you can use SOAP/WSDL/XSD/etc. to build a distributed object system, that’s a dangerous place to go because you are using technologies everyone associates with Web services and building something that is not, at least in my opinion, a Web service. And muddying these waters at this point is a really bad idea.
you have a great site! | http://www.pluralsight.com/community/blogs/tewald/archive/2004/11/11/3418.aspx | crawl-002 | refinedweb | 859 | 67.08 |
First post here, please be gentle...
I use ArcMap 10.3.1 and I'm having trouble with part of a Python script which will always be run from the Current mxd and active data frame.
I have to pass a list of layers to a function. I have given the script a list of all potential layers for this function (List 1). Some of those potential layers will actually be in my active data frame (always at least 1), along with other layers that are not compatible with the next function (List2). I want to only work with the potential layers that are actually present in my active data frame (List3)
I've tried the following:
import arcpy
mxd = arcpy.mapping.MapDocument("CURRENT")
df = mxd.ActiveDataFrame
List 1 = ["September", "October", "November", "December"]
List 2 = arcpy.mapping.ListLayers(df) # layers are named September and December
List 3 = list(set.(List1).intersection(List2))
The result is an empty list when it should be September, December.
I think the syntax roughly works, but the problem is that List2 returns something similar to <layer u'September'> so the two layers with identical names are not recognized as such.
(For context, I'll then be using List3 to print unique messages depending on the layer name returned... In case this helps)
Can anyone help me out?
Solved! Go to Solution.'] >>>
arcpy.mapping.ListLayers(df)
is returning a list of Layer objects. Something like this:
[<map layer u'September '>, <map layer u'December'>]
How about the following:
List2a = [] for l in List2: List2a.append(str(l.name))
I found this with a google search: Python | Intersection of two lists - GeeksforGeeks
and it suggests in method 2 something close to what you are trying:
def intersection(lst1, lst2): return list(set(lst1) & set(lst2)) lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9] lst2 = [9, 4, 5, 36, 47, 26, 10, 45, 87] print(intersection(lst1, lst2))
As Pavan suggests, you need to use the layer's name property in your comparison. Try:
import arcpy mxd = arcpy.mapping.MapDocument("CURRENT") df = mxd.ActiveDataFrame List1 = ["September", "October", "November", "December"] List2 = arcpy.mapping.ListLayers(df) # layers are named September and December List3 = [] for lyr in List2: if lyr.name in List1: List3.append(lyr.name)
EDIT: As Joshua Bixby shows in his code example, line 6 in my code should read as below. See: ListLayers.
# ListLayers (map_document_or_layer, {wildcard}, {data_frame}) List2 = arcpy.mapping.ListLayers(mxd, data_frame=df)
Ah, this looks promising. I didn't get to the layer name before but this looks like it could solve that. I will try it out first thing in the morning and report back.
Do you know if this method preserves the list order?
List3 should be in the List2 (or ListLayers) order. It is likely that it would match the Table of Contents order.
Unfortunately I'm getting an error on the line 'if lyr.name in List2:'
File "<string>" - AttributeError: 'str' object has no attribute 'name'
When I print List2 the entries are still "<layer u'September'>" or something like that so it's not matching List1 "September". My List3 result is a list of lots of duplicates of items in List2 with the "<layer u'September'>" formatting.
Did you try str(), like this:
List2a.append(str(l.name))
?'] >>>
This works for me, thanks so much. If anyone else reading this requires a string it requires the following change: On line 5 change [lyr.name for .... to [str(lyr.name) for .... | https://community.esri.com/t5/python-questions/intersecting-lists-problem/td-p/686932 | CC-MAIN-2022-21 | refinedweb | 582 | 65.62 |
Python is considered as one of the languages with the simplest syntax, along with the huge applicability. There are some common mistakes that developers make when working with the language. Here are some of the most common mistakes that Python developers make.
1. Error handling
Errors in Python have a very specific form, called a traceback. When you forget a colon at the end of a line, accidentally add one space too many when indenting under an if statement, or forget a parenthesis, you will encounter a syntax error. This means that Python couldn’t figure out how to read your program.
2.Incorrect Indentation
To indicate a block of code in Python, each line of the block has to be indicated by the same amount.
In Python, unlike other languages, indentation means a lot more than making code look clean. It is required for indicating what block of code a statement belongs to. Many characteristics depend on indentation. Some indentation errors in Python are harder to spot than others. For example, mixing spaces and tabs can be difficult to spot in a code. If that happens, whatever is seen in the editor may not be the thing that is seen by the Python when the tabs are being counted as a number of spaces. Jupyter notebook automatically replaces tabs with spaces, but it gives an error in most cases. To avoid this mistake, for the entire block, all spaces or all tabs must be used.
3.Misusing The __init__ Method
The init is a reserved method in python classes used as constructors. In object-oriented terminology, it is called as a constructor And it gets called when Python allocates memory to a new class object. This method is called when an object is created from a class and it allows the class to initialize the attributes of the class. The objective is to set the values of instance members for the class object. Trying to explicitly return a value from the init method implies that the user wants to deviate from its actual purpose.
4. Class variables use
In Python, class variables are internally handled as dictionaries and follow what is often referred to as Method Resolution Order or MRO. It defines the class search path used by Python to search for the right method to use in classes with multi-inheritance. This causes a Python problem unless it’s handled properly. Consider the following example:
class A:
def rk(self):
print(” In class A”)
class B(A):
def rk(self):
print(” In class B”)
r = B()
r.rk()
the methods that are invoked is from class B but not from class A, and this is due to Method Resolution Order(MRO). The order that follows in the above code is- class B – > class A. This causes a Python problem unless it’s handled properly.
5.Variable Binding
Python has late binding behavior. There is often confusion among Python developers regarding how Python binds its variables. What it means is that it binds its variables in closures or in the surrounding global scope and hence the values of variables used in closures are looked up at the time the inner function is called.
6. Python Standard Library Module Names
Python is rich with library modules which comes out of the box. A common mistake is using the same name for a module and a module in the Python standard library. This will lead to importing another library which will then try to import the module in the Python standard library and since there will be a module with the same name, the other package will import the defined module, in place of the Python standard library module.
7. LEGB Rule
Python scope resolution is based on what is known as the LEGB rule, which is shorthand for Local, Enclosing, Global, Built-in. Python uses a different approach for scoping variables than other programming languages. If a user makes an assignment to a variable in a scope, that variable is automatically considered by Python to be local to that scope and shadows any similarly named variable in an outer scope. This error is particularly common for developers when using lists.
Source: analyticsindiamag | https://learningactors.com/7-common-mistakes-python-developers-should-avoid/ | CC-MAIN-2021-43 | refinedweb | 702 | 61.06 |
Archives
ASP.NET MVC Validations using MVCContrib
In my earlier post, I have explained how to use MVCContrib Grid in ASP.net MVC application. In this post, I demonstrate how you can use ASP.net MVC client side validation using the MVCContrib Validation helpers. MVCContrib is a cool contrib project to ASP.net MVC that extends the functionalities of an ASP.net MVC application and it provides rich set of validation helpers and it also provides different validation groups. The MVCContrib project can download from.
The following are the steps to get Validation Helpers to work:
Step1
Add a reference to the MvcContrib assembly (download available from)
Step 2
Add namespace import for MvcContrib to your web.config file: | https://weblogs.asp.net/shijuvarghese/archive/2008/8 | CC-MAIN-2020-16 | refinedweb | 119 | 50.23 |
i am new to c++ and this is my second program for class...keep getting the error, warning: cannot pass objects of non-POD type 'struct std::string' through '...'; call will abort at runtime. can someone help me out please, here is my code:
Code:#include <stdio.h> #include <cstdlib> #include <iostream> using namespace std; // Input first and last name, grade, ande print out their name and lettergrade int main(int argc , char *argv) { string name, grade, A, B, C, D, F; cout << "Please insert your first and last name:\n"; cin >> name; cout << "Please insert your numeric grade:\n"; cin >> grade; name = name; grade = grade; if ("90" <= grade && grade <="100") A; if ("80" <= grade && grade <= "89") B; if ("70" <= grade && grade <= "79") C; if ("60" <= grade && grade <= "69") D; if (grade <= "59") F; printf("Hello name\n", name); printf("You Made grade\n", grade); } | http://cboard.cprogramming.com/cplusplus-programming/130321-help-please.html | CC-MAIN-2015-06 | refinedweb | 145 | 78.32 |
Name finder
Name finder was a tool to search for names and related items like road numbers in the OSM database. For a long time it was the main geocoding search engine powering the search box on the openstreetmap.org front page, as well as running at gazetteer.openstreetmap.org/namefinder
As of August 2010 (See announcement) Name finder is no longer in active service on the front page, or at gazetteer.openstreetmap.org.
The name finder is built by David.earl, but the code is (possibly) no longer actively developed or deployed anywhere
Contents
- 1 Searching for things with name finder
- 2 Example searches
- 3 Abbreviations, Accented characters etc.
- 4 Limitations
- 5 UK Postcodes
- 6 How it works
- 7 XML interface
- 8 Wiki template
- 9 What about the source code?
Searching for things with name finder
You can find anything in the OpenStreetMap database which has been given a name (e.g. a place, street, pub, school etc., e.g. Bakers Arms) or a reference (e.g. M11), or by its type or its plural (e.g. pub or churches).
You can give just one word or several (e.g. Hinton or Hinton Road), but they must appear in the same order in what you are looking for.
In particular, you can restrict your search to a, and possibly later with the 'is_in' relation).
You can also use a latitude,longitude either as the search target or the place qualifying the search, hence pubs near 52.2,0.19.
Furthermore, you can find the distance between two results by putting a colon between them. So Hinton Road, Fulbourn: Crossings Road, Chapel-en-le-Frith will look up both and tell you how far it is between.
If you search for cities near Islington, for example, you will only get cities back, not named items like City Road. Likewise, towns, suburbs, villages, hamlets, and places. These are recognised and constrained only to match the relevant items. This does not extend to their singulars or capitalized forms, so Towns near 52.0,0.0 unusually produces a different result from towns near 52.0,0.0.
I am considering a more analytic approach to search terms, so we don't rely on a syntax that isn't necessarily obvious. To that end it would be helpful if people could add to the namefinder's address format page so I get a good idea of what street addresses look like across the world.
Example searches
Fulbourn
- finds anything called or containing Fulbourn in its name:
village Fulbourn in Cambridgeshire, England, UK (which is about 7km east of city Cambridge, ditto) found. unclassified road Fulbourn Old Drift (east) about 2km south-east of middle of village Teversham in Cambridgeshire, England, UK (which is about 4km east of city Cambridge, ditto) found ...
places near 52.18,0.20
- where is this latitude,longitude?
requested location found about 1km west of middle of village Fulbourn in Cambridgeshire, England, UK (which is about 7km east of city Cambridge, ditto)
Hinton Road, Fulbourn
Hinton Rd near Fulbourn
- equivalent to above
Hinton Road near 52.18,0.20
hospitals near Fulbourn
- churches, pubs, supermarkets, stations, atms ...
pubs near 52.18,0.20
post offices near Cambridge, UK
- qualifying which one, using is_in
places near Fulbourn
villages near 52.18,0.20
suburbs near Cambridge
airports near Cambridge
airports
- not that helpful, you'll just get a random 30 of them
Victoria pub, Oxford
- as opposed to Victoria Station, Victoria Road etc, even though 'pub' doesn't appear in the name
Ipswich : 52.18,0.20
- how far is it between the two locations?
Abbreviations, Accented characters etc.
Words like Road and Rd, Avenue and Ave, East and E are equivalent. There is a list of what abbreviations are recognised. Please add to the list for other languages.
Letters like ß and ss are equivalent, æ and ae, å and aa etc (so Aarhus will find the Danish city of Århus and vice-versa).
Names with accented characters will be located even if you omit the accent (e.g. Sodertalje finds Södertälje). ø is recognised by o. Pretty much every diacritical 'latin-like' character in the Unicode character set is matched by its non-accented equivalent.
Also, if you search for the linguistically correct transliteration, you'll get a hit too. For example München, Munchen and Muenchen are all equivalent.
Punctuation and case are pretty much ignored, except that spaces divide words, so Field Fare Way will not match Fieldfare Way. However, certain suffixes which are commonly quoted either as part of a longer word or as separate words in languages like German and Dutch - for example Straße and Straat - are recognised to be special and will match whether or not concatenated and/or abbreviated. So for example, the following are all equivalent to the Name finder: Budapester Platz, Budapester Pl, Budapesterpl, Budapesterplatz. See the are abbreviations page for a list of recognised suffixes.
English possessives are also ignored (e.g. St Andrew or St Andrews will find St Andrew’s and vice-versa).
Where things on the map have been given in more than one language (using a 'name:languagecode' tag), the name finder will them in any of the languages.
Definite articles are omitted both from the index and in searches. For example if the surveyor has included only Barkers Arms a search for The Bakers Arms will match. Definite articles treated in this way are the, le, la, der, die, das, el, il.
Limitations
Because types of item and their names use the same index, places [or place] near Cambridge will yield street Abbey Place... as well as suburb Chesterton, and likewise churches near Waterbeach may yield street Church Lane... among the results. For this reason, at the moment place of worship is not included in the index, so searches for e.g. place of worship near Cambridge don't work because places near Cambridge would otherwise yield all the place of worship too if I put that term in the index. But place of worship is translated into church or mosque if there is enough information in the place_of_worship node to determine this; Hindu temples and the like will have to wait for now.
In general, an item has to have a name (including name:language), ref or airport code in order to be found. However, there are some exceptions to this to put certain anonymous items in the index, for example supermarkets and cinemas, so cinemas near Cambridge will give you them all, not just the named ones.
Highways are not indexed by type at all, so you can't currently say highways near Cambridge.
Types of things are only indexed in English. Kirchen nahe München and Hôpitaux pres Besançon sadly don't work. You have to say churches near München or hospitals near Besançon. In a future version I will attempt to support multiple languages here, if you will help with the translations. There is a translations page to gather these.
UK Postcodes
The Namefinder can also make limited use of UK postcodes. Searches for postcode alone are considered experimental: see below.
You can use either a UK postcode or postcode prefix (the bit before the space) in the following contexts:
- as a term to search for, e.g. CB21 5DZ or CB21
- as a qualifier instead of a place e.g. Hinton Road, CB21 5DZ or Hinton Road, CB21
- as a restriction on a qualifying place instead of a country or county, Hinton Road, Fulbourn, CB21 5DZ or Hinton Road, Fulbourn, CB21. Exceptionally the second comma can also be omitted, as in Adelaide Road, London NW11
A postcode prefix search merely searches for the name in the index. The postcode areas are on the map as nodes.
A full postcode used as a qualifier or restrictor is abbreviated to the partial postcode. This is then used either to limit the search term to results near to the postcode area centroid or limit instances of the place name given to those near the postcode area centroid respectively.
Full postcode searches work around the problem of copyright databases by translating the postcode into a street name (or possibly a building name or the like), place name and postcode prefix, and then using those to do the search, i.e. to geolocate the postcode, in the usual way as above. The translation is done by a Google search for the postcode and analyzing the results to see if a street address precedes it, and if so to extract the salient data from it. This does, of course, depend on some address in a postcode being indexed by Google. Not all are, but it is surprisingly common - lots of people publish addresses, estate agents in particular have a good spread of postcodes for example.
How it works
Outline
An index database is built initially from the planet export and then updated regularly from the incremental differences. This indexes names in a canonical form which makes them easy to look up by name and variations, and this is further divided into individual words for efficiency of matching. The index building process is in three stages: the first updates a database of the entire planet data; the second regenerates all the indexes which share the same canonical string (both old and new when this changes) and the third updates the separate index database.
The earth's surface is divided into regions (like big map tiles) about 111km square which are identified by a single number easily derivable from latitude and longitude, and the region number for the location of each indexed name is stored in the index. Because regions are roughly equal in size, their number reduces as one goes further away from the equator and they don't share common lines of longitude as edges.
When a search is constrained to a place (that is, after a comma or "near"), the place is looked up in the index by canonical name. If found, then its region number is determined. Then if it is "close" to the edge of a region, neighbouring region numbers adjoining those edges are also determined.
Where the 'place' is a lat,lon pair, a place is artificially constructed for it instead of looking it up.
The index doesn't store duplicate names. A duplicate name is defined as exactly the same canonical string withing a given distance of another (currently 3km). This means long roads will be found at intervals, but you only get one hit for a road in an area. If there really are two different roads identically named in the same locality, this is likely to lead to confusion elsewhere anyway, so it is suggested that they are disambiguated in the name (for example, 'Silver Street (central Wakefield)' and 'Silver Street (Newton Hill)').
Then names matching the part before the comma are looked up (or constructed from a lat,lon pair), constrained to those entries with the determined region numbers (which is what makes it efficient and scalable), and sorted by increasing distance from the located place, so the database gives us back a list of potential named items close to the place. However, there are some place names which are remarkably common around the world (Cambridge, London, ...) and each has to be searched, so this can be slow.
If no nearby place was specified, or we didn't find any nearby names near the place and the 'any' parameter is on (see below), then we lookup any instance of the name. This database query is constructed to provide exact matches first, then by decreasing importance of place (cities, towns, villages etc), then other non-place names, and limited to an arbitrary 30 results (or max results if the max parameter is give, see below).
In all cases, when a name is located, its context is established: that is we determine firstly the nearest place (if that is not the place we asked for - e.g. if the street located is in a nearby village not the village we asked for), and then the nearest town and/or city. This means we can give quite a lot of contextual information about what we found.
The distances between all these are computed by pythagoras theorem. This is adequate over what is by definition a local area, and distances are rounded to 1, 5 and 10km as they get further away. Sort order for results determined by distance also uses planar formula to speed the database queries. However, distance between different search results (using colon in the search), which can be very large, is the great circle distance.
In more detail
Tables used in searching
named: a named item from the OSM data, where name includes references, IATA codes, old names, foreign language names etc., and the info derived from the kind of item it is (church, pub, school, residential street...) Note that this is for all potentially searchable items, which includes duplicates both nearby and distant.
id: A unique identifier derived from OSM node, way and relation ids by multiplying by 4 and adding 1, 2 or 3 for node, way and relation respectively. In this way, all names can have a single space for numeric identifiers, but still refer back to the OSM ~ original if necessary. region: number as described in wiki lat: ) of the named item lon: ) name: the name of the item as displayed to the user (includes concatenation of bits of name mentioned above) canonical: a canonical form of the name (lower case, punctuation stripped etc) category: the key part of the main tag describing the object (e.g. highway) is_in: an is_in tag value, tidied up for human readability rank: 0 except for places, which are 10 through 60 for hamlet through to city info: a string derived from various tags describing the object (e.g. "church", "secondary road", "pub"), intended for readability,
placeindex: abstracts out some of the information in the Named table where entries are places. This is purely for efficiency - a smaller set to search when locating nearby places. Joined on id with Named when textual info then needed.
id ) region ) all as above lat ) lon ) rank )
word: a list of words derived from the canonical names of named items including alternate forms (like Strasse and Straße, Muenchen and Munchen and München), split forms (like Bahnhofweg vs. Bahnhof Weg) and the info string (so searches for "pubs" etc work - in English only though at present). Note that Word entries reference only one instance of a similarly named Named of the same type within any 3km radius, so nearby duplicates are not included in any search results, but distant ones aren't. Hence "M11, Harlow" gives a different result from "M11, Cambridge", but you don't get dozens of hits for either just because the road is split up into many ways, at bridges and the like, or for branches of estate roads.
id: as above ordinal: where in the sequence of words in the name the word appears (e.g. in "Kilburn High Road [A5]", kilburn=1, high=2, road=3, a5=1 - it starts again for alternates like the ref), used to determine exact matches in preference to approximate ones firstword: ) lastword: ) bools indicating that condition, ditto region: as above. Not vital here, but allows searches to home in on a region here rather than the database engine having to join to named first, though in practice MySQL only uses one index at a time
Search procedure
Searching firstly looks up any place qualifier if given (including an artificial place derived from lat,lon if that's given), then culls the result according to is_in for on any third qualifier given ("Kilburn High Road, London, UK), and then looks up the first part of the search by joining Word with itself on id as many times as there are words in the user's *canonicalised* search term and also with Named, using the region and neighbours of the located place(s), ordered by distance from it, or if no qualifying place then by exact match and then by approx match (Kilburn High Road only then Kilburn Road would match).
After that it gets the neighbouring settlements to provide context, hence Kilburn High Road is near Kilburn (presumably) even though the search was for London.
Tables for update management
node: stores position info (only) for all nodes
id, lat, lon
relation_node
relation_relation
relation_way
way_node
All of those just have two columns, relating one id to others so a search on Way_node for example by way_id will return all nodes in that way, and conversely a search on node_id will return all ways the node is a part of. Way_node contains ids for all ways, and the Relation_Xs for all relations.
canonical: just a list of canonical strings affected by an update and the containing region number.
changedid: a list of the ids of anonymous but interesting items changed during in an update. There are relatively few of these - most pubs do have names, for example.
Update procedure
Currently, a cron job runs updates daily.
Updates are in two phases.
import phase: read XML file (planet, or planet difference file); for each affected object find related affected objects (ways of nodes etc using way_node table etc) and for all names found by doing this record in canonical table (which is emptied at start of update).
Where an object is modified, record both the old and new canonical names. Also edit the Named, Node and relationship tables to reflect the new state, applying deletions, modifications and additions. The position assigned to a Way is that of the middle node, except for known areas it is the centre of the bounding box, and for a relation is one of the constituent nodes or ways.
More than one difference file can be imported, one after the other, and then the update phase applied once for all of them.
update phase: for each distinct Canonical/Region pair found in the import phase, find all Nameds with that pair. Clear out the word index for all those ids just found. For that list then take the first (or in the case of nodes vs ways, the way) and eliminate any others sharing that same pair within the 3km radius. Repeat until all nearby duplicates eliminated.
Create alternate forms for words in the canonical and insert them in the word index - that is, only for the remaining non-nearby-duplicates. In this way, if one way named (say) Kilburn High Road is deleted in an update, another remaining nearby would take its place so it doesn't disappear from the index, even though that Way was not affected by the update, or if a new part of Kilburn High Road is added, the whole of the nearby Kilburn High Road entries are re-evaluated to see which is the best to choose.
(Note that by using region like this, items either side of a region boundary will not be compared for similarity. Region is not essential in theory and could remove this minor boundary case, but at the expense of considering massively more similar names worldwide. You might not think this was much of a problem, but nearly every US settlement has a 1st street and a Main street so the problem expands from a few dozen comparisons in the neighbour culls to many hundreds and becomes prohibitively expensive.)
Anonymous nodes are directly attributable to ids so their 'info' detail can simply be added or removed from the word index directly.
Initial priming is simply an update from an entire planet file consisting purely of additions, though for efficiency Word and other deletions can be turned off, as these are remarkably slow and unnecessary when the Word table is known to be empty.
XML interfaceYou can also get the results back in an XML file for further processing or to implement the search on another site or in a different language. The url for this is<urlencodedstring>where the urlencoded string is what you would otherwise put in the search box (including commas and colons, as above). You can also optionally give parameters 'max' and 'any', as in<urlencodedstring>&max=20&any=1where max gives the maximum number of results to be returned and 'any' (which can have any value) indicates that if the search finds nothing near the place specified in the search, then it will proceed to search worldwide. Previously (before September 2008) this was always the case, but the default is now not to do this (for performance reasons). It is always an error if any qualifying place is not found at all, and it is still the case that the search is relaxed to look for any place of the given name if any qualifying is_in is not satisifed.
Though the whole result is provided in structured form, most of it can be ignored for simple presentation: just iterate the top-level named items extracting description, and in the case of distance searches, combine the referenced named elements by id and the distance between them. To locate on the map, also extract the lat and lon from the top level named elements.
In the event of an error, only the top level osmsearchbyname element is returned, which will include an error attribute, and as much other context as is available, as in
<searchresults date='2007-05-08 12:56:33' error='updating index, back soon'/>
The XML is as follows:
<?xml version="1.0" encoding="UTF-8" ?> <searchresults date='2007-05-08 12:56:33' <!-- date of search --> sourcedate='2007-05-02' <!-- date of index data (planet file) --> find='Newmarket Road, Cambridge, England' <!-- the original search string requested --> distancesearch='no' <!-- or yes; says whether to expect <distance> items in response to the colon in the find string --> findname='Newmarket Road' <!-- the name part of the string (before the first comma) --> findplace='Cambridge' <!-- the place part of find, after the first comma, possibly omitted --> findisin='England' <!-- the is_in part of the search string, after the second comma, possibly omitted --> foundnearplace='yes' <!-- or no; if no, says that though the place was found, the name was not found in or near it, but somewhere else; <place> below will then be absent in all cases --> <!-- in the case of a distancesearch, these will be findname1 and findname2 etc, and foundnearplace1,foundnearplace2 --> > <named ...>...</named> <named ...>...</named> ... <distance ...>...</distance> <distance ...>...</distance> ... </searchresults>
where <named> is a result, also used recursively to describe the context, as follows:
<named type='way' <!-- 'node', 'way' or 'relation' --> id='123456' <!-- the osm id from which the item was obtained --> lat='52.123456' <!-- latitude of the named item. Note: for segments this is the midpoint of the segment and for ways is the midpoint of a segment selected from the middle of the list of segemnts for the way --> lon='0.123456' <!-- longitude, ditto --> name='Newmarket Road [A1304]' <!-- the name of the item. Note that this is an amalgam of name, ref, name:lang and possibly others --> category='highway' <!-- the principal type key --> info='primary road' <!-- a sanitised readable version of the principal tag key/value pair --> rank='0' <!-- 0 except for places, which are numerically ranked by importance --> is_in='Cambridgeshire, England, UK' <!-- a tidied up equivalent of the item's is_in tag value, generally only applied to places --> region='52231' <!-- a region number (used internally for matching) --> distance='1.234' <!-- distance in km to the parent named --> approxdistance='0' <!-- as above, rounded to 1, 5 or 10km depending on distance. 0 means < 1km --> direction='188' <!-- the direction, in degrees anticlockwise from East, of the target _to_ named so 188 is nearly west. However, you'll probably want to express it in terms of direction from named to the target, so you'll probably want to reverse it --> zoom='16' <!-- a suggested zoom level (for top-level nameds) when constructing a map url --> > <description> Street Newmarket Road less than 1km from middle of suburb Barnwell in Cambridge, Cambridgeshire, England, UK (which is about 3km from city Cambridge in Cambridgeshire, England, UK) found <!-- text describing the match in context, only in the outermost named items --> </description> <place> <!-- the target place, if any. Note that this will have its own context of nearestplaces as well, which are often different. Also place may differ from result to result as named items are found in different places with the same name --> <named ...>...</named> </place> <nearestplaces> <!-- the nearest town and/or city to the parent. Note that the distance (and approxdistance) tags in the subordinate nameds says how far it is back to the parent. Note that these places may be nearer to the target name than the target place <named ...>...</named> <named ...>...</named> </nearestplaces> </named>
and <distance> is (if requested using a colon in the search) the distance between two of the top-level nameds in the xml, identified by their ids:
<distance fromtype='node' <!-- the type of the item at one end of the great circle: you need to know this because ids are only unique within type --> from='123456' <!-- its id --> totype='node' to='345678' <!-- the id of the named item at the other end --> > 227.3 <!-- the great circle distance in km between from and to --> </distance>
Wiki template
For linking to a resulting maps from within this wiki there is a now a Template:NameFinder.
What about the source code?
This is now checked in to svn at in the namefinder directory.
This is the currently running version with incremental updates (after June 7, 2008, and including performance changes from September 1, 2008)
It is written in PHP 5 and uses MySQL 5. | http://wiki.openstreetmap.org/wiki/Namefinder | CC-MAIN-2015-11 | refinedweb | 4,276 | 67.79 |
> > Installed 0.4.0 and compile multipathd with DEBUG=3. > In multipath/Makefile > > endif > > EXEC = multipath > DEBUG = 3 > > all: $(BUILD) > If you want more verbose log from the daemon (in daemon.log), compile with LOGLEVEL=7. DEBUG=3 is for multipath only, not for the daemon. > The following is displayed after the daemon is restarted though: > > Device Mapper prerequisites not met > Quite explicit. You need linux kernel 2.6.10-rc?-udm2 to run the tools. > Setup DEBUG=3 in multipath/Makefile. > > > Few additional things: > > The output of multipath -v2 is now: > > Device mapper prerequisites not met. > ditto > > I have hotplug-2004-09-23 > Device-mapper-1.00.19 > Multipath-tools-0.4.0 > Kernel 2.6.5-7.111.5 (Could this be the problem?) > It is. Either stick with the tools provided by Suse or upgrade the kernel and use the vanilla tools. regards, -- christophe varoqui <christophe varoqui free fr> | http://www.redhat.com/archives/dm-devel/2004-December/msg00052.html | CC-MAIN-2014-52 | refinedweb | 152 | 62.54 |
Summary: Learn how to use Windows PowerShell to get software installation locations, and to uninstall software from remote computers.
Hey, Scripting Guy! We have a dumb application that we have to use at work. The company has released a new version of this application, and I am trying to write a Windows PowerShell script to uninstall the old application—the problem is that I need to find the application first. I tried looking in the registry, but the install key is empty…figures. Like I said, this is a really dumb application. I read the guest blog written by Marc Carter about problems using the Win32_Product WMI class, but it looks like I am going to be stuck using this anyway. The problem is that it is really slow. Is there any way to speed this thing up? I have to query over a thousand computers, and in our testing, this query takes nearly five minutes to complete—that would be three and a half days for only one query.
—BT
Hello BT,
Microsoft Scripting Guy, Ed Wilson, is here. The Scripting Wife and I were in Texas for the Corpus Christi Windows PowerShell User Group meeting when Marc Carter told me about the problem with the MSI installer reconfiguring applications when the Win32_Product WMI class is queried. I immediately encouraged him to write a guest blog about this issue.
BT, there is a way to use the Win32_Product WMI class in a more efficient manner. It relies on using the [WMI] type accelerator, instead of doing a generic WMI query. The problem is that the [WMI] type accelerator returns a specific instance of a WMI class. To connect to a specific instance, I must use the Key property of a WMI class.
I can use the Get-WMIKey function from my HSGWMImoduleV6 module. In the following code, I first import my HSGWMImoduleV6 module, and then I use the Get-WMIKey function to return the key to the Win32_Product WMI class. The commands and the output from the commands are shown here.
PS C:\> Import-Module hsg*6
PS C:\> Get-WmiKey win32_product
IdentifyingNumber
Name
Version
The Key property for Win32_Product is a composite key comprised of IdentifyingNumber, Name, and Version. The easy way to get this information is to use the Get-WmiObject cmdlet to query for the information. I only need to do this once, and I will have the three pieces of information. A table is a nice way to display the information. In the code shown here, I use the Get-WmiObject cmdlet (gwmi is an alias) to return product information, and then I pipe the management objects to the Format-Table (ft is an alias) cmdlet for display.
gwmi win32_product | ft name, version, ident*
In the image that follows, I import the HSGWMIModuleV6 module, use the Get-WMIKey function to retrieve the Key property of the Win32_Product WMI class. I then use the Get-WmiObject cmdlet (gwmi is an alias) to query the Win32_Product WMI class, and I output the management objects to a table via the Format-Table (ft is alias) cmdlet. The following image displays the commands and the output from the commands.
BT, you may ask, “What about Marc Carter’s warning about using the Win32_Product WMI class? “ Well as seen in the results from querying the event log, it is a concern. Shortly after querying the Win32_Product WMI class, I used the Get-EventLog cmdlet to query the application log for MSIInstaller events. The following image shows massive product reconfiguring going on.. The command and associated output are shown here.
PS C:\> gwmi win32_product -filter “Name LIKE ‘%Silverlight%'”
IdentifyingNumber : {89F4137D-6C26-4A84-BDB8-2E5A4BB71E00}
Name : Microsoft Silverlight
Vendor : Microsoft Corporation
Version : 4.0.60831.0
Caption : Microsoft Silverlight
When I have the three pieces of information (the IdentifyingNumber, the Name, and the Version), it is time to create the key. This is where quite a bit of experimentation could be required. I have to use the back tick (grave) character to escape inside quotation marks. I have to escape the quotation mark and the opening curly bracket for the IdentifyingNumber property. I also have to escape the closing curly bracket and the closing quotation mark. I then have to escape the quotation marks that surround Microsoft Silverlight, in addition to the quotation marks for the Version property. There are also two quotation marks at the end of the ClassKey.
Here is the key I derived for Microsoft Silverlight on my computer. (This is a single line command. A space between Microsoft and Silverlight exists, but other than that, there are no spaces).
$classKey=”IdentifyingNumber=`”`{89F4137D-6C26-4A84-BDB8-2E5A4BB71E00`}`”,Name=`”Microsoft Silverlight`”,version=`”4.0.60831.0`””
The reason for all the escaping in the ClassKey, is that WMI expects the quotation marks and the curly brackets in the key itself. To see what WMI expects to receive via the command, I use the Windows Management Instrumentation Tester (WbemTest) command, and I view the instances of the class. The following image illustrates the instances of Win32_Product on my computer.
When I have the ClassKey, I can use the [WMI] type accelerator to connect to the specific software package (Microsoft Silverlight in this example). In fact, using the [WMI] type accelerator is very easy. Here is the command. (The command is [WMI], the class name, and the key).
[wmi]”Win32_Product.$classkey”
I can also include the WMI namespace (really important if the class resides in a namespace other than the default root\cimv2). In the command that follows, notice that there is a backslash that precedes the word root. One other thing to notice is that a colon separates the WMI namespace and the WMI class name.
[wmi]”\root\cimv2:Win32_Product.$classkey”
If I need to connect to a WMI class on a remote computer, I use a double backslash and the name of the computer, then the WMI namespace, the WMI class, and the WMI ClassKey. The command that follows illustrates this.
[wmi]\\remotehost\root\cimv2:Win32_Product.$classkey
In the image that follows, I illustrate the different ways of querying WMI for Microsoft Silverlight software. I then compare the speed of using the Get-WmiObject cmdlet against the speed of using the [WMI] type accelerator. As shown in the following image, the Get-WmiObject cmdlet, using the filter to find Microsoft Silverlight, takes over five seconds on my laptop. Using the [WMI] type accelerator takes less than one-half of a second. This is more than 10 times faster.
By the way, there was not much difference between using the filter to look for Microsoft Silverlight or using the Where-Object. In the following output, I use the Measure-Object cmdlet to determine the performance of using the Where-Object (the ? is an alias for Where-Object).
If you suspect that the problem with the filter is that I used the like operator as opposed to the equality operator, that is not the case. Here are the results from using the equality operator.
When using the [WMI] type accelerator, a complete instance of the WMI class instance returns. The properties and their associated values are shown in the following image. Notice two properties: the __Path (that is, double underscore Path) property is the key to the WMI class instance. The InstallLocation property points to the location where the software installs.
BT, you did not ask, but there is an Uninstall method available from the Win32_Product WMI class. It appears only on instances of the class. Therefore, it is possible to uninstall software by using the command that is shown here. (If I want to uninstall from a large collection of servers, I use the foreach statement ($servers is an array of server names).
foreach($server in $servers)
{ ([wmi]”\\$server\root\cimv2:Win32_Product.$classKey”).uninstall() }
BT, that is all there is to using the Win32_Product WMI class to detect or to uninstall software. Join me tomorrow when I will have a guest blog written by Raymond Mitchel as he talks about Windows PowerShell and SharePoint. by far the best solution I have found, it's very quick, and doesn't trigger a repair.
blogs.technet.com/…/how-to-not-use-win32-product-in-group-policy-filtering.aspx
Create a custom MOF
Per one of the previous articles on this blog, usage of Win32_Product WMI class is not a right choice. I advised many people to stop using that class because of performance reasons and it's unnecessary attempt to repair of applications when a simple query is triggered to get list of softwares. Marc Carter explained more about it in blogs.technet.com/…/use-powershell-to-quickly-find-installed-software.aspx.
If you would like to use other available approaches to uninstall a product, see techibee.com/…/1400
Hi Ed,
I read through your very interesting blog article.
Even on my slow machine it is signifficantly faster to use the [wmi] type accelerator but the time it took to get at the $classKey using:
gwmi win32_product -filter "Name LIKE '%Silverlight%'"
compensates for that, I' afraid …
Constructing the concrete $classkey with all those escape sequences is no fun either!
So I'd like to stay with the slower but much more intuitive approach:
measure-command {gwmi win32_product | ? {$_.name -match 'silverlight'}}
Of course having to repeat this command, maybe including a lot of different servers, it may well be worth to go for the faster version.
There maybe one mistake in the article, After the statement:
"If you suspect that the problem with the filter is that I used the like operator as opposed to the equality operator, that is not the case. Here are the results from using the equality operator."
you are repeating the exactly same command and output as before. This looks like a copy&paste bug 🙂 …
Klaus.
Nice post! I know that every problem has the some solutions so we need to search in a suitable place or person to know the actual concept that how it can be done. Actually ,i am a new in this industry but i will search the solution and then write it. I hope to you to present this type of post in the future also.
<a href="ecommercesoftwarereviewss.com/">ecommerce reviews</a>
Thanks for sharing the information.
Any ideas on how to use this on Office 2010 uninstall with powershell 3.0…
I have used the following code and nothing works:
Step 1
gwmi win32_product | ft name, version, ident*
Step 2
gwmi win32_product -filter "Name LIKE '%Office%'"
Step 3
$classKey="IdentifyingNumber=`"`{90150000-0011-0000-0000-0000000FF1CE`}`",Name=`"Microsoft Office Professional Plus 2013`",version=`"15.0.4420.1017`""
Step 4
[wmi]"Win32_Product.$classkey"
Step 5
[wmi]"rootcimv2:Win32_Product.$classkey"
([wmi]"rootcimv2:Win32_Product.$classKey").uninstall()
Unfortunetly this does not uninstall Office 2013 any ideas what I could be doing wrong?
Thanks,
U cant uninstall office 2010 using msi or wmi command(include powershell)
u must use original installer setup.exe + uninstallation args
Hi scripting guy !
I know i’m a bit late, but what do you think about this short command :
([wmi]((Get-WmiObject -Class Win32_Product | Where-Object -FilterScript {$_.Name -like "*Silverlight*"}).__PATH)).uninstall()
Joris, | https://blogs.technet.microsoft.com/heyscriptingguy/2011/12/14/use-powershell-to-find-and-uninstall-software/ | CC-MAIN-2017-26 | refinedweb | 1,862 | 62.88 |
This section describes abstractions for creating new data types representing records.
A record is a compound data structure with a fixed number of components, called fields. Each record has an associated type specified by a record-type descriptor, which is an object that specifies the fields of the record and various other properties that all records of that type share. Record objects are created by a record constructor, a procedure that creates a fresh record object and initializes its fields to values. Records of different types can be distinguished from each other and from other types of objects by record predicates. A record predicate returns #t when passed a record of the type specified by the record-type descriptor and #f otherwise. An accessor extracts from a record the component associated with a field, and a mutator changes the component to a different value.
Record types can be extended via single inheritance, allowing record types to model hierarchies that occur in applications like algebraic data types as well as single-inheritance class systems. If a record type t extends another record type p, each record of type t is also a record of type p, and the predicate, accessors, and mutators applicable to a record of type p are also applicable to a record of type t. The extension relationship is transitive in the sense that a type extends its parent’s parent, if any, and so on. A record type that does not extend another record type is called a base record type.
A record type can be sealed to prevent it from being extended. Moreover, a record type can be nongenerative, i.e., it is globally identified by a “uid”, and new, compatible definitions of a nongenerative record type with the same uid as a previous always yield the same record type.
The record mechanism spans three libraries:
the (rnrs records syntactic (6)) library, a syntactic layer for defining a record type and associated constructor, predicate, accessor, and mutators,
the (rnrs records procedural (6)) library, a procedural layer for creating and manipulating record types and creating constructors, predicates, accessors, and mutators;
the (rnrs records inspection (6)) library, a set of inspection procedures.
The inspection procedures allow programs to obtain from a record instance a descriptor for the type and from there obtain access to the fields of the record instance. This facility allows the creation of portable printers and inspectors. A program may prevent access to a record’s type—and thereby protect the information stored in the record from the inspection mechanism—by declaring the type opaque. Thus, opacity as presented here can be used to enforce abstraction barriers.
Any of the standard types mentioned in this report may or may not be implemented as an opaque record type. Thus, it may be possible to use inspection on objects of the standard types.
The procedural layer is particularly useful for writing interpreters that construct host-compatible record types. It may also serve as a target for expansion of the syntactic layers. The record operations provided through the procedural layer may, however, be less efficient than the operations provided through the syntactic layer, which is designed to allow expand-time determination of record-instance sizes and field offsets. Therefore, alternative implementations of syntactic record-type definition should, when possible, expand into the syntactic layer rather than the procedural layer.
The syntactic layer is used more commonly and therefore described first. This chapter uses the rtd and constructor-descriptor parameter names for arguments that must be record-type descriptors and constructor descriptors, respectively (see section 6.3).
The fields of a record type are designated mutable or immutable. Correspondingly, a record type with no mutable field is called immutable, and all records of that type are immutable objects. All other record types are mutable, and so are their records.
Each call to a record constructor returns a new record with a fresh location (see report section on “Storage model”). Consequently, for two records obj1 and obj2, the return value of (eqv? obj1 obj2), as well as the return value of (eq? obj1 obj2), adheres to the following criteria (see report section on “Equivalence predicates”):
If obj1 and obj2 have different record types (i.e., their record-type descriptors are not eqv?), eqv? returns #f.
If obj1 and obj2 are both records of the same record type, and are the results of two separate calls to record constructors, then eqv? returns #f.
If obj1 and obj2 are both the result of a single call to a record constructor, then eqv? returns #t.
If obj1 and obj2 are both records of the same record type, where applying an accessor to both yields results for which eqv? returns #f, then eqv? returns #f.
The syntactic layer is provided by the (rnrs records syntactic (6))library. Some details of the specification are explained in terms of the specification of the procedural layer below.
The record-type-defining form define-record-type is a definition and can appear anywhere any other <definition> can appear.
A define-record-type form defines a record type along with associated constructor descriptor and constructor, predicate, field accessors, and field mutators. The define-record-type form expands into a set of definitions in the environment where define-record-type appears; hence, it is possible to refer to the bindings (except for that of the record type itself) recursively.
The <name spec> specifies the names of the record type, constructor, and predicate. It must take one of the following forms:
(<record name> <constructor name> <predicate name>)(<record name> <constructor name> <predicate name>)
<Record name>, <constructor name>, and <predicate name> must all be identifiers.
<Record name>, taken as a symbol, becomes the name of the record type. (See the description of make-record-type-descriptor below.) Additionally, it is bound by this definition to an expand-time or run-time representation of the record type and can be used as parent name in syntactic record-type definitions that extend this definition. It can also be used as a handle to gain access to the underlying record-type descriptor and constructor descriptor (see record-type-descriptor and record-constructor-descriptor below).
<Constructor name> is defined by this definition to be a constructor for the defined record type, with a protocol specified by the protocol clause, or, in its absence, using a default protocol. For details, see the description of the protocol clause below.
<Predicate name> is defined by this definition to a predicate for the defined record type.
The second form of <name spec> is an abbreviation for the first form, where the name of the constructor is generated by prefixing the record name with make-, and the predicate name is generated by adding a question mark (?) to the end of the record name. For example, if the record name is frob, the name of the constructor is make-frob, and the predicate name is frob?.
Each <record clause> must take one of the following forms; it is a syntax violation if multiple <record clause>s of the same kind appear in a define-record-type form.
(fields <field spec>*)
Each <field spec> has one of the following forms
(immutable <field name> <accessor name>)(immutable <field name> <accessor name>)
<Field name>, <accessor name>, and <mutator name> must all be identifiers. The first form declares an immutable field called <field name>, with the corresponding accessor named <accessor name>. The second form declares a mutable field called <field name>, with the corresponding accessor named <accessor name>, and with the corresponding mutator named <mutator name>.
If <field spec> takes the third or fourth form, the accessor name is generated by appending the record name and field name with a hyphen separator, and the mutator name (for a mutable field) is generated by adding a -set! suffix to the accessor name. For example, if the record name is frob and the field name is widget, the accessor name is frob-widget and the mutator name is frob-widget-set!.
If <field spec> is just a <field name> form, it is an abbreviation for (immutable <field name>).
The <field name>s become, as symbols, the names of the fields in the record-type descriptor being created, in the same order.
The fields clause may be absent; this is equivalent to an empty fields clause.
(parent <parent name>)
Specifies that the record type is to have parent type <parent name>, where <parent name> is the <record name> of a record type previously defined using define-record-type. The record-type definition associated with <parent name> must not be sealed. If no parent clause and no parent-rtd (see below) clause is present, the record type is a base type.
(protocol <expression>)
<Expression> is evaluated in the same environment as the define-record-type form, and must evaluate to a protocol appropriate for the record type being defined.
The protocol is used to create a record-constructor descriptor as described below. If no protocol clause is specified, a constructor descriptor is still created using a default protocol. The clause can be absent only if the record type being defined has no parent type, or if the parent definition does not specify a protocol.
(sealed #t)
(sealed #f)
If this option is specified with operand #t, the defined record type is sealed, i.e., no extensions of the record type can be created. If this option is specified with operand #f, or is absent, the defined record type is not sealed.
(opaque #t)
(opaque #f)
If this option is specified with operand #t, or if an opaque parent record type is specified, the defined record type is opaque. Otherwise, the defined record type is not opaque. See the specification of record-rtd below for details.
(nongenerative <uid>)
(nongenerative)
This specifies that the record type is nongenerative with uid <uid>, which must be an <identifier>. If <uid> is absent, a unique uid is generated at macro-expansion time. If two record-type definitions specify the same uid, then the record-type definitions should be equivalent, i.e., the implied arguments to make-record-type-descriptor must be equivalent as described under make-record-type-descriptor. See section 6.3. If this condition is not met, it is either considered a syntax violation or an exception with condition type &assertion is raised. If the condition is met, a single record type is generated for both definitions.
In the absence of a nongenerative clause, a new record type is generated every time a define-record-type form is evaluated:
(let ((f (lambda (x)(let ((f (lambda (x)
(parent-rtd <parent rtd> <parent cd>)
Specifies that the record type is to have its parent type specified by <parent rtd>, which should be an expression evaluating to a record-type descriptor, and <parent cd>, which should be an expression evaluating to a constructor descriptor (see below). The record-type definition associated with the value of <parent rtd> must not be sealed. Moreover, a record-type definition must not have both a parent and a parent-rtd clause.
Note: The syntactic layer is designed to allow record-instance sizes and field offsets to be determined at expand time, i.e., by a macro definition of define-record-type, as long as the parent (if any) is known. Implementations that take advantage of this may generate less efficient constructor, accessor, and mutator code when the parent-rtd clause is used, since the type of the parent is generally not known until run time. The parent clause should therefore be used instead when possible.
All bindings created by define-record-type (for the record type, the constructor, the predicate, the accessors, and the mutators) must have names that are pairwise distinct.
The constructor created by a define-record-type form is a procedure as follows:
If there is no parent clause and no protocol clause, the constructor accepts as many arguments as there are fields, in the same order as they appear in the fields clause, and returns a record object with the fields initialized to the corresponding arguments.
If there is no parent or parent-rtd clause and a protocol clause, the protocol expression must evaluate to a procedure that accepts a single argument. The protocol procedure is called once during the evaluation of the define-record-type form with a procedure p as its argument. It should return a procedure, which will become the constructor bound to <constructor name>. The procedure p accepts as many arguments as there are fields, in the same order as they appear in the fields clause, and returns a record object with the fields initialized to the corresponding arguments.
The constructor returned by the protocol procedure can accept an arbitrary number of arguments, and should call p once to construct a record object, and return that record object.
For example, the following protocol expression for a record-type definition with three fields creates a constructor that accepts values for all fields, and initialized them in the reverse order of the arguments:
If there is both a parent clause and a protocol clause, then the protocol procedure is called once with a procedure n as its argument. As in the previous case, the protocol procedure should return a procedure, which will become the constructor bound to <constructor name>. However, n is different from p in the previous case: It accepts arguments corresponding to the arguments of the constructor of the parent type. It then returns a procedure p that accepts as many arguments as there are (additional) fields in this type, in the same order as in the fields clause, and returns a record object with the fields of the parent record types initialized according to their constructors and the arguments to n, and the fields of this record type initialized to its arguments of p.
The constructor returned by the protocol procedure can accept an arbitrary number of arguments, and should call n once to construct the procedure p, and call p once to create the record object, and finally return that record object.
For example, the following protocol expression assumes that the constructor of the parent type takes three arguments:(lambda (n)
The resulting constructor accepts seven arguments, and initializes the fields of the parent types according to the constructor of the parent type, with v1, v2, and v3 as arguments. It also initializes the fields of this record type to the values of x1, ..., x4.
If there is a parent clause, but no protocol clause, then the parent type must not have a protocol clause itself. The constructor bound to <constructor name> is a procedure that accepts arguments corresponding to the parent types’ constructor first, and then one argument for each field in the same order as in the fields clause. The constructor returns a record object with the fields initialized to the corresponding arguments.
If there is a parent-rtd clause, then the constructor is as with a parent clause, except that the constructor of the parent type is determined by the constructor descriptor of the parent-rtd clause.
A protocol may perform other actions consistent with the requirements described above, including mutation of the new record or other side effects, before returning the record.
Any definition that takes advantage of implicit naming for the constructor, predicate, accessor, and mutator names can be rewritten trivially to a definition that specifies all names explicitly. For example, the implicit-naming record definition:
(define-record-type frob(define-record-type frob
is equivalent to the following explicit-naming record definition.
(define-record-type (frob make-frob frob?)(define-record-type (frob make-frob frob?)
Also, the implicit-naming record definition:
(define-record-type point (fields x y))(define-record-type point (fields x y))
is equivalent to the following explicit-naming record definition:
(define-record-type (point make-point point?)(define-record-type (point make-point point?)
With implicit naming, it is still possible to specify some of the names explicitly; for example, the following overrides the choice of accessor and mutator names for the widget field.
(define-record-type frob(define-record-type frob
Evaluates to the record-type descriptor (see below) associated with the type specified by <record name>.
Note: The record-type-descriptor procedure works on both opaque and non-opaque record types.
Evaluates to the record-constructor descriptor (see below) associated with <record name>.
The following example uses the record? procedure from the (rnrs records inspection (6)) library (section 6.4):
(define-record-type (point make-point point?)(define-record-type (point make-point point?)
The procedural layer is provided by the (rnrs records procedural (6))library.
Returns a record-type descriptor, or rtd, representing a record type distinct from all built-in types and other record types.
The name argument must be a symbol. It names the record type, and is intended purely for informational purposes and may be used for printing by the underlying Scheme system.
The parent argument must be either #f or an rtd. If it is an rtd, the returned record type, t, extends the record type p represented by parent. An exception with condition type &assertion is raised if parent is sealed (see below).
The uid argument must be either #f or a symbol. If uid is a symbol, the record-creation operation is nongenerative i.e., a new record type is created only if no previous call to make-record-type-descriptor was made with the uid. If uid is #f, the record-creation operation is generative, i.e., a new record type is created even if a previous call to make-record-type-descriptor was made with the same arguments.
If make-record-type-descriptor is called twice with the same uid symbol, the parent arguments in the two calls must be eqv?, the fields arguments equal?, the sealed? arguments boolean-equivalent (both #f or both true), and the opaque? arguments boolean-equivalent. If these conditions are not met, an exception with condition type &assertion is raised when the second call occurs. If they are met, the second call returns, without creating a new record type, the same record-type descriptor (in the sense of eqv?) as the first call.
Note: Users are encouraged to use symbol names constructed using the UUID namespace [10] (for example, using the record-type name as a prefix) for the uid argument.
The sealed? flag must be a boolean. If true, the returned record type is sealed, i.e., it cannot be extended.
The opaque? flag must be a boolean. If true, the record type is opaque. If passed an instance of the record type, record? returns #f. Moreover, if record-rtd (see “Inspection” below) is called with an instance of the record type, an exception with condition type &assertion is raised. The record type is also opaque if an opaque parent is supplied. If opaque? is #f and an opaque parent is not supplied, the record is not opaque.
The fields argument must be a vector of field specifiers. Each field specifier must be a list of the form (mutable name) or a list of the form (immutable name). Each name must be a symbol and names the corresponding field of the record type; the names need not be distinct. A field identified as mutable may be modified, whereas, when a program attempts to obtain a mutator for a field identified as immutable, an exception with condition type &assertion is raised. Where field order is relevant, e.g., for record construction and field access, the fields are considered to be ordered as specified, although no particular order is required for the actual representation of a record instance.
The specified fields are added to the parent fields, if any, to determine the complete set of fields of the returned record type. If fields is modified after make-record-type-descriptor has been called, the effect on the returned rtd is unspecified.
A generative record-type descriptor created by a call to make-record-type-descriptor is not eqv? to any record-type descriptor (generative or nongenerative) created by another call to make-record-type-descriptor. A generative record-type descriptor is eqv? only to itself, i.e., (eqv? rtd1 rtd2) iff (eq? rtd1 rtd2). Also, two nongenerative record-type descriptors are eqv? iff they were created by calls to make-record-type-descriptor with the same uid arguments.
Returns #t if the argument is a record-type descriptor, #f otherwise.
Returns a record-constructor descriptor (or constructor descriptor for short) that specifies a record constructor (or constructor for short), that can be used to construct record values of the type specified by rtd, and which can be obtained via record-constructor. A constructor descriptor can also be used to create other constructor descriptors for subtypes of its own record type. Rtd must be a record-type descriptor. Protocolmust be a procedure or #f. If it is #f, a default protocol procedure is supplied.
If protocol is a procedure, it is handled analogously to the protocol expression in a define-record-type form.
If rtd is a base record type and protocol is a procedure, parent-constructor-descriptor must be #f. In this case, protocol is called by record-constructor with a single argument p. P is a procedure that expects one argument for every field of rtd and returns a record with the fields of rtd initialized to these arguments. The procedure returned by protocol should call p once with the number of arguments p expects and return the resulting record as shown in the simple example below:(lambda (p)
Here, the call to p returns a record whose fields are initialized with the values of v1, v2, and v3. The expression above is equivalent to (lambda (p) p). Note that the procedure returned by protocol is otherwise unconstrained; specifically, it can take any number of arguments.
If rtd is an extension of another record type parent-rtd and protocol is a procedure, parent-constructor-descriptor must be a constructor descriptor of parent-rtd or #f. If parent-constructor-descriptor is a constructor descriptor, protocol it is called by record-constructor with a single argument n, which is a procedure that accepts the same number of arguments as the constructor of parent-constructor-descriptor and returns a procedure p that, when called, constructs the record itself. The p procedure expects one argument for every field of rtd (not including parent fields) and returns a record with the fields of rtd initialized to these arguments, and the fields of parent-rtd and its parents initialized as specified by parent-constructor-descriptor.
The procedure returned by protocol should call n once with the number of arguments n expects, call the procedure p it returns once with the number of arguments p expects and return the resulting record. A simple protocol in this case might be written as follows:(lambda (n)
This passes arguments v1, v2, v3 to n for parent-constructor-descriptor and calls p with x1, ..., x4 to initialize the fields of rtd itself.
Thus, the constructor descriptors for a record type form a sequence of protocols parallel to the sequence of record-type parents. Each constructor descriptor in the chain determines the field values for the associated record type. Child record constructors need not know the number or contents of parent fields, only the number of arguments accepted by the parent constructor.
Protocol may be #f, specifying a default constructor that accepts one argument for each field of rtd (including the fields of its parent type, if any). Specifically, if rtd is a base type, the default protocol procedure behaves as if it were (lambda (p) p). If rtd is an extension of another type, then parent-constructor-descriptor must be either #f or itself specify a default constructor, and the default protocol procedure behaves as if it were:(lambda (n)
The resulting constructor accepts one argument for each of the record type’s complete set of fields (including those of the parent record type, the parent’s parent record type, etc.) and returns a record with the fields initialized to those arguments, with the field values for the parent coming before those of the extension in the argument list. (In the example, j is the complete number of fields of the parent type, and k is the number of fields of rtd itself.)
If rtd is an extension of another record type, and parent-constructor-descriptor or the protocol of parent-constructor-descriptor is #f, protocol must also be #f, and a default constructor descriptor as described above is also assumed.
Implementation responsibilities: If protocol is a procedure, the implementation must check the restrictions on it to the extent performed by applying it as described when the constructor is called. An implementation may check whether protocol is an appropriate argument before applying it.
(define rtd1(define rtd1
Calls the protocol of constructor-descriptor (as described for make-record-constructor-descriptor) and returns the resulting constructor constructor for records of the record type associated with constructor-descriptor.
Returns a procedure that, given an object obj, returns #t if obj is a record of the type represented by rtd, and #f otherwise.
K must be a valid field index of rtd. The record-accessor procedure returns a one-argument procedure whose argument must be a record of the type represented by rtd. This procedure returns the value of the selected field of that record.
The field selected corresponds to the kth element (0-based) of the fields argument to the invocation of make-record-type-descriptor that created rtd. Note that k cannot be used to specify a field of any type rtd extends.
K must be a valid field index of rtd. The record-mutator procedure returns a two-argument procedure whose arguments must be a record record r of the type represented by rtd and an object obj. This procedure stores obj within the field of r specified by k. The k argument is as in record-accessor. If k specifies an immutable field, an exception with condition type &assertion is raised. The mutator returns unspecified values.
(define :point(define :point
The (rnrs records inspection (6))library provides procedures for inspecting records and their record-type descriptors. These procedures are designed to allow the writing of portable printers and inspectors.
On the one hand, record? and record-rtd treat records of opaque record types as if they were not records. On the other hand, the inspection procedures that operate on record-type descriptors themselves are not affected by opacity. In other words, opacity controls whether a program can obtain an rtd from a record. If the program has access to the original rtd via make-record-type-descriptor or record-type-descriptor, it can still make use of the inspection procedures.
Returns #t if obj is a record, and its record type is not opaque, and returns #f otherwise.
Returns the rtd representing the type of record if the type is not opaque. The rtd of the most precise type is returned; that is, the type t such that record is of type t but not of any type that extends t. If the type is opaque, an exception is raised with condition type &assertion.
Returns the name of the record-type descriptor rtd.
Returns the parent of the record-type descriptor rtd, or #f if it has none.
Returns the uid of the record-type descriptor rtd, or #f if it has none. (An implementation may assign a generated uid to a record type even if the type is generative, so the return of a uid does not necessarily imply that the type is nongenerative.)
Returns #t if rtd is generative, and #f if not.
Returns #t if the record-type descriptor is sealed, and #f if not.
Returns #t if the the record-type descriptor is opaque, and #f if not.
Returns a vector of symbols naming the fields of the type represented by rtd (not including the fields of parent types) where the fields are ordered as described under make-record-type-descriptor. The returned vector may be immutable. If the returned vector is modified, the effect on rtd is unspecified.
Returns #t if the field specified by k of the type represented by rtd is mutable, and #f if not. K is as in record-accessor. | https://docs.racket-lang.org/r6rs/r6rs-lib-std/r6rs-lib-Z-H-7.html | CC-MAIN-2018-13 | refinedweb | 4,728 | 52.09 |
Red Hat Bugzilla – Bug 136218
yum stops with Python error
Last modified: 2014-01-21 17:50:23 EST
From Bugzilla Helper:
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3)
Gecko/20040913 Firefox/0.10.1
Description of problem:
yum stops with Python error, no matter what parameter I use:
Traceback (most recent call last):
File "/usr/bin/yum", line 6, in ?
import yummain
ImportError: No module named yummain
Version-Release number of selected component (if applicable):
yum-2.1.8-1
How reproducible:
Always
Steps to Reproduce:
See below.
Additional info:
*** This bug has been marked as a duplicate of 136172 ***
Changed to 'CLOSED' state since 'RESOLVED' has been deprecated. | https://bugzilla.redhat.com/show_bug.cgi?id=136218 | CC-MAIN-2016-26 | refinedweb | 118 | 57.57 |
Dockerize It!
Anna Zubova
・6 min read
Solving problems with code is a lot of fun. But when your creative process gets interrupted by a dependency issue where you have to dig into the terminal and check versions fearing that one wrong move can break what you have been building for weeks, it is definitely a frustrating setback.
On my path to learn Data Science, I have struggled a lot with creating the right environment for my project and making sure that all my packages are installed and are not creating any issues. But what happens when I need to run my application on a server where I don’t have my hand-crafted development environment? Luckily, Docker saves the day.
Docker is an open source platform for developers and sysadmins to develop, deploy, and run applications with containers (from Docker documentation). Here we are talking about linux containers, or in other words, applications that let developers wrap a project into one package that contains all the libraries and dependencies along with the project code itself. A container can be compared with a virtual machine, but it is much more lightweight since it uses only the right amount of resources from the host machine, rather than creating a full operating system inside the host machine.
In this tutorial I will introduce you to some key Docker concepts and components to be able to start using them in your development process.
Installation
- Download Docker:
There are 2 Docker editions available: Docker CE (Community Edition) and EE (Enterprise Edition). The documentation recommends CE for learning purposes and small team projects. Docker can be run on AWS or downloaded to run on your local machine. In this tutorial I am going to download Docker for MacOS. If you don’t have a Docker account, you will need to create one to be able to download the installation file.
Run Docker.dmg installation file and move the application to your Applications folder
Open Docker from your Applications folder. You will see an icon appearing in the upper right corner of your screen.
- In Terminal type the following to see if it is working correctly:
docker run hello-world
The output should look like thi:.
Docker Images and Dockerfiles
There are 2 key components of Dockerizing your project: Docker images and Dockerfiles.
An image can be described as a set of tools and instructions that we need to execute the project's code: system tools, libraries, dependencies, etc. Conveniently, this set of tools can be reused in a very easy way, so you would not need to define a new project environment, but can rather reuse an existing one.
A Dockerfile is a text file with a set of instructions to assemble an image. Each line of the Dockerfile is considered a layer which can be later reused.
There is also a cloud service called Docker Hub where Docker users can share Docker images. This service is similar to what GitHub does for git.
Running an existing image
To test how Docker can run a Jupyter server, I followed this tutorial
I started with running this command in my terminal:
docker run ubuntu:16.04
This command will run an image called [ubuntu] with image version [16.04]. If Docker doesn’t find the image on a local machine, it will then look in the Docker Hub to download the image.
There are some extra options for the
run command that can be found in the Docker Official Documentation.
As I mentioned before, it is very convenient to use existing images. Let’s run an image already created by Jupyter development community that has just Python and Jupyter installed:
docker run -p 8880:8888 jupyter/minimal-notebook
In the above line,
-p <host_port>:<container_port> is the part that tells Docker to open connection between the Docker container and host machine, so interaction with the running container is possible.
jupyter/minimal-notebookis the image that we want to run.
After running this command, you will see this type of output in your terminal:
To access the notebook, open this file in a browser: Or copy and paste one of these URLs: http://(2f0da4326d97 or [my IP address]):8888/?token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
From the last URL we have to take the token number, which I represented with 'x' since it is a secret key. With the port number 8880 that I used to run the image, I was able to access the notebook:
Next step would be to allow to create and make changes to a Jupyter notebook with a container running. There is a special option in
run command:
-v <host_directory>:<container_directory>
Host directory specifies where to store the notebook we are going to create, and container directory should be specified in the container documentation (if using Docker Hub container). In our case the container directory from the documentation was
/home/jovyan
So the final code to run an image with the option to access it and create notebook is:
docker run -p 8880:8888 -v ~/docker_tests:/home/jovyan jupyter/minimal-notebook
Going to in your browser will allow you access your Jupyter server and create notebooks.
Dockerizing your Python project
To Dockerize your project, you will first need to create a Dockerfile containing instructions on what image you are going to be using, what packages you need to install, and what your project’s directory is.
Imagine that you need to Dockerize your python script called
add_numbers.py that would require installation of the
scikit-learn library.
First, create a file called Dockerfile (don't add extension to it!). Add these lines to the file in any text editor:
FROM python:3 ADD add_numbers.py / RUN pip install -U scikit-learn CMD [ "python", "add_numbers.py" ]
FROM command says what image you are using as a template.
ADD tells Docker to add certain script to the Dockerfile. This command takes 2 parameters: source and destination
ADD <source> <destination>
RUN says that before executing the script, installation of
scikit-learn should be done.
CMD provides the default command that will be executed after the image has loaded unless overwritten by other command.
My python file
add_numbers.py has just the following code:
def add_numbers (a, b): return a + b c = 3 d = 4 print(add_numbers(c, d))
After creating my script and my Dockerfile that has the instructions on how to create an image, I can run this command to build a new image based on newly created Dockerfile:
docker build -t add_numbers .
This commands creates an image called ‘add_numbers’ based on a Dockerfile from the same directory we are running the command from.
Finally, we can run the image with this command:
docker run add_numbers
As my python script contained a function that would add two numbers and print out the result, and also had one function call to add 3 + 4, I got 7 as an output in my terminal.
To learn more, please refer to the official Docker documentation:
Useful tutorials on starting working with Docker:
(open source and free forever ❤️)
Anna this was extremely helpful thank you for writing!
Congrats Anna, nice tutorial.
Have you tested alpine images yet? it will create the smallest images for you.
FROM python:3-alpine // change this line. you will see the difference between the sizes. | https://practicaldev-herokuapp-com.global.ssl.fastly.net/annalara/dockerize-it-4pne | CC-MAIN-2019-30 | refinedweb | 1,218 | 58.62 |
Alexandrescu, Meyers, Sutter: On Static If, C++11 in 2012, Modern Libraries, and Metaprogramming
- Posted: Aug 21, 2012 at 5:00 AM
- 84,265 Views
- 24 Comments
Something went wrong getting user information from Channel 9
Something went wrong getting user information from MSDN
Something went wrong getting the Visual Studio Achievements
Right click “Save as…”
Channel 9 was invited to this year's C++ and Beyond to film some sessions (that will appear on C9 over the coming months!) and have a chat with the "Big Three": Andrei Alexandrescu, Scott Meyers, and Herb Sutter. If you are a C++ programmer, then you know these names very well. If you've not heard of C++ and Beyond, well, put it down as a must-attend event (let's hope they do it again in 2013!). You can see material from last year's event here..
Huge thanks to Andrei, Herb, and Scott for their time and wisdom. Thanks, too, to the Niners who asked great questions!
Here's what happened:
[00:00] Themes for C++ in 2012 and beyond (and C++ and Beyond 2012)
[07:00] C++11 Efficiency and Concurrency/Parallelism (Standardization)
[12:12] dot_tom asks: When can we expect standardized modern libraries like, XML, File system, Web Services?
[15:00] ZippyV asks: Standardized modern libraries: What has the response been? Any unexpected requests?
[17:17] static if
[26:26] Matt_PD asks: Future of template metaprogramming? Standardizing static loops?
[40:07] More on template metaprogramming (and static if and enable_if)...
[50:05] async/await language feature in C++ would be nice, C! I've been waiting for the C++ and Beyond 2012 coverage. Very happy to see it here!
@dot_tom: And your question was answered
Thanks for asking it!
C
What about header files? Will they always be required? I suppose you could say the editor should just automatically generate the header, but then there is the requirement to include the header in the .cpp file. Anyway, having to duplicate the definition of a function in the .h and .cpp files really slows me down when coding C++. It also impacts code organization. VC++ 2012 allows filters to organize code, but that is not as good as using folders in C#. In C# I have each class in its own source file, where the name of the source file is the name of the class. Then the source files are organized in a hierarchy of folders and sub folders. I try to do roughly the same in c++ projects, but class declarations are still consolidated in a single .h files. Which results in a single .h file and multiple .cpp files, which requires more organizational thought to assign meaningful file names, and makes it harder to find the file in solution explorer that I need to edit.
Will the ^ syntax used in c++ WinRT apps be enabled for all windows apps? I assume the hat syntax encapsulates some sort of automatic implementation of smart pointers. It looks like a feature I would like to use.
Andrei: To be fair, part of the reason we got away without static foreach in D so far is that we _do_ have compile-time foreach – pretty much the only thing that's missing compared to a "full" implementation is availability outside functions:
---
import std.stdio, std.typetuple;
void main() {
foreach (T; TypeTuple!(int, float, string)) {
writeln(T.stringof);
}
}
---
shhh.....what was that special announcement by herb again ?
David: You're of course right. By and large I'm trying to minimize mentions of D in C++ contexts because it's as unfair as bringing a machine gun to a knife fight.
Nice discussion, thanks for making it available.
At 41:48 Andrei mentioned a paper on optimisation, and asked if a link couls be place with the video. Do you have the link yet.
@Cairn: Yes: &.
Thanks for passing on the (admittedly long-winded) question, Charles!
In other words, this is how I view the role of extensions like "static_if" (instead of hand-crafted template specialization equivalent) or, say, "static_while" (instead of, say, hand-crafted recursive template instantiation equivalent) -- similarly to "constexpr", they allow to achieve what's already (at least theoretically / in some cases) possible, but do it in a natural fashion providing accessibility and ease of use to a wider base of developers.
And, of course, thanks for the insightful answers from all!
In particular, Andrei's sentiments are quite compatible to mine here -- for instance, the fact that more metaprogramming facilities go hand in hand with the greater use of (and the need for) the supporting infrastructure (or "a web of supporting facilities in the language and in the std. lib.," as in CTFE in the tangent function values compile-time tabulation example). That's also why I'm looking into this area with a renewed interest now, given C++11's progress -- in fact, constexpr, also mentioned in the discussion, is one of the new C++11 features I'm most happy about in this context and I'm already thinking of it as being a part of this very supporting infrastructure
In particular, CTFE (D) seems to be one of the requirements for the aforementioned example and constexpr (C++11) seems to provide just that:
// Incidentally, constexpr being another form of compile-time language is also a very good point, there are already some nice examples out there illustrating the code simplification (relative to C++03 TMP) it allows for: &
Charles has already linked to the questions thread with the link to Agner's example so I won't spam here again, but can also add Compile-Time Language (CTL) available in High Level Assembly (HLA) as another illustration:
// See also 8.3 Writing Compile-Time "Programs":
I think the point on making the language available for everyone ("language should be comphrehensible and usable for 100% of its users") is also a great point which I fully agree with. In fact, that's an important motivating factor -- ideally TMP should *not* be a feature just for the "select few" and I think we agree that it's more a result of a historical coincidence in the case of TMP rather than an inherent difficulty of TMP itself. Hence, Herb's and Scott's points (as in the worries about repelled-not-attracted or run-screaming reactions ;]) are fully and well taken (it's also true TMP is indeed just one area of C++ and not in quite as widespread use as the others). At the same time, simplifying the syntax / removing the awkwardness are directly meant to address this exact point
Why so long to produce an XML library? Excuse me if I do not understand the context of the issue. Why would it take years to code the equivalent of LINQ to XML in C++?
Why is this native movement ONLY for the client?
Where is a native server framework? All of the server frameworks that MS offers are managed, ASP.Net Webform, MVC, and on it goes.
How is it possible that native, which is only needed in a few cases on the client, but massively needed on the server where every cycle counts, is nonexistant?
Exactly. I'd say people run screaming not because they fear metaprogramming, but because of the unbearable awkwardness of advanced C++ template metaprogramming.
@Novox: Is there some other form of metaprogramming in C++?
C
Destroy!.
@Novox: This. Putting aside claims of languages that they've supported metaprogramming for years, it seems to me that this is the next obvious step just like C++ was the next obvious step all those years ago.
I'm not remotely a big metaprogramming user, but I don't think even the experts would argue against the fact that it needs to be a lot easier.
Andrei is right that we need to make better usage of the hardware we already have. Sure, C++11 features will help, rvalue references, constexpr etc. but times have moved on. "Modern C++ Design" was published in 2001! It is not unreasonable to at least be planning to radically move the state of the art forward. Who genuinely wants to be stuck forever in the 1970s?
Herb was talking about doing "significantly better than precompiled headers".
He talked in the context of speeding up compilation.
However I had a different need for "standard" precompiled headers.
The idea is that if we have "standard" precompiled headers which can be explicitly included like header files, we can release template libraries in binary form in the same way as we release dlls or static libs. (i.e. without giving out source code).
Let's also not forget that up until now, a lot of the benefit of metaprogramming has been taken by ever increasingly clever compile-time optimisations.
For example
if(sizeof(void*) == 4)
Do_X86()
else if(sizeof(void*) == 8 )
Do_X64()
behaves as a static-if in Visual Studio's release builds, because the compiler is smart enough to see that the condition can be determined at compile-time and the unused branch can be removed.
Similarly (3 * foo) typically becomes ((foo << 1) + foo) in release builds to avoid the multiply - something that other programming languages might try and do by having a meta-programming multiply_by_constant that is clever enough to know tricks to avoid performing multiplies on the hardware.
Meta-programming is certainly interesting from a language perspective, but without a good grounding in compiler theory, it's easy to overstate its important from a performance perspective.
Great! Have been waiting for C&B 2012 stuff. Thanks so much :)
@evildictaitor: I tried this very technique recently instead of resorting to compile-time dispatch and I got compiler warnings (else is never executed etc.) so I disagree. If compilers are getting smarter then that is great, but I don't see that it makes metaprogramming unnecessary.
Hi Charles, is there a schedule for posting other session videos from C++ and Beyond 2012? I'm particularly keen to see Andrei's presentation about high perf C++.
@dot_tom: Hi Tom!
Actually, that specific talk will not be published on Channel 9 (or anywhere else for that matter, I believe).
The rough "schedule" is:
up next: Ask Us Anything Panel
then Scott Meyers Session (Universal References)
then Andrei Session (Systematic Error Handling in C++)
then Herb Session (You don't know _ about _)
then Herb Session (Concurrency and Parallelism)
then Herb Session (Memory Model P1)
then Herb Session (Memory Model P2)
then Convincing Your Boss (to move to C++11) Panel
Something like that... Sorry for not being specific (no exact dates). There will be great content here from this event, but we need to be patient (I mean, I'm ready to ship it all, but that's not going to happen...).
C
Remove this comment
Remove this threadclose | http://channel9.msdn.com/Shows/Going+Deep/Alexandrescu-Meyers-Sutter-On-Static-If-C11-in-2012-Modern-Libraries-and-Metaprogramming?format=progressive | CC-MAIN-2014-49 | refinedweb | 1,806 | 60.55 |
So the title says it all. I’m getting a compilation error inside of my
onClick.
Here’s the code.
public class fieldsActivity extends Activity { Button addSiteButton; Button cancelButton; Button signInButton; /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // to create a custom title bar for activity window requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.fields); // use custom layout title bar getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.topbar); Pager adapter = new Pager(); ViewPager mPager = (ViewPager) findViewById(R.id.fieldspager); mPager.setAdapter(adapter); mPager.setCurrentItem(1); addSiteButton = (Button) findViewById(R.id.addSiteButton); addSiteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mPager.setCurrentItem(2, true); //Compilation error happens here. } }); cancelButton = (Button) findViewById(R.id.cancel_button); signInButton = (Button) findViewById(R.id.sign_in_button); }
If you don’t want to make it final, you can always just make it a global variable.
Answer:
You can declare the variable final, or make it an instance (or global) variable. If you declare it final, you won’t be able to change it later.
Any variable defined in a method and accessed by an anonymous inner class must be final. Otherwise, you could use that variable in the inner class, unaware that if the variable changes in the inner class, and then it is used later in the enclosing scope, the changes made in the inner class did not persist in the enclosing scope. Basically, what happens in the inner class stays in the inner class.
I wrote a more in-depth explanation here. It also explains why instance and global variables do not need to be declared final.
Answer:
The error says it all, change:
ViewPager mPager = (ViewPager) findViewById(R.id.fieldspager);
to
final ViewPager mPager = (ViewPager) findViewById(R.id.fieldspager);
Answer:
Here’s a funny answer.
You can declare a final one-element array and change the elements of the array all you want apparently. I’m sure it breaks the very reason why this compiler rule was implemented in the first place but it’s handy when you’re in a time-bind as I was today.
I actually can’t claim credit for this one. It was IntelliJ’s recommendation! Feels a bit hacky. But doesn’t seem as bad as a global variable so I thought it worth mentioning here. It’s just one solution to the problem. Not necessarily the best one.
final int[] tapCount = {0}; addSiteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { tapCount[0]++; } });
Answer:
As @Veger said, you can make it
final so that the variable can be used in the inner class.
final ViewPager pager = (ViewPager) findViewById(R.id.fieldspager);
I called it
pager rather than
mPager because you are using it as a local variable in the
onCreate method. The
m prefix is cusomarily reserved for class member variables (i.e. variables that are declared at the beginning of the class and are available to all class methods).
If you actually do need a class member variable, it doesn’t work to make it final because you can’t use
findViewById to set its value until
onCreate. The solution is to not use an anonymous inner class. This way the
mPager variable doesn’t need to be declared final and can be used throughout the class.
public class MainActivity extends AppCompatActivity { private ViewPager mPager; private Button mButton; @Override public void onCreate(Bundle savedInstanceState) { // ... mPager = (ViewPager) findViewById(R.id.fieldspager); // ... mButton.setOnClickListener(myButtonClickHandler); } View.OnClickListener myButtonClickHandler = new View.OnClickListener() { @Override public void onClick(View view) { mPager.setCurrentItem(2, true); } }; }
Answer:
When you create an
non static nested (
inner class)About actually a compiler generates a new class –
<ClassName>$<Counter>.class, and pass next parameters into constructorLocal variable on stack
- reference to outer class
- final local variables that are used inside
There is no possibility to reassign the variable from a constructor (or method) but it is simple to change the state of passed variable. That is why you can use:
- a field of outer class
- final local variable which is reference type (e.g.
Object…) and change it’s state inside the inner class
- wrap a local variable that is value(primitive) type (e.g.
int…) and pass it as a reference type (
IntelliJ IDEAproposes you to transform a variable into final one element array)
Tags: class, javajava, sed | https://exceptionshub.com/java-variable-is-accessed-within-inner-class-needs-to-be-declared-final.html | CC-MAIN-2021-17 | refinedweb | 724 | 50.02 |
ROOT macros and shared libraries
A ROOT macro contains pure C++ code, which additionally can contain ROOT classes and other ROOT objects (→ see ROOT classes, data types and global variables). A ROOT macro can consist of simple or multi-line commands, but also of arbitrarily complex class and function definitions.
You can save a ROOT macro in a file and execute it at the ROOT prompt or the system prompt (→ see Creating ROOT macros).
You also can compile a ROOT macro (→ see Compiling ROOT macros).
ROOT provides many tutorials that are available as ROOT macros (→ see ROOT tutorial page).
Creating ROOT macros
The name of the ROOT macro and the file name (without file extension) in which the macro is saved must match.
Create a new file in your preferred text editor.
Use the following general structure for the ROOT macro:
void MacroName() { ... your lines of C++ code code line ends with ; ... }
- Save the file ROOT macro, using the macro name as file name: MacroName.C
Executing ROOT macros
You can execute a ROOT macro:
- at the system prompt,
- at the ROOT prompt,
- by loading it to a ROOT session.
To execute a ROOT macro at the system prompt, type:
root MacroName.C
– or –
To execute a ROOT macro at the ROOT prompt, type:
.x MacroName.C
– or –
To load a ROOT macro to a ROOT session, type (at the ROOT prompt):
.L MacroName.C MacroName()
Note
You can load multiple ROOT macros, as each ROOT macro has a unique name in the ROOT name space.
In addition, you can:
Executing a ROOT macro from a ROOT macro
You can execute a ROOT macro conditionally inside another ROOT macro.
- Call the interpreter TROOT::ProcessLine().
ProcessLine() takes a parameter, which is a pointer to an
int or to a
TInterpreter::EErrorCode to let you access the interpreter error code after an attempt to interpret.
This contains the error as defined in enum
TInterpreter::EErrorCode with
TInterpreter::kSuccess
as being the value for a successful execution.
Example
The example
$ROOTSYS/tutorials/tree/cernstaff.C calls a ROOT macro to build a ROOT file, if it does not exist.
void cernstaff() { if (gSystem->AccessPathName("cernstaff.root")) { gROOT->ProcessLine(".x cernbuild.C"); }
Executing a ROOT macro from the invocation of ROOT
You can pass a macro to ROOT in its invocation.
Example
The exact kind of quoting depends on the used shell. This example works for bash-like shells.
$ root -l -b 'myCode.C("some String", 12)'
Compiling ROOT macros
You can use ACLiC (Compiling Your Code) to compile your code and to build a dictionary and a shared library from your ROOT macro. ACliC is implemented in TSystem::CompileMacro().
When using ACliC, ROOT checks what library really needs to be build and calls your system’s C++ compiler, linker and dictionary generator. Then ROOT loads a native shared library.
ACLiC executes the following steps:
Calls
rootclingto create automatically a dictionary.
For creating a dictionary manually, → see Using rootcling to generate dictionaries manually.
Calls the the system’s C++ compiler to build the shared library.
If there are errors, it calls the C++ compiler to build a dummy executable to clearly report the unresolved symbols.
ACLiC adds the classes and functions declared in included files with the same name as the
ROOT macro files with one of following extensions:
.h,
.hh,
.hpp,
.hxx,
.hPP,
.hXX.
This means that, by default, you cannot combine ROOT macros from different files into one
library by using
#include statements; you will need to compile each ROOT macro separately.
Compiling a ROOT macro with ACLiC
Before you can compile your interpreted ROOT macro, you need to add the include statements for the classes used in the ROOT macro. Only then you can build and load a shared library containing your ROOT macro.
You can compile a ROOT macro with:
default optimizations
optimizations
debug symbols
Compilation ensures that the shared library is rebuilt.
Note
Do not call ACLiC with a ROOT macro that has a function called
main().
To compile a ROOT macro and build a shared library, type:
root[] .L MyScript.C+
The
+ option compiles the code and generates a shared library. The name of the shared library is the filename
where the dot before the extension is replaced by an underscore. In addition, the shared library
extension is added.
Example
On most platforms,
hsimple.cxx will generate
hsimple_cxx.so.
The
+ command rebuilds the library only if the ROOT macro or any of the files it includes
are newer than the library.
When checking the timestamp, ACLiC generates a dependency file, which name is the same as
the library name, just replacing the
so extension by the
d extension.
To compile a ROOT macro with default optimizations, type:
root[] .L MyScript.C++g
To compile a ROOT macro with optimizations, type:
root[] .L MyScript.C++O
To compile a ROOT macro with debug symbols, type:
root[] .L MyScript.C++
Setting the include path
The
$ROOTSYS/include directory is automatically appended to the include path.
To get the include path, type:
root[] .include
To append the include path, type:
root[] .include $HOME/mypackage/include
Append the following line in the ROOT macro to include the include path:
gSystem->AddIncludePath(" -I$HOME/mypackage/include")
To overwrite an existing include path, type:
gSystem->SetIncludePath(" -I$HOME/mypackage/include")
To add a static library that should be used during linking, type:
gSystem->AddLinkedLibs("-L/my/path -l*anylib*");
For adding a shared library, you can load it before you compile the ROOT macros, by
gSystem->Load("mydir/mylib");
Generating dictionaries
A dictionary (“reflection database”) contains information about the types and functions that are available in a library.
With a dictionary you can call functions inside libraries. Dictionaries are also needed to write a class into a ROOT file (→ see ROOT files).
A dictionary consists of a source file, which contains the type information needed by Cling and ROOT’s I/O subsystem. This source file needs to be generated from the library’s headers and then compiled, linked and loaded. Only then does Cling and ROOT know what is inside a library.
There are two ways to generate a dictionary:
using ACLiC
using
rootcling
Using ACLiC to generate dictionaries
With a given header file
MyHeader.h, ACliC automatically generates a dictionary:
root[] .L MyHeader.h+
Using rootcling to generate dictionaries manually
You can manually create a dictionary by using
rootcling:
rootcling -f DictOutput.cxx -c OPTIONS Header1.h Header2.h ... Linkdef.h
DictOutput.cxxSpecifies the output file that will contain the dictionary. It will be accompanied by a header file
DictOutput.h.
OPTIONSare:
Isomething: Adding an include path, so that
rootclingcan find the files included in
Header1.h,
Header2.h, etc.
DSOMETHING: Define a preprocessor macro, which is sometimes needed to parse the header files.
Header1.h Header2.h...: The headers files.
Linkdef.h: Tells
rootcling, which classes should be added to the dictionary, → see Selecting dictionary entries: Linkdef.h.
Note
Dictionaries that are used within the same project must have unique names.
Compiled object files relative to dictionary source files cannot reside in the same library or in two libraries loaded by the same application if the original source files have the same name.
Example
In the first step, a
TEvent and a
TTrack class is defined. Next an event object is created to add tracks to it. The track objects have a pointer to their event. This shows that the I/O system correctly handles circular references.
In the second step, a
TEvent and a
TTrack call are implemented.
After that you can use
rootcling to manually generate a directory. This generates the
eventdict.cxx file.
The TEvent.h header
TTrack.h header
#ifndef __TTrack __ #define __TTrack__ #include "TObject.h" class TEvent; class TTrack : public TObject { private: Int_t fId; // Track sequential id. TEvent *fEvent; // TEvent. };
Implementation of TEvent and TTrack class
TEvent.cxx: #include <iostream.h> #include "TOrdCollection.h" #include "TEvent.h" #include "TTrack.h" ClassImp(TEvent) ... TTrack.cxx: #include <iostream.h> #include "TMath.h" #include "Track.h" #include "Event.h" ClassImp(TTrack) ...
Using rootcling to generate the dictionary
rootcling eventdict.cxx -c TEvent.h TTrack.h
eventdict.cxx - the generated dictionary; } }
Selecting dictionary entries: Linkdef.h
To select which types and functions should go into a dictionary, create a
Linkdef.h file that you use when you call
rootcint manually. The
Linkdef.h file is passed as the last argument to
rootcint. It must end on
Linkdef.h, LinkDef.h, or
linkdef.h. For example,
My_Linkdef.h is correct,
Linkdef_mine.h is not.
The
Linkdef.h file contains directives for
rootcint, for what a dictionary should be created: select the types and functions that will be accessible from the prompt (or in general through CINT) and for I/O.
Preamble: deselection
A
Linkdef.h file starts with the following preamble:
#ifdef __CINT__ #pragma link off all globals; #pragma link off all classes; #pragma link off all functions; #pragma link C++ nestedclasses;
The first line protects the compiler from seeing the
rootcint directives. The
rootcint directives are in the form of
#pragma statements. A
#pragma link of all something says that by default,
rootcint should not generate the dictionary for anything it sees.
The nested classes directive tells
rootcint not to ignore
nestedclasses, this is, classes defined inside classes like here:
class Outer { public: class Inner { public: // we want a dictionary for this one, too! ... }; ... };
Selection
In the next step, tell
rootcint for which objects the dictionary should be generated for:
#pragma link C++ class AliEvent+; #pragma link C++ function StrDup; #pragma link C++ function operator+(const TString&,const TString&); #pragma link C++ global gROOT; #pragma link C++ global gEnv; #pragma link C++ enum EMessageTypes;
Note
**The
+after the class name: This enables an essential feature for
rootcint. It is not a default setting, so you must add
+at the end.
Selection by file name
Sometimes it is easier to say: Create a dictionary for everything defined in the
MyHeader.h file.
Write the following statement into the
Linkdef.h file:
#pragma link C++ defined_in "subdir/MyHeader.h";
Make sure that
subdir/MyHeader.h corresponds to one of the header files that is passed to
rootcint.
Closing
Add the following line at the end of the
Linkdef.h file:
#endif /* __CINT__ */.
Example of a Linkdef.h file
#ifdef __CINT__ #pragma link off all globals; #pragma link off all classes; #pragma link off all functions; #pragma link C++ nestedclasses; #pragma link C++ global gHtml; #pragma link C++ class THtml; #endif
Developing portable ROOT macros
Portable ROOT macros run both with the Cling interpreter and ACLiC (Compiling Your Code).
Therefore, it is recommended not to use the Cling extensions and program around the Cling limitations.
If it is not possible to program around the Cling limitations, use the C preprocessor symbols
defined for Cling and
rootcling:
__CLING__is defined for both ROOT and
rootcling.
__ROOTCLING__(and
__MAKECINT__for backward compatibility) is only defined in rootcling.
Use
!defined(__CLING__) || defined(__ROOTCLING__) to bracket code that needs to be seen by
the compiler and
rootcling, but will be invisible to the interpreter.
– or –
Use
!defined(__CLING__) to bracket code that should be seen only by the compiler and not by Cling nor
rootcling.
Example
Hiding the declaration and initialization of the array
gArray from both Cling and
rootcling:
#if !defined(__CLING__) int gArray[] = { 2, 3, 4}; #endif
Cling and
rootcling will ignore all statements between the
#if !defined (__CLING__)
and
#endif. Because ACLiC calls
rootcling to build a dictionary, the declaration of
gArray will not be included in the dictionary, and consequently,
gArray will not be
available at the command line even if ACLiC is used.
If you want use the ROOT macro in the interpreter, you have to bracket the usage of
gArray
between the
#if’s, since the definition is not visible.
#if !defined(__CLING__) int gArray[] = { 2, 3, 4}; #elif defined(__ROOTCLING__) int gArray[]; #endif
gArray will be visible to
rootcling, but still not visible to Cling. If you use ACLiC,
gArray will be available at the command line.
Included header files
It is recommended to write ROOT macros with all the needed include statements. Only a few header files are not handled correctly by Cling.
You can include following types of headers in the interpreted and compiled mode:
The subset of standard C/C++ headers defined in
$ROOTSYS/Cling/include.
Headers of classes defined in a previously loaded library (including ROOT own library). The defined class must have a name known to ROOT (this is a class with a
ClassDef).
Hiding header files from
rootcling that are necessary for the compiler but optional for the interpreter can lead to a fatal error..
Embedding the rootcling call into a GNU Makefile
Use the following statement to compile and run the code.
.L MyCode.C+
If you need to use a:
libCore.
This rule generates $^ | https://root.cern.ch/manual/interacting_with_shared_libraries/ | CC-MAIN-2021-04 | refinedweb | 2,141 | 65.42 |
Creating a Chrome Extension for Diigo, Part 2
Free JavaScript Book!
Write powerful, clean and maintainable JavaScript.
RRP $11.95
In part 1, we introduced some new concepts, explained how we were going to build the extension and demonstrated the use of the Diigo API. In this part, we'll create most of our helper functions and deal with error handling.
Error handling
When the API returns a response, it's up to us to cover all edge cases and use it adequately. Relying on the request to succeed every time isn't an option – we need to account for not only the ready-state, but also potential failures.
In order to clean up the code somewhat and make
background.js more concise, I compressed the Base64 object into a minified string. The background.js file as it is now looks like this. You can start from that one if you're following along with the code.
The
xml.readyState === 4 part checks if the request is complete. Once it's complete, we're free to check for the status code. Only 200 means "success", all others mean something went wrong. Using the list of possible responses, we'll modify our code to produce a human readable description of the error that occurred.
var possibleErrors = { 400: 'Bad Request: Some request parameters are invalid or the API rate limit is exceeded.', 401: 'Not Authorized: Authentication credentials are missing or invalid.', 403: 'Forbidden: The request has been refused because of the lack of proper permission.', 404: 'Not Found: Either you\'re requesting an invalid URI or the resource in question doesn\'t exist (e.g. no such user).', 500: 'Internal Server Error: Something is broken.', 502: 'Bad Gateway: Diigo is down or being upgraded.', 503: 'Service Unavailable: The Diigo servers are too busy to server your request. Please try again later.', other: 'Unknown error. Something went wrong.' }; xml.onreadystatechange = function() { if (xml.readyState === 4) { if (xml.status === 200) { console.log(xml.responseText); } else { if (possibleErrors
!== undefined) {
console.error(xml.status + ' ' + possibleErrors
);
} else {
console.error(possibleErrors.other);
}
}
}
};
In the above code, we define a set of error messages and bind each message to a key corresponding to the status code. We then check if the code matches any of the predefined ones and log it in the console. If the request is successful, we output the responseText.
The above error handling is very basic, and not very end-user friendly. Options to improve it are: an alert box when an error occurs, graying out the extension's icon, deactivating the extension, and more. I'll leave that up to you.
We can also wrap the whole shebang into a function, just so it's neatly encapsulated and the global namespace isn't polluted:
var doRequest = function() { var xml = new XMLHttpRequest(); xml.open('GET', url); xml.setRequestHeader('Authorization', auth); xml.send(); xml.onreadystatechange = function() { if (xml.readyState === 4) { if (xml.status === 200) { console.log(xml.responseText); } else { if (possibleErrors !== undefined) { console.error(xml.status + ' ' + possibleErrors ); } else { console.error(possibleErrors.other); } } } }; }; doRequest();
Popup
Now that we have our responseText, we can process it. We first need to turn it into a proper array, because it's useless to us in string form. Replace
console.log(xml.responseText);with:
var response = JSON.parse(xml.responseText); console.log(response);
The above should produce a JavaScript Array of JavaScript Objects when you look at the generated background page's JavaScript console.
I've made a test account called "testerguy" on Diigo, with some sample bookmarks. You should probably make your own to experiment with, since there's no telling what might be going on with this one by the time you're reading this article.
As mentioned in part 1, the structure of the bookmark folder will be: all "bbs-root" tagged bookmarks in the root of the folder, and all tags in subfolders in the "tags" folder. This is so the user can prioritize certain bookmarks by tagging them with "bbs-root" and make sure they appear outside their respective folders for fastest access.
In order to properly make the Bookmark Bar folder, we need to find out all the unique tags, create the root folder, create the subfolder "tags" and create subfolders for each tag we know of, in that order. To make testing for this easier, we'll add a popup to our extension with a Refresh button which repeats the XHR request. Update the
manifest.json
browser_actionblock like so:
"browser_action": { "default_icon": { "19": "icons/19.png", "38": "icons/38.png" }, "default_title": "Diigo BBS", "default_popup": "popup/popup.html" },
and create a folder called
popupin the root of your project. Create three more files in that folder:
popup.html,
popup.jsand
popup.csswith the following content:
<!-- popup.html --> <!DOCTYPE html> <html> <head> <title>BBS popup</title> <script src="popup.js"></script> <link rel="stylesheet" type="text/css" href="popup.css"> <link rel="icon" href="../icons/19.png"> </head> <body> <button id="refreshButton">Refresh</button> </body> </html>
// popup.js var bg = chrome.extension.getBackgroundPage(); document.addEventListener('DOMContentLoaded', function () { document.getElementById('refreshButton').addEventListener('click', function() { bg.doRequest(); }); });
/* popup.css */ #refreshButton { margin: 10px; }
The JS code here does the following: first we fetch the window object of the
background.jsscript's autogenerated page. Popup scripts have direct access to background page code, as opposed to content scripts which have to pass messages. Then, we bind a click handler to the Refresh button's click event which calls our
doRequestmethod from
background.js.
If you reload the extension now and keep the generated background page open, you should see repeated outputs of fetched bookmarks as you click the refresh button.
We can now continue coding in
background.js.
Processing the response array
We find all tags by iterating through all the fetched bookmarks, storing them in an array, and then removing duplicates. While we're iterating, we can check for all bookmarks containing the tag "bbs-root" and make a note of them in a separate variable. Let's add a
processfunction:
var process = function(response) { var iLength = response.length; if (iLength) { console.info(iLength + " bookmarks were found."); } else { console.info("Response is empty - there are no bookmarks?"); } };
Also, in the function
doRequest, let's replace
var response = JSON.parse(xml.responseText); console.log(response);
with
process(JSON.parse(xml.responseText));.
Reloading the extension will print out the number of found bookmarks for the selected user. Let's include a helper function to assist us with filtering out the duplicate tags from the tags array. This function extends the native JavaScript Array, so you can call it as if it had been built in all along. Put it under the Base64 part, near the top of the file:
/** * Removes duplicate elements from the array */ Array.prototype.unique = function () { var result = []; var len = this.length; while (len--) { if (result.indexOf(this[len]) == -1) { result.push(this[len]); } } this.length = 0; len = result.length; while (len--) { this.push(result[len]); } };
Now, let's build out the
processfunction.
var process = function(response) { var iLength = response.length; var allTags = []; var rootBookmarks = []; if (iLength) { console.info(iLength + " bookmarks were found."); var i = iLength; while (i--) { var item = response[i]; if (item.tags !== undefined && item.tags != "") { var tags = item.tags.split(','); if (tags.indexOf('bbs-root') > -1) { rootBookmarks.push(item); } allTags = allTags.concat(tags); } } allTags.unique(); allTags.sort(); console.log(allTags); } else { console.info("Response is empty - there are no bookmarks?"); } };
We iterate through all the bookmarks, if any are found, and for each one we turn their "tags" property into an array. This array then gets merged with the
allTagsarray on which we call
unique()to remove duplicates, and sorted alphabetically. In the process, we also watch out for bbs-root tagged bookmarks and copy their references to the
rootBookmarksarray.
We are now ready to manipulate the Bookmarks Bar.
Bookmarks Bar
First, we need to check if "Diigo #BBS" exists as a folder in the bookmarks bar. If not, we create it. Put the following code immediately under
allTags.sort();:
var folderName = 'Diigo #BBS'; chrome.bookmarks.getChildren("1", function(children) { var numChildren = children.length; var folderId; while (numChildren--) { if (children[numChildren].title == folderName) { folderId = children[numChildren].id; break; } } if (folderId === undefined) { chrome.bookmarks.create({ parentId: "1", title: folderName }, function(folder) { folderId = folder.id; console.log(folderName + " not found and has been created at ID " + folder.id); }); } });
We first get the children of the node with the ID 1, which is the bookmarks bar (you can see that by using getTree). We then iterate through them, and compare their titles to the desired name of our folder. If the folder is found, we save its ID and exit the loop. If it's never found, we create it and save the ID.
Now we need to find out if our folder contains the folder "Tags". Once we do that, we'll need to find out if our "Tags" folder contains a subfolder matching the name of every tag we found. Noticing a pattern here? Looks like we'll need a common function for checking if a bookmark folder contains another folder. We might as well make another helper method to check for actual bookmarks, too. Let's add the following functions to our background.js file (above the
processfunction, for example):
chrome.bookmarks.getFirstChildByTitle = function (id, title, callback) { chrome.bookmarks.getChildren(id, function (children) { var iLength = children.length; while (iLength--) { var item = children[iLength]; if (item.title == title) { return callback(item); } } return callback(false); }); }; chrome.bookmarks.getFirstChildByUrl = function (id, url, callback) { chrome.bookmarks.getChildren(id, function (children) { var iLength = children.length; while (iLength--) { var item = children[iLength]; if (item.hasOwnProperty('url') && item.url == url) { return callback(item); } } return callback(false); }); };
These functions are almost identical, though each compares its own property to the provided value. We'll use one for folders, and the other for bookmarks. These methods are asynchronous just like the rest of the
chrome.bookmarksnamespace, so we'll need to provide callbacks whenever we use them.
You can also merge them into one single method and use a third parameter that tells the method which property we're looking for (title or url), thus respecting the DRY principle a bit more. I'll leave that up to you for now, and come back to it in a followup article that will be focusing on optimizations.
Let's rewrite our
processmethod to use this now.
chrome.bookmarks.getFirstChildByTitle("1", folderName, function(value) { if (value === false) { chrome.bookmarks.create({ parentId: "1", title: folderName }, function (folder) { console.log(folderName + " not found and has been created at ID " + folder.id); }); } });
Much more concise, isn't it? When we consider further steps, it's clear we'll need to differentiate between a list of existing tags, and the list of tags we've freshly fetched from the server. For this purpose, we'll add two new helper methods to the native JavaScript Array object:
intersectand
diff. Let's put them at the top of the file, right where
Array.unique()is, and while we're at it, let's move the
getFirstChildByTitleand
getFirstChildByUrlmethods up there as well.
/** * Returns an array - the difference between the two provided arrays. * If the mirror parameter is undefined or true, returns only left-to-right difference. * Otherwise, returns a merge of left-to-right and right-to-left difference. * @param array {Array} * @param mirror * @returns {Array} */ Array.prototype.diff = function (array, mirror) { var current = this; mirror = (mirror === undefined); var a = current.filter(function (n) { return array.indexOf(n) == -1 }); if (mirror) { return a.concat(array.filter(function (n) { return current.indexOf(n) == -1 })); } return a; }; /** * Returns an array of common elements from both arrays * @param array * @returns {Array} */ Array.prototype.intersect = function (array) { return this.filter(function (n) { return array.indexOf(n) != -1 }); };
Finally, let's add a helper method for console logging in the same place at the top of the
background.jsfile:
const CONSOLE_LOGGING = true; function clog(val) { if (CONSOLE_LOGGING) { console.log(val); } }
You can now replace all your console.log() calls in the code with
clog. When you need to turn the logging off, simply switch the CONSOLE_LOGGING constant to
falseand all output will stop. This is great when moving from development to production – it introduces a very small overhead, but cuts down on preparation time in that you don't need to manually hunt down and comment or remove all your console outputs.
Conclusion of Part 2
In this part, we built several helper functions essential for further work, and added some basic error handling logic. In the next installment of this series, we build the body of the extension. Stay tuned!
Get practical advice to start your career in programming!
Master complex transitions, transformations and animations in CSS! | https://www.sitepoint.com/creating-chrome-extension-diigo-part-2/ | CC-MAIN-2021-04 | refinedweb | 2,119 | 60.41 |
I want to create an animation in which a box will move on a specified track.
Is there way to accomplish this task in python?
Also is there boolean plot function in matplotlib which can allow one to explicitly draw pixels?
I'm going to adapt from this answer (from @unutbu). The following code builds a square trajectory and moves a rectangle with it:
import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches from matplotlib import animation # Building a possible trajectory x = np.hstack((np.linspace(-5, 5, 50), np.ones(50)*5, np.linspace(5, -5, 50), np.ones(50)*-5)) y = np.hstack((np.ones(50)*-5, np.linspace(-5, 5, 50), np.ones(50)*5, np.linspace(5, -5, 50))) yaw = [0.0, 0.5, 1.3] fig = plt.figure() plt.axis('equal') plt.grid() ax = fig.add_subplot(111) # Adding a simple plot for trajectory (initial coordinate of rectangle) ax.plot([-5, 5, 5, -5, -5], [-5, -5, 5, 5, -5], color="grey", linestyle="--") ax.set_xlim(-10, 10) ax.set_ylim(-10, 10) patch = patches.Rectangle((0, 0), 0, 0, fc='y') def init(): ax.add_patch(patch) return patch, def animate(i): patch.set_width(1.2) patch.set_height(1.0) patch.set_xy([x[i], y[i]]) return patch, anim = animation.FuncAnimation(fig, animate, init_func=init, frames=len(x), interval=50, blit=True) plt.show()
, the result is this (well just a screenshot, its actually animated):
As for your other question, matplotlib is not pixel based so I don't think you have a (easy) way of drawing just one pixel. Depending on your objective you light want to consider using the well supported image api in matplotlib to provide you with customized backgrounds. So you would be drawing in arrays that would be parsed to the screen by matplotlib. | https://codedump.io/share/Jwp7wwlQJtsP/1/how-to-plot-2d-object-in-python | CC-MAIN-2017-39 | refinedweb | 306 | 61.83 |
SDL for Mac
Installing SDL
The SDL Package can be installed for all users or just one user.
The following location is where you can get SDL:
The Package is under the "Runtime Libraries" called:
SDL-1.2.14.dmg
.
Avoid the Mac OS X development library unless you intend to explore SDL deeply.
Save the package somewhere easy to find. I suggest you right click and "Save Link As..." to the Desktop.
From the included ReadMe.txt:
To Install:
Copy the SDL.framework to /Library/Frameworks
You may alternatively install it in <Your home directory>/Library/Frameworks if your access privileges are not high enough.
Be sure to keep the devel-lite folder somewhere safe.
Set up a SDL Program
Start XCode
Create a new Project
From the list at the left select Application
From the icons at the right select Cocoa Application
Click Choose...
Name your project, select a location to save it and click Save.
Find and add the SDL.framework.
NOTE:
If you don't see it listed with the other frameworks, I suggest dragging and dropping it to your project group from the folder you installed it to. If you search for it you will lose your main Framework directory. By default your Framework path should be:
/Developer/SDKs/MacOSX10.5.sdk/System/Library/Frameworks
Find and add the OpenGL.framework.
Delete main.m and move it to the trash.
From the devel-lite folder, copy SDLmain.h and SDLmain.m to the project folder and add them to your project as existing files.
Copy your main C or C++ file to the project folder and add it as an existing file.
For new projects, you can start from this
SDL template
.
Try compiling. If you're like me you got a complaint about "SDL.h" in "SDLmain.m". Change the offending line to read:
#include <SDL/SDL.h>
Compile again and you're good to go. | http://www.cs.uregina.ca/Links/class-info/315/WWW/Lab1/SDL/mac.html | CC-MAIN-2018-22 | refinedweb | 322 | 77.43 |
Mar 29 2019 10:34 AM
Mar 29 2019 10:34 AM
Good Evening,
I am looking for some advice with an Exchange migration. . I have a client that has an Exchange 2007 server but is using Office 365 (no hybrid) and we are migrating them to Exchange 2016. They use Azure AD connect to sync AD to Office 365 but use Exchange 2007 to manage the mail attributes. We are moving them to Exchange 2016 as Exchange 2007 is a out of support. Typically I would upgrade to Exchange 2013 then Exchange 2016 Management tool. They have no mailboxes, all their users have been setup as Mail Users. Do I need to still do the migration or can I decommission Exchange 2007 then install Exchange 2016 management tool and link the AD accounts to Mail Users?
Mar 29 2019 06:09 PM - edited Mar 29 2019 06:10 PM
Mar 29 2019 06:09 PM - edited Mar 29 2019 06:10 PMSolution
First, let me remind you that you cannot install Ex2016 in an environment which still contains Ex2007 servers, so that sets your upgrade path through Ex2013. I would not start with decomissioning Ex2007, as that in essence means removing all on-prem configuration items related to Exchange, which you then need to re-configure after deploying Ex2016 (e.g. accepted domains). Just follow the regular upgrade procedure for Ex2007->Ex2013, then Ex2013 to Ex2016. Since everybody lives in Office 365 already (assuming you have autodiscover pointing to Office365 and you have no mail relay functionality on-prem, etc), you have no worries regarding namespace, public endpoints etc.
Apr 01 2019 03:40 AM
Apr 01 2019 03:40 AM
Thanks Michel. In regards to the mail user accounts I am struggling to find material on how they are migrated to the new exchange server, do you have any information on that?
Sep 23 2019 07:39 AM
Sep 23 2019 07:39 AM
Hello Brian, check and let me know if this link is helpful | https://techcommunity.microsoft.com/t5/exchange/exchange-maigration-mail-users/td-p/390976 | CC-MAIN-2021-17 | refinedweb | 338 | 64.95 |
Red Hat Bugzilla – Bug 667124
artifacts visible on scroll
Last modified: 2011-01-10 03:51:36 EST
See the attached screenshot taken with:
import -display :0.0 -window root ff-artifacts.png
The area circled in red has artifacts due to the overlying terminal window.
They appear after scrolling the firefox content.
This happens with general.smoothScroll on or off.
$ rpm -q xorg-x11-drv-intel xorg-x11-server-Xorg kernel firefox
xorg-x11-drv-intel-2.12.0-6.fc14.1.i686
xorg-x11-server-Xorg-1.9.3-3.fc14.i686
kernel-2.6.35.10-72.fc14.i686
firefox-3.6.13-1.fc14.i686
Created attachment 471679 [details]
See the area enclosed in red
I should also add:
$ lspci | grep VGA
00:02.0 VGA compatible controller: Intel Corporation Mobile 915GM/GMS/910GML Express Graphics Controller (rev 03)
Also I don't see the issue in other apps,
but I do see flickering in the problematic
area in other apps, but they do always draw
in a consistent state, when you stop scrolling.
Also it doesn't happen immediately, but may
take 10-20s of scrolling in firefox to show the issue
This one is a firefox bug fixed in rawhide.
Cool thanks.
Will it be backported. It's a minor issue so I guess not.
Do you have a pointer to the bug or patch for the issue?
It's fixed by new layer engine in ff4 and it's not going to be backported to 3.6 line. | https://bugzilla.redhat.com/show_bug.cgi?id=667124 | CC-MAIN-2017-09 | refinedweb | 255 | 65.62 |
The TryCatchFinally Interface in JSP
By: Jagan Emailed: 1671 times Printed: 2149 times
TryCatchFinally.java
package javax.servlet.jsp.tagext;
import javax.servlet.jsp.*;
public interface TryCatchFinally {
void doCatch(Throwable t) throws Throwable;
void doFinally();
}
The TryCatchFinally interface has two methods, doCatch() and doFinally(), in which you can place functionality that might typically be written into catch and finally blocks. For example, in the doCatch() method, you might choose to roll back a transaction, and in the doFinally() method, you might choose to close a file or a connection to a remote resource. In essence, tags should implement this interface if you want them to have more control over exception handling. Figure below shows a UML diagram of the tag life cycle for a tag that implements the TryCatchFinally interface. Next, we’ll cover each of the methods in turn.
The doCatch() Method
The JSP specification guarantees that the doCatch() method will be called if an exception is thrown in the doStartTag() method, the tag’s body content, or the doEndTag() method. Additionally, if the tag handler implements the IterationTag or BodyTag interface, the doCatch() method will be executed if an exception is thrown within the doAfterBody() and doInitBody() methods, respectively.
Something to notice is that the doCatch() method won’t be called if an exception is thrown before the execution of the doStartTag() method—perhaps when the context or attributes are being set. Therefore, it’s best not to put any logic into attribute setter methods that may cause an exception to be thrown.
If the exception should be propagated further up the calling stack, perhaps by a JSP error page, the doCatch() method can handle the exception as required and then subsequently rethrow the same or a new exception. This is useful because there’s no way to tell the tag handler class to catch only specific subclasses of Exception in the same way you would when writing try-catch blocks in your code. Instead, the doCatch() method handles all exceptions, and it’s up to us as tag developers to decide which to handle and which to rethrow.
During the tag life cycle, there are several opportunities where doCatch() or doFinally() might be called to handle an exception.
The doFinally() Method
When you write try-catch-finally blocks in regular Java code, the finally block always gets called, regardless of whether an exception was thrown. Similarly, the doFinally() method on the tag handler will always get called.
Although tag handlers are generally small components, there is still much that can go wrong, especially when you’re dealing with databases and remote objects such as Enterprise JavaBeans. Implementing the TryCatchFinally interface is a way to build tags that are better equipped to deal with such problems; it will make your tag libraries more robust and resilient to failure. With this in mind, let’s now take a look at how you can deploy these resilient tags and make them available for use in the easiest possible way.
Be the first one to add a comment | http://www.java-samples.com/showtutorial.php?tutorialid=612 | CC-MAIN-2017-17 | refinedweb | 507 | 57.4 |
The download files contain a Visual Studio 2012 project and source files, but no executable file. If you don't use Visual Studio, or if you've another version and if the project doesn't load, then try to open Program.cs (C#) or Program.vb (VB.NET). The download file contains examples of FlagsAttribute, XOR encryption, the XOR swap algorithm ... The Main method is empty.
Main
In this article, I tell you how bitwise operators work.
All operators in this article:
|
Or
&
And
^
Xor
~
Not
<<
>>
Bitwise operators are used for numbers. Bitwise operators perform an action on the bits of a number, so if you want to understand how bitwise operators work, then you should first learn to convert from decimal to binary and from binary to decimal. I tell you how to do that in Converting from decimal to binary and from binary to decimal.
In this article, I give examples mostly with Bytes. But the examples will also work for other types, such as an Int32 or an Int16
Byte
Int32
Int16
Bitwise operators are used in more languages than C# and VB.NET, but in this article, I give examples in C# and VB.NET.
If you use a bitwise operator, there will be an action performed for each bit in the binary form of the integer. For example 110100112 is 21110. And 14310 is 100011112. In this paragraph, I tell how to convert from decimal to binary and how to convert from binary to decimal.
If we have a decimal number, 783 for example, then we convert it to a decimal number using this way:
You have to stop dividing if the quotient is 0.Now, read the sequence of remainders from right to left, then you get the binary number 1100001111Step-by-step explanation on converting 78310 to a binary number:
To convert a negative decimal number to binary (-783 for example):
UInt16
If you've a binary number 0000000100010110 (Int16 -> first number = 0, positive number), then reverse the order of the bits (then you get 0110100010000000), and use this method:
Now, you have to add up all results:
0 + 2 + 4 + 16 + 0 + 0 + 0 + 256 + 0 + 0 + 0 + 0 + 0 + 0 + 0 = 2 + 4 + 16 + 256 = 278
Step-by-step explanation on converting 00000001000101102 to a decimal number:
The way to convert a negative binary number to decimal (1111111111010011 = Int16 -> first bit = 1, so negative):
If you've two numbers, 38 (Byte) and 53 (Byte) for example, then first we convert these numbers to binary:
38 -> 00100110
53 -> 00110101
38 | 53
38 Or 53
Corresponding table of this method:
If one of the two numbers is a Int16 for example, then one of the two numbers may be negative. If the sign of the first Int16 is 0 (positive), and the sign of the second number is 1 (negative), then the sign in the result will be 1. So, -15 | 378 (-15 Or 378 in VB.NET) is -5.C# and VB.NET code for an OR operator:
-15 | 378
-15 Or 378
byte inclusiveOrExample = 38 | 53; // change 'byte' into the data type which you need
Dim inclusiveOrExample As Byte = 38 Or 53 ' change "byte" into the data type which you need
You can treat an enum as a bit field using a FlagsAttribute[^]. In an enum with a FlagsAttribute, you should set the first value to 1, the second value to 2, the third value to 4, the fourth value to 8 ... Set "None" to 0.
FlagsAttribute
[Flags]
public enum Priority
{
None = 0,
VeryLow = 1,
Low = 2,
Medium = 4,
High = 8,
VeryHigh = 16
}
<Flags>
Public Enum Priority
None = 0
VeryLow = 1
Low = 2
Medium = 4
High = 8
VeryHigh = 16
End Enum
Now, you can combine the enum values using the OR operator:
Priority p = Priority.Medium | Priority.High;
Console.WriteLine(p.ToString());
// output: Medium, High
Dim p As Priority = Priority.Medium Or Priority.High
Console.WriteLine(p.ToString())
' output: Medium, High
The output will be Medium, High because I use a FlagsAttribute. If I remove the [Flags] (<Flags> in VB.NET), then the output will be 12. Important note: if you also want to declare a value "MediumHigh", then the value "MediumHigh" should be Medium | High (Medium Or High in VB.NET).
Medium, High
[Flags]
<Flags>
12
Medium | High
Medium Or High
If you've two numbers, 76 and 231 for example, then first we convert these numbers to bytes:
76 -> 01001100
231 -> 11100111
76 & 231
76 And 231
A & B (A And B in VB.NET) will be negative if A and B are both negative, otherwise, A & B (A And B) will be positive.
C# and VB.NET implementation of the AND operator:
A & B
A And B
byte andOperatorExample = 76 & 231; // change 'byte' into the data type which you need
Dim andOperatorExample As Byte = 76 And 231 ' change "Byte" into the data type which you need
The Exclusive OR operator is not the same as the Inclusive OR operator. If you use an Inclusive OR, 1 | 1 (1 Or 1 in VB.NET) is 1. But if you use an XOR operator, 1 ^ 1 (1 Xor 1 in VB.NET) is not 1, but 0. Only 0 ^ 1 (0 Xor 1 in VB.NET) and 1 ^ 0 (1 Xor 0 in VB.NET) return 1.
1 | 1
1 Or 1
1
1 ^ 1
1 Xor 1
0
0 ^ 1
0 Xor 1
1 ^ 0
1 Xor 0
If you have two numbers, 138 and 43 for example, then use this way to calculate 138 ^ 43 (138 Xor 43 in VB.NET):
138 ^ 43
138 Xor 43
138 -> 10001010
43 -> 00101011
Corresponding table of this method:
C# and VB.NET implementation of the Exclusive OR (XOR) operator:
byte exclusiveOrExample = 138 ^ 43 // change 'byte' into the data type which you need
Dim exclusiveOrExample As Byte = 138 Xor 43
With the XOR swap algorithm[^], you can swap the values of two variables (having the same data type) without using a temporary variable.
int x = 31643; // you can choose another data type
int y = 134;
x ^= y;
y ^= x;
x ^= y;
Console.WriteLine(x);
Console.WriteLine(y);
// output: 134
// 31643
Dim x As Integer = 31643
' you can choose another data type
Dim y As Integer = 134
x = x Xor y
y = x Xor y
x = x Xor y
Console.WriteLine(x)
Console.WriteLine(y)
' output: 134
' 31643
With the XOR operator, you can encrypt some text. Iterate over all characters, and the new (encrypted) character is c ^ k (c Xor k in VB.NET). c is the int value of the current char, k is the int value of a key.
c ^ k
c Xor k
c
k
string msg = "This is a message.";
char k = '.'; // For example, use '.' as key. You can also use another key.
StringBuilder sb = new StringBuilder();
foreach (char c in msg)
{
sb.Append((char)(c ^ k));
}
Console.WriteLine(sb.ToString());
Dim msg As String = "This is a message."
Dim k As Char = "."C
' For example, use '.' as key. You can also use another key.
Dim sb As New StringBuilder()
For Each c As Char In msg
sb.Append(ChrW(AscW(c) Xor AscW(k)))
Console.WriteLine(sb.ToString())
The output is zFG]♫G]♫O♫CK]]OIK. This is simple to break using frequency analysis[^]. So, don't use one char as a key, but a string:
zFG]♫G]♫O♫CK]]OIK
char
string
string msg = "This is a message.";
string k = "97k/ -X.O"; // you can choose another key
StringBuilder sb = new StringBuilder();
for (int i = 0; i < msg.Length; i++)
{
sb.Append((char)(msg[i] ^ k[i % k.Length]));
}
Console.WriteLine(sb.ToString());
Dim msg As String = "This is a message"
Dim k as String = "97k/ -X.O"
Dim sb As New System.Text.StringBuilder()
For i As Integer = 0 To msg.Length - 1
sb.Append(ChrW(AscW(msg(i)) Xor AscW(k(i Mod k.Length))))
Console.WriteLine(sb.ToString())
The output is m_☻\ D+♫.↓Z♫\SL?Ka. Now, you can't break this using frequency analysis. But your application can be decompiled and if someone knows the key, then it's easy to decrypt your message. So, don't use only XOR encryption to encrypt a message. Anyway, if you're interested in security and encryption, you can use XOR encryption as a part of your encryption algorithm.
m_☻\ D+♫.↓Z♫\SL?Ka
The bitwise NOT operator inverts each bit in a sequence of bits. A 0 becomes a 1, and a 1 becomes a 0. If the data type is a signed data type, a positive number becomes a negative number, and a negative number becomes a positive number. If the data type is a unsigned data type, a positive number stays positive. If you've a number, 52 for example (00110100 in binary, and a Byte, unsigned data type, so it's positive), then calculate ~52 (Not 52 in VB.NET) using this way:
~52
Not 52
Convert 11001011 to a decimal number, then you get 203. So, ~52 (as a Byte) is 203.The NOT operator in C# and VB.NET:
byte b = 52;
byte notB = (byte)~b; // returns 203
Int16 int16NotB = (Int16)~b; // returns -53
Dim b As Byte = 52
Dim notB As Byte = Not b ' returns 203
Dim int16NotB As Int16 = CShort(Not b) ' returns 203
In C#, if you convert ~b to a short (Int16), then you get -53. But if you convert Not b to an Int16 in VB.NET, then you get 203. Why? I tried (~b).GetType() in C#, and I got System.Int32. I tried (Not b).GetType() in VB.NET, and I got System.Byte. So, the standard data type of an inversed byte is Int32 in C#, and Byte in VB.NET. In this table, I calculate (Int16)~52:
~b
Not b
(~b).GetType()
System.Int32
(Not b).GetType()
System.Byte
(Int16)~52
Convert 1111111111001011 to a decimal number (Int16 = signed data type, first bit is 1, so negative), and the result is -53. So, (Int16)~52 is -53.
x << n (a Left Shift) shifts all bits in x n places to left, and the empty bit-positions are filled with zeros.
As you can see on the image, all bits are moved one place to left, and the empty bit-position is filled with a zero. So, 154 << 1 is 52. Important note: if you've a signed data type, then the sign will be preserved.
5 << 2 shifts all bits in the binary form of 5 (00000101) two places to left: 00010100 (binary form of 2010). So, 5 << 2 is 20. A table on calculating 154 << n:
154 << 1
52
5 << 2
154 << n
The Left Shift operator in C# and VB.NET:
byte b1 = 154;
byte b2 = (byte)(b1 << 1);
Console.WriteLine(b2); // output: 52
Dim b1 As Byte = 154
Dim b2 As Byte = b1 << 1
Console.WriteLine(b2) ' output: 52
1 << n returns 2n, but calculating powers of 2 using the Left Shift is faster than using the Math.Pow method:
1 << n
2n
Math.Pow
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
byte pow = 1 << 7;
sw.Stop();
Console.WriteLine(sw.Elapsed.TotalMilliseconds); // output: 0.0012 (may differ)
sw.Reset();
sw.Start();
byte mathPow = (byte)Math.Pow(2, 7);
sw.Stop();
Console.WriteLine(sw.Elapsed.TotalMilliseconds); // output: 0.0057 (may differ)
Dim sw As New System.Diagnostics.Stopwatch()
sw.Start()
Dim pow As Byte = 1 << 7
sw.[Stop]()
Console.WriteLine(sw.Elapsed.TotalMilliseconds)
' output: 0.0012 (can differ)
sw.Reset()
sw.Start()
Dim mathPow As Byte = CByte(Math.Pow(2, 7))
sw.[Stop]()
Console.WriteLine(sw.Elapsed.TotalMilliseconds)
' output: 0.0077 (can differ)
x >> n (a Right Shift) shifts all bits in x n places to right, and the empty bit-positions are filled with zeros.
As you can see on the image, all bits are moved one place to right, and the empty bit-position is filled with a zero. So, 155 >> 1 is 77. Important note: if you've a signed data type, then the sign will be preserved.
155 >> 1
77
A table on calculating 155 >> n:
The Right Shift operator in C# and VB.NET:
byte b1 = 155;
byte b2 = (byte)(b1 >> 1);
Console.WriteLine(b2); // output: 77
Dim b1 As Byte = 155
Dim b2 As Byte = b1 >> 1
Console.WriteLine(b2) ' output: 77
x >> n is equal to x / 2n. For example, 8 >> 2 is equal to 8 / 22 and that is equal to 8 / 4 and that is equal to 2. So, 8 >> 2 is 2.
x >> n
x / 2n
8 >> 2
8 / 22
8 / 4
2
byte b = (byte)(8 >> 2);
Console.WriteLine(b); // output: 2
Dim b As Byte = 8 >> 2
Console.WriteLine(b) ' output: 2
This is also faster than 8 / Math.Pow(2, 2);
8 / Math.Pow(2, 2);
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
byte divisionUsingRightShift = 8 >> 2;
sw.Stop();
Console.WriteLine(sw.Elapsed.TotalMilliseconds); // output: 0.0016 (may differ)
sw.Reset();
sw.Start();
byte divisionUsingMathPow = (byte)(8 / Math.Pow(2, 2));
sw.Stop();
Console.WriteLine(sw.Elapsed.TotalMilliseconds); // output: 0.0073 (may differ)
Dim sw As New System.Diagnostics.Stopwatch()
sw.Start()
Dim divisionUsingRightShift As Byte = 8 >> 2
sw.[Stop]()
Console.WriteLine(sw.Elapsed.TotalMilliseconds) ' output: 0.0016 (may differ)
sw.Reset()
sw.Start()
Dim divisionUsingMathPow As Byte = CByte(8 / Math.Pow(2, 2))
sw.[Stop]()
Console.WriteLine(sw.Elapsed.TotalMilliseconds) ' output: 0.0102 (may differ)
A Circular Left Shift shifts all bits in b n places to left, and fills the last bit with the first bit (of the byte before shifting).
The image shows 154 circularleftshift 1. 154 circularleftshift 1 is (for a byte) equal to 154 << 1 | 154 >> 7, and a circularleftshift n is equal to a << n | a >> (b - n). b is the count of bits. So, for a byte, the formula is a << n | a >> (8 - n), and for an Int32, the formula is a << n | a >> (32 - n).
The circular left shift in C# and VB.NET (for a byte):
b
154 circularleftshift 1
byte
154 << 1 | 154 >> 7
a circularleftshift n
a << n | a >> (b - n)
a << n | a >> (8 - n)
a << n | a >> (32 - n)
static byte CircularLeftShift(byte a, byte n)
{
return (byte)(a << n | a >> (8 - n));
}
// Usage:
byte b1 = CircularLeftShift(154, 1); // calculates 154 circularleftshift 1
// value of b1: 53
byte b2 = CircularLeftShift(154, 2); // calculates 154 circularleftshift 2
// value of b2: 106
Private Function CircularLeftShift(a As Byte, n As Byte) As Byte
Return CByte(a << n Or a >> (8 - n))
End Function
' Usage:
Dim b1 As Byte = CircularLeftShift(154, 1) ' calculates 154 circularleftshift 1
' value of b1: 53
Dim b2 As Byte = CircularLeftShift(154, 2) ' calculates 154 circularleftshift 2
' value of b2: 106
A Circular Right Shift shifts all bits in b n places to right, and fills the first bit with the last bit (of the byte before shifting).
The image shows 155 circularrightshift 1. 155 circularrightshift 1 is (for a byte) equal to 155 >> 1 | 154 << 7, and a circularrightshift n is equal to a >> n | a << (b - n). b is the count of bits. So, for a byte, the formula is a >> n | a << (8 - n), and for an Int32, the formula is a >> n | a << (8 - n).
The circular right shift in C# and VB.NET (for a byte):
155 circularrightshift 1
155 >> 1 | 154 << 7
a circularrightshift n
a >> n | a << (b - n)
a >> n | a << (8 - n)
static byte CircularRightShift(byte a, byte n)
{
return (byte)(a >> n | a << (8 - n));
}
// Usage:
byte b1 = CircularRightShift(155, 1); // calculates 155 circularrightshift 1
// value of b1: 205
byte b2 = CircularRightShift(155, 2); // calculates 155 circularrightshift 2
// value of b2: 230
Private Function CircularRightShift(a As Byte, n As Byte) As Byte
Return CByte(a >> n Or a << (8 - n))
End Function
' Usage:
Dim b1 As Byte = CircularRightShift(155, 1) ' calculates 155 circularrightshift 1
' value of b1: 205
Dim b2 As Byte = CircularRightShift(155, 2) ' calculates 155 circularrightshift 2
' value of b2: 230. | http://www.codeproject.com/Articles/544990/Understand-how-bitwise-operators-work-Csharp-and-V?fid=1827932&df=90&mpp=10&sort=Position&spc=None&select=4529723&tid=4584997 | CC-MAIN-2015-14 | refinedweb | 2,681 | 65.22 |
Editor.)
Tomcat (available from), the reference Web server for servlets and JSP, has become more attractive to Ant developers since it comes with custom Ant tasks for deployment. Copy the file server/lib/catalina-ant.jar from your Tomcat 5 installation into the lib directory of your Ant installation to use these tasks.
The Tomcat
deployment tasks are
deploy,
reload, and
undeploy; to use
them, add these
taskdef elements (discussed in
Chapter 11) to your build file:
<taskdef name="deploy" classname="org.apache.catalina.ant.DeployTask"/> <taskdef name="reload" classname="org.apache.catalina.ant.ReloadTask"/> <taskdef name="undeploy" classname="org.apache.catalina.ant.UndeployTask"/>
To use these
tasks, you'll need manager privileges with Tomcat;
edit conf/tomcat-users.xml to add manager
privileges for a username (
admin here) and
password like this:
<?xml version='1.0' encoding='utf-8'?> <tomcat-users> <role rolename="manager"/> <role rolename="role1"/> <role rolename="tomcat"/> <user username="admin" password="password" roles="manager"/> <user username="role1" password="tomcat" roles="role1"/> <user username="tomcat" password="tomcat" roles="tomcat"/> <user username="both" password="tomcat" roles="tomcat,role1"/> </tomcat-users>
You can use the
deploy task to deploy a web application to Tomcat
from Ant like this:
<target name="install"> <deploy url="${manager.url}" username="${manager.username}" password="${manager.password}" path="${app.path}" localWar="{build}"/> </target>
Here,
manager.url is
the URL of the Tomcat manager servlet. The default name for this
servlet is "manager", so this is
something like. The
app.path property holds the context path at which
this application should be deployed (usually
/
plus the name of the application as you want to use it in the URL to
access the application online). The
build property
holds the location at which you build the Web application as it
should be installed in the Tomcat
webapps
directory.
If you have installed an application
and want Tomcat to recognize you have updated Java classes, use the
reload task instead:
<target name="reload"> <reload url="${manager.url}" username="${manager.username}" password="${manager.password}" path="${app.path}"/> </target>
To remove a
Web application, use the
undeploy task:
<target name="remove"> <undeploy url="${manager.url}" username="${manager.username}" password="${manager.password}" path="${app.path}"/> </target>
More often than not, you
won't be developing your applications on the same
server you want to deploy to. You can deploy to a Tomcat installation
running on a remote server by contacting the Tomcat manager servlet
via URL in a browser. To do that in Ant you use the
get task, which gets a file when you pass it a
URL. If you're using Java 1.4 or later, this task
supports any URL schema, including http:, ftp:,
jar:, and https:. This task is great if you want to
download online content, or, as in this case, issue commands via URLs
to online code.
Before getting to deployment, here's an example that
uses
get to retrieve the Ant home page and stores
it in ant.html:
<get src="" dest="ant.html"/>
You can upload Web applications to Tomcat using the manager servlet, passing the local location of the Web application to upload. For example, to upload a Web application from C:/ant/ch08/app in Windows, you'd use this location::\ant\ch08\app/
To
upload a .war file, you add an
! at the end of the location to indicate
you're uploading a file, not the contents of a
directory, like this in Unix:
jar:
Example 8-3 shows how this works
in practice. In this case, the build file deploys a Web application
from C:\ant\deploy\app that consists of a
servlet (
org.antbook.ch08.Deploy) that displays
the message "Project Deployment!"
to Tomcat. Here's the URL you pass to the
get task to tell the Tomcat manager servlet what
you want to do: war=:\ant\deploy\app/
You can see this at work in Example 8-4.
<?xml version="1.0" encoding="UTF-8" ?> <project default="main" basedir="."> <property name="tomcat.port" value="8080" /> <property name="tomcat.username" value="admin" /> <property name="tomcat.password" value="password" /> <target name="main" > <get src=" war=:\ant\deploy\app/" dest="deploy.txt" username="${tomcat.username}" password="${tomcat.password}" /> </target> </project>
Here's what the build file looks like in action:
%ant Buildfile: build.xml main: [get] Getting:? path=/deployment&war=:\ant\ch08\get\app/ BUILD SUCCESSFUL Total time: 1 second
Here's what Tomcat wrote to the output file, deploy.txt:
OK - Deployed application at context path /deployment
After deployment, navigating to shows the deployed servlet, as seen in Figure 8-1.
Figure 8-1. Deploying to Tomcat
TIP: For more information on using the Tomcat manager servlet, look at manager/html-manager-howto.html in your Tomcat installation.
The
attributes of the
get task appear in Table 8-4.
TIP: When the
verboseoption is on, this task will display a dot (.) for every 100 KB received.
When deploying to servers, the
jspc task can be useful. This task runs the
JavaServer Pages compiler and turns JSP pages into Java source, which
you can compile with the
javac task. Compiling JSP
pages supports fast invocation of JSP pages, deployment on servers
without the complete JDK, or lets you check the syntax of pages
without deploying them. By default, this task uses the Jasper JSP
compiler, which comes with Tomcat. Copy Tomcat's
jasper-compiler.jar and
jasper-runtime.jar files into the Ant
lib directory to use this task.
You'll need servlet.jar, which
comes with Tomcat, in the Ant lib directory.
For example, say you have this JSP page, greeting.jsp:
<HTML> <HEAD> <TITLE>Creating a Greeting</TITLE> </HEAD> <BODY> <H1>Creating a Greeting</H1> <% out.println("Hello from JSP!"); //Display the greeting %> </BODY> </HTML>
Example 8-5 shows how to compile this JSP into greeting.java.
<?xml version="1.0" ?> <project default="main"> <property name="message" value="Compiling the JSP...." /> <property name="src" location="source" /> <property name="output" location="bin" /> <target name="main" depends="init, compile"> <echo> ${message} </echo> </target> <target name="init"> <mkdir dir="${output}" /> </target> <target name="compile"> <jspc srcdir="${src}" destdir="${output}" package="org.antbook.jsp" verbose="9"> <include name="**/*.jsp" /> </jspc> </target> </project>
Here's what you see when you run the build file:
%ant Buildfile: build.xml init: compile: [jspc] Compiling 1 source file to /home/steven/ant/ch08/jspc/bin/org/antbook/jsp [jasperc] 2004-06-30 02:20:09 - Class name is: greeting [jasperc] 2004-06-30 02:20:09 - Java filename is: /home/steven/ant/ch08/jspc/bin/org/antbook/jsp/greeting.java [jasperc] 2004-06-30 02:20:09 - Accepted org.apache.jasper.compiler.Parser$Scriptlet at /greeting.jsp(7,4) [jasperc] 2004-06-30 02:20:09 - Compiling with: -encoding UTF8 main: [echo] [echo] Compiling the JSP.... [echo] BUILD SUCCESSFUL Total time: 3 seconds
And this is what the resulting Java code, greeting.java, looks like:
package org.antbook.jsp.; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import org.apache.jasper.runtime.*; public class greeting extends HttpJspBase { static { } public greeting( ) { } private static boolean _jspx_inited = false; public final void _jspx_init( ) throws org.apache.jasper.runtime.JspException { } public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { JspFactory _jspxFactory = null; PageContext pageContext = null; HttpSession session = null; . . . out.println("Hello from JSP!"); //Display the greeting . . . } }
Here's another example,
which compiles JSP pages, checks the dependencies, and uses the
javac task to create the actual bytecode for this
JSP:
<jspc destdir="temp" srcdir="${src}" package="org.antbook.ch08"> <include name="**/*.jsp" /> </jspc> <depend srcdir="temp" destdir="${bin}" classpath="lib/app.jar"/> <javac srcdir="temp" destdir="${bin}" classpath="lib/app.jar" />
You can see the attributes of the
jspc task in
Table 8-5.
The
jspc task is
a directory-based task, so the JSP files to be compiled are located
the same way as the
javac task locates files,
which means you can use nested elements, such as
includes and
excludes. You can
use nested
classpath and
classpathref elements, as well as nested
webapp elements. The
webapp
element, unique to the
jspc task, instructs the
JSP compiler to build an entire Web application. The one attribute of
the
webapp element is the
basedir attribute, which sets the base directory
of the application. The base directory must have a
WEB-INF subdirectory beneath it. If you use this
element, the task uses the compiler for all dependency checking.
Here's an example using
webapp:
<jspc package="org.antbook.ch08"> <include name="**/*.jsp" /> <webapp basedir="${ch08}" /> </jspc>
Fundamentally, deploying to Enterprise JavaBean (EJB) application servers is similar to other Ant deployment projects you've seen. You can use the tasks covered to package and deploy EJB applications. For example, you can see a build file developed for the JBoss server in Example 8-6; this build file first creates a .war file and then packages it into an .ear file for deployment.
<?xml version="1.0" ?> <project default="main" basedir="."> <target name="main" depends="init, compile, war, ear"/> <target name="init"> <property name="src" value="${basedir}/src"/> <property name="bin" value="${basedir}/output"/> <property name="web" value="${basedir}/web"/> <property name="descriptors" value="${basedir}/output/deploymentdescriptors"/> <property name="eardir" value="${basedir}/output/ear"/> <property name="wardir" value="${basedir}/output/war"/> <property name="warfile" value="app.war"/> <property name="earfile" value="app.ear"/> <mkdir dir="${wardir}/WEB-INF"/> <mkdir dir="${wardir}/WEB-INF/classes"/> <mkdir dir="${eardir}/META-INF"/> </target> <target name="compile"> <javac destdir="${bin}" srcdir="${src}" includes="**/*.java" /> </target> <target name="war"> <copy todir="${wardir}"> <fileset dir="${web}" includes="**/*.*" /> </copy> <copy file="${descriptors}/web.xml" todir="${wardir}/WEB-INF" /> <copy todir="${wardir}/WEB-INF/classes"> <fileset dir="${bin}" includes="**/*.class" /> </copy> <jar jarfile="${eardir}/${warfile}" basedir="${wardir}" /> </target> <target name="ear"> <copy file="${descriptors}/application.xml" todir="${eardir}/META-INF" /> <jar jarfile="${basedir}/${earfile}" basedir="${eardir}" /> </target> </project>
That's all it takes. Though this build file gets the
job done using standard Ant tasks, tasks built into Ant make it
easier to work with EJB applications, starting with the
ear task.
The
ear task is handy for creating
.ear files and makes special provisions for the
application.xml file needed in most EARs.
It's not mandatory to use this task to create a
.ear file, but it can make life easier. You can
see the attributes of this task in Table 8-6.
TIP: The
eartask is an extension of the Jar task with special treatment for application.xml. You can perform the same operation by using the
prefixand
fullpathattributes of zipfilesets in a
zipor
jartask.
The extended
zipfileset element from the
zip
task, which supports the attributes
prefix,
fullpath, and
src, is available
in the
ear task. The nested
metainf element specifies a fileset; all files
included in this fileset will end up in the
META-INF directory of the
.ear file.
This task lets you specify where to get
application.xml from, using the
appxml attribute. Here's an
example that creates an .ear
file:
<ear destfile="${output}/app.ear" appxml="${src}/application.xml"> <fileset dir="${wardir}" includes="*.war"/> </ear>
The
serverdeploy task
is designed to support hot deployment (where you
don't have to take the server down before deploying)
to EJB-aware servers. You set the
action attribute
to values you've seen, like those used for the
Tomcat manager servlet: "deploy",
"delete", and
"undeploy".
TIP: You'll need vendor-specific deployment software to make this one work. Ant provides the build-end, but your server will need to provide a deployment facility that Ant can connect and interact with.
As of this writing, this task only supports Weblogic servers and the JOnAS 2.4 Open Source EJB server, but support for other EJB containers should be added soon. This task has only two attributes, which appear in Table 8-7, and requires some nested elements.
The
serverdeploy task
supports a nested
classpath element to set the
classpath. It supports the vendor-specific
generic,
jonas, and
weblogic nested elements.
This is the element you use for generic
Java-based deployment if you've got deployment codea
Java classsupplied by the server's vendor. If
there's a vendor-specific element for
serverdeploy, use that, of course, but if not, try
the
generic element. The attributes of this
element appear in Table 8-8.
The
generic element
supports nested
arg and
jvmarg
elements. Here's an example using the
generic element for deployment that assumes the
deployment tool for the target Web server is
org.steven.j2ee.config.Deploy:
<serverdeploy action="deploy" source="${eardir}/app.ear"> <generic classname="org.steven.j2ee.config.Deploy" classpath="${classpath}" username="${user.name}" password="${user.password}"> <arg value="-install"/> <jvmarg value="-mx512m"/> </generic> </serverdeploy>
The
weblogic element is designed to run the
weblogic.deploy deployment tool; legal actions for
this tool are
deploy,
undeploy,
list,
update, and
delete. The attributes for this element appear in
Table 8-9.
Here's an example using
this element inside a
serverdeploy element to
deploy to a WebLogic server:
<serverdeploy action="deploy" source="${eardir}/app.ear"> <weblogic application="app" server="ff19://server:7001" classpath="${weblogic.home}/lib/weblogic.jar" username="${user.name}" password="${user.password}" component="appserver,productionserver" /> </serverdeploy>
The
jonas element
supports deployment to JOnAS (Java Open Applicaton Server) servers.
Valid actions for the JOnAS deployment tool
(
org.objectweb.jonas.adm.JonasAdmin
)
are
deploy,
undeploy,
list and
update. The attributes of this element appear in
Table 8-10.
TIP: If you want to build in delay times to take into account delays in getting responses from a server, use the Ant
waitfortask. You can use the
sleeptask for this purpose.
The
jonas element
supports nested
classpath,
arg,
and
jvmarg elements. Here's an
example using
serverdeploy to deploy to a JOnAS
server:
<serverdeploy action="deploy" source="${eardir}/app.jar"> <jonas server="JOnAS5" jonasroot="${jonas.root}"> <classpath> <pathelement path="${jonas.root}/lib/RMI_jonas.jar"/> </classpath> </jonas> </serverdeploy>
Steve Holzner is the author of O'Reilly's upcoming Eclipse: A Java Developer's Guide.
Return to ONJava.com. | http://www.onlamp.com/lpt/a/5831 | CC-MAIN-2015-18 | refinedweb | 2,338 | 50.12 |
Have a long running set of discrete tasks: parsing 10s of thousands of lines from a text file, hydrating into objects, manipulating, and persisting.
If I were implementing this in Java, ...
newCachedThreadPool() V/s newFixedThreadPool(...)
when to use and which is better in terms of resource utilisation?
Executor seems like a clean abstraction. When would you want to use Thread directly rather than rely on the more robust executor?
According to Brian Goetz's Java Concurrency in Practice JVM can't exit until all the (nondaemon) threads have terminated, so failing to shut down an Executor could prevent the JVM from exiting.
I.e. ...
Number of tasks (threads) submitted is also not huge in this test scenario.
Say that I have the following code:
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(myRunnable);
myRunnable
RuntimeExcpetion
ThreadFactory
Why, oh why doesn't java.util.concurrent provide a queue length indicators for its ExecutorServices? Recently I found myself doing something like this:
java.util.concurrent
ExecutorService
ExecutorService queue = Executors.newSingleThreadExecutor();
AtomicInteger queueLength = new AtomicInteger();
...
public void addTaskToQueue(Runnable ...
This is some sample code from an example. What I need to know is when call() gets called on the callable? What triggers it?
call()
public class CallableExample {
public static class ...
I have a Java project where I need to run things in parallel. I do this with executors. The thing is, I need to use executors in a great many places. ...
I was trying to run ExecutorService object with FixedThreadPool and I ran into problems.
The trouble was that I expected the program to run in nanoseconds while it hung up on me. ...
I wrote some Java code to learn more about the Executor framework.
Specifically, I wrote code to verify the Collatz Hypothesis - this says that if you iteratively ...
Suppose I have an Executor executor; somewhere in my application. Is it sufficient to just say setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); as usual and let "the system" deal with it, or do I have to ...
Executor executor;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
How does java.util.concurrent.Executor create the "real" thread?
Suppose I am implementing Executor or using any executor service (like ThreadPoolExecutor). How does JVM internally work?
java.util.concurrent.Executor
i have been advised to use Executors.newCachedThreadPool() which will be able to solve problems when over-spawning threads.
However there is still an error when the number of threads is growing past a ...
Executors.newCachedThreadPool()
I started learning java and I am now at the concurrency chapter. After reading some stuff about concurrency I tried an example of my own.
public class Task implements Runnable{
public void run() ...
I am trying to execute a simple calculation (it calls Math.random() 10000000 times). Surprisingly running it in simple method performs much faster than using ExecutorService.
I have read another thread at
Math.random()
Some questions about Executors best usage for memory and time performance:
-1-
Is there any cost penalty from using
ExecutorService e=Executors.newSingleThreadExecutor();
e.execute(callable)
e.shutdown()
new Thread(runnable).start()
I'm new to java concurrency so this may be a question already answered many time over or too obvious that I maybe missing something.
I am running as task like so:
Executors.newSingleThreadExecutor().execute(task)
My question ...
As the question title itself says what is the difference between Executors and ExecutorCompletionService classes in java?
I am new to the Threading,so if any one can explain with a piece of ...
It's not infrequent in my practice that software I develop grows big and complex, and various parts of it use executors in their own way. From the performance point of view ...
Consider the following code snipet:
public class A {
private final Executor executor = Executors.newCachedThreadPool();
private final Queue<Object> messageQueue = new ConcurrentLinkedQueue<M>();
public ...
hi friends, I implemented the concurrent.Executors in my project. to tell my problem consider a program that insert 1000 data into oracle database. instead of inserting 1000 data as a single operations i created 5 threads using the concurrent API. and inserted 200 records per thread. when i analyse the time(in miliseconds) i got the following result, insert the 1000 records ...
Hi all, The API for java.util.concurrent.Executor.execute() says: Executes the given command at some time in the future. The command may execute in a new thread, in a pooled thread, or in the calling thread, at the discretion of the Executor implementation. If the calling thread is the EDT and I need to process something on a separate thread to free the ... | http://www.java2s.com/Questions_And_Answers/Java-Thread/concurrency/executor.htm | CC-MAIN-2013-20 | refinedweb | 753 | 52.05 |
In this C programming class, we’ll cover the C for loop statement, its purpose, syntax, flowchart, and examples. Please note that the loops are the main constructs to implement iterative programming in C.
C For Loop for Beginners
In our previous tutorial, we have learned the functioning of while and do-while loops. In this chapter, we will see the for loop in detail.
We’ve taken up an entire chapter on the “for loop” because it is the most used iterative programming construct. And the programmers use it in almost every program. Hence, let’s start with its explanation.
1. What is For Loop in C Programming?
The For Loop is a loop where the program tells the compiler to run a specific code FOR a specified number of times.
This loop allows using three statements, first is the counter initialization, next is the condition to check it and then there is an increment/decrement operation to change the counter variable. You will understand it once we see some programs.
For starters, this flowchart will help you.
1.1. C For Loop Flowchart
1.2. C For Loop Syntax
for( triad statement ) { //statement block }
The for loop’s triad statement is like the ( i=0 ; i < n ; i++ ).
First comes the initialization of the counter variable.
For example – If the variable is “i” then it needs to be initialized like the following.
i = 0;
Next, there comes a conditional statement separated by a semicolon.
Example: It can be a specific value, or it can be another variable.
"; i < 0; " or "; i >= a; "
The last is the increment/decrement operation again separated by a semicolon.
Example: It goes like the following.
"; i++" or "; i--"
Finally, the C for loop gets the following structure.
for (i = 0; i <= 10; i++) { //Statement block }
Now we will see some examples of this through some programs.
2. C For Loop Examples
2.1. Program-1: Program to find the factorial of a number
Flowchart:
Algorithm:
Step 1: Start. Step 2: Initialize variables. Step 3: Check FOR condition. Step 4: If the condition is true, then go to step 5 otherwise go to step 7. Step 5: f = f * i. Step 6: Go to step 3. Step 7: Print value of factorial. Step 8: Stop.
Code:
#include <stdio.h> #include <conio.h> void main() { int i, a ,f = 1; printf("Enter a number:\n"); scanf("%d", &a); for (i = 1; i <= a; i++) f = f * i ; printf("Factorial of %d is %d\n", a, f); getch(); }
The output of the above example is something like this-
You have two options here. Either you can put {} after for or you cannot. However, if there are multiple statements, then you should put {} so that the code remains organized.
2.2. Program-2: Program to find all numbers between 1 to 100 divisible by 4
Flowchart:
Algorithm:
Step 1: Start Step 2: Initialize variables Step 3: For condition Step 4: If condition. If it is true, then go to step 5 otherwise to step 7 Step 5: Print value Step 6: Increment the value of "i" by 1 Step 7: Go to step 3 Step 8: Stop
Code:
#include<stdio.h> #include<conio.h> void main() { int i; printf("Numbers from 0 to 100 divisible by 4\n"); for(i = 0; i <= 100; i++) { if(i%4 == 0) { printf("%d\t", i); } i++; } getch(); }
Output:
The for loop is very important in C language and will be used very often so you should study this comprehensively. This chapter may have fewer exercises because we expect you to learn the for loop like a snow plower in further tutorials to come. | https://www.techbeamers.com/c-for-loop/ | CC-MAIN-2019-04 | refinedweb | 613 | 73.68 |
This article describes the setting up of the application development environment with VS2015 for Windows Embedded Compact 2013(WEC2013). WEC2013 development can only be done on VS2012/2013/2015.
Install the following software on your development PC.
Application development for WEC2013 could be done with VS2012/2013/2015 and for this article, download and install Visual Studio 2015. Also, the Community Edition of Visual Studio 2015 will work too. As the Community Edition is free in many cases, you can check the (terms for details). Note: On WEC2013 application debugging is done only via an Ethernet connection. Note: WEC2013 is not available for the Colibri PXA Series, Colibri T20 (Nvidia Tegra 2), Apalis TK1(there is no Windows Embedded Compact Support).
Download and install the WEC2013 SDK from here.
The Remote Display Tool allows you to see the display content of the Toradex module. On WEC2013 remote display works over Ethernet only. Download the Remote Display V3 over Ethernet package.
Note: We noticed that the Remote Display V3 (over Ethernet) loses connection as soon as the software keyboard (SIP) appears or disappears from the screen. Remote Display may or may not automatically reconnect. As a workaround, you can disable the SIP by adding a registry key
[HKEY_CURRENT_USER\ControlPanel\SIP] Disabled = dword:1
With this development environment setup is complete.
Make sure you have setup the development environment, only then should you proceed further.
Start Visual Studio 2015.
On the File menu, click New and then Project. The New Project dialog box appears.
In the Templates pane, expand Visual C++ node and select Empty Project from the list of templates.
Specify a name and a location for the application and then click OK. Uncheck the Create directory for solution box.
New empty project on X86 and X64 platform will be created.
#include <windows.h> int wmain(void) { printf("Welcome to Toradex"); return 0; }
For deployment and debugging over Ethernet click on the article Application Debugging Over Ethernet Using Visual Studio for detailed instructions.
You can download the sample project from here.
Note: Debugging and deployment over an Ethernet only works if both, the module and computer, are connected to the same network.
VS2015 does not support WEC2013 VCSharp development. It only support native C/C++ development. | https://developer.toradex.cn/knowledge-base/setting-up-development-environment-with-visual-studio-2015 | CC-MAIN-2019-43 | refinedweb | 375 | 58.38 |
Tech Off Thread6 posts
FxCop advise vs Release Mode Optimisations
Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.
Hello all.
As an exercise, I decided to take an open source library for .NET 1.1 and convert it to .NET 2. (I used SharpZipLib as my test project, as I have previously used NZipLib, its predecessor, and wanted to see what had changed).
After handling all the compiler warnings that a straight upgrade of the SLN file produced, I decided to run FxCop and looked at the performance rules. The main rule that repeated was initialisation of variables to null/0/false. So I modified the code and ran a micro-benchmark (zipping a directory of junk a few times and taking a time lapse).
The original, unmodifed SharpZipLib code was a few seconds slower that the modified version. Great. Or so I thought. I realised that I had run the benchmark in debug mode, so I repeated it in release mode.
The result? No discrenable difference between the two versions.
So what happened? I'm guessing that the optimisations in release mode made to the unaltered code as good as the hand-altered code.
So whats the point in FxCop telling us to make changes that the release optimiser will do for us anyway?
Is there anyone here who knows more about optimisation/benchmarking who could shed light on this?
Herbie
The absolute best place to go read about this is Rico Mariani's blog. He covers loads of performance analysis of .NET and it's absolutely loaded with tips about how to profile things.
It's quite possible, in this case, that SharpZibLib had already been well performance tuned and so there just wasn't much opportunity for improvement.
The SharpZipLib library is well written (there weren't many items in FxCop really).
But the original version ran slower in debug but not in release, which I can't figure out.
It's possible that the manual changes to optimise the code interferred with what the optimiser could do so that the original was optimised in a more efficient manner.
I guess I'll have to try this with other code to see if this one was a fluke.
Show the value of the rule to profile before and after hand optimisation, to see if it's better or worse.
There are a few rules in FxCop that are now redundant due to the optimizations now performed by both the C# compiler and JIT in with optimizations enabled.
Code such as the following which is flagged by DoNotInitializeUnnecessarily:
public class Foo
{
private int _Value = 0;
private string _String = null;
}
Is now optimized out by both the C# compiler and JIT (if the language doesn't do it). This could be why you can see no discrenable difference between the unmodified version and the modified version.
We will probably change this rule so that it no longer fires on .NET 2.0+.
Thanks for the info David.
I think I'll ignore performance rules for .NET 2.0 for the time being and just use profiling after the code is written.
Looking forward to a .NET 2.0 set of rules for FXCop, though.
Herbie
Some performance rules may help you. But profiling is always a good thing. | https://channel9.msdn.com/Forums/TechOff/167789-FxCop-advise-vs-Release-Mode-Optimisations | CC-MAIN-2017-13 | refinedweb | 579 | 63.8 |
digitalmars.D - Modules
- bearophile <bearophileHUGS lycos.com> Feb 01 2008
This comes after a short discussion on the #D IRC channel. The topic is complex, and I don't know all its complexities. Generally I try to talk only about the things I know, so here I don't talk about some things (like packages, etc. For the interested people this may be interesting: ). I think the current way D manages modules has some small problems, despite being usable enough anyway. I think the purposes of a module system like the Python-like D currently has, are: - to manage name spaces - to avoid name clashes and to avoid using the names coming from the wrong name spaces. So the most important qualities it must have are: - It imports as few names as possible from one namespace to another one. Having less names around as possible is generally very good; - it must be very clear to the programmer what names are imported, and where each one of them comes from; - Another quality is the ability to import all names from a name space (a module), this can be useful in particular circumstances (like quick-and-dirty script-like programs) to reduce programming time of small scripts, but such ability can't be the default one. - We have to remember that a module name is a name, like any other function/variable name. So I think something like this: module foo; import somemodule1; import package.somemodule2; has to import only two names in the current namespace: somemodule1 package.somemodule2 So if you want to use what's inside them you have to use: somemodule1.name1 package.somemodule2.name2 If a third module imports foo, like this: import foo; It imports just the "foo" name, and it doesn't contain somemodule1 and package.somemodule2 names. "public import" can be used to allow the presence of the "somemodule1" and "package.somemodule2" names inside the module that has imported "foo". But D conventions have to discourage this practice. A command like: import somemodule1: name1; Has to import just 1 name in the current namespace, "name1", not "somemodule1" name too. Both Python and Java have a way to import all names from another namespace/module: from somemodule1 import * import name1.*; So D can add one of such ways, like: import name1.*; or the commonly used: import name1.all; Or something else still. That command imports in the current namespaces all the names contained in the "name1" namespace, but not the "name1" name itself. D conventions have to discourage this practice in programs more than 30 lines long, but in particular situations it's useful. I think the DMD compiler has to be able to recursively find by itself the modules, like the "bud" tool does, because duplicating the information is generally bad in computer science. In the situations where this behavior isn't appreciated (for example large projects, etc) it can be added a flag to DMD to disable the automatic file retrieval ("bud" has the -explicit and -names flags to manage such things, and I think they work well enough). D 1.x can't be changed now, but 2.x is new so such import semantics can be discussed and improved. Fixing such problems later may become more difficult. Bye, bearophile
Feb 01 2008 | http://www.digitalmars.com/d/archives/digitalmars/D/Modules_65730.html | CC-MAIN-2014-10 | refinedweb | 550 | 62.17 |
22 June 2012 11:15 [Source: ICIS news]
LONDON (ICIS)--European chemical stocks were down on Friday, in line with financial markets, after ratings agency Moody’s downgraded 15 global banks.
On Thursday, the ratings agency downgraded the banks, which included HSBC, Credit Suisse and Barclays, citing significant exposure to market volatility.
Moody's global banking managing director Greg Bauer said all of the banks affected by the downgrades are at risk of outsized losses inherent to capital markets activities.
At 08:29 GMT on Friday, the ?xml:namespace>
With European indices trading lower, the Dow Jones Euro Stoxx Chemicals index was down by 1.98%, as shares in many of
Petrochemical major BASF’s shares were down by 2.27%, while fellow Germany-based chemical company Wacker Chemie’s shares were trading down by 2.58%.
Shares in
Belgium-based Solvay’s shares were trading down by 4.38% from the previous close.
Investor confidence was also hit late on Thursday by concerns over global growth, | http://www.icis.com/Articles/2012/06/22/9571843/europe-chem-stocks-fall-after-moodys-downgrades-15-global-banks.html | CC-MAIN-2014-52 | refinedweb | 167 | 56.05 |
Hello All,
I have very basic knowledge of C and I'm trying to write a program to read a single line from an ASCII data file which has following format
" 1337936.4550 6070317.1261 1427876.7852 APPROX POSITION XYZ"
The problem is the position of line is not fixed. Its different in different files. I know the code is not correct, but this is what I could write
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char name, string[20], *chek = "APPROX"; float x, y, z; printf("\nEnter file name:\t"); scanf("%s", &name); FILE *file; file = fopen(name, "r"); while (string!=chek) { fscanf(file, "%0.4f %0.4f %0.4f %s", &x, &y, &z, &string); if(string==chek) { printf("\n%f %f %f %s\t", x, y, z, string); } else printf("\nLife Sux"); } fclose(file); }
Now when I compile it in Unix I get
1readtest.c: In function `main':
1readtest.c:17: warning: passing arg 1 of `fopen' makes pointer from integer without a cast
If I run it anyway, I get "Segmentation Fault"
Please help me. I'm very much frustrated and don't want to end up quitting C. | https://www.daniweb.com/programming/software-development/threads/106616/read-from-ascii-file | CC-MAIN-2018-30 | refinedweb | 197 | 82.75 |
I'm using a known package called v-usb. For some reason I'm running in to this error and can't quite understand why? I know the package I'm using is good as I have an example that compiles. I tried to find any difference in the good and the bad but see nothing.
Here is the code that causes the error.
#ifndef __ASSEMBLER__ extern #if !(USB_CFG_DESCR_PROPS_DEVICE & USB_PROP_IS_RAM) PROGMEM #endif char usbDescriptorDevice[];
If I do this.
#ifndef __ASSEMBLER__ extern #if !(USB_CFG_DESCR_PROPS_DEVICE & USB_PROP_IS_RAM) char i;//just some dummy code. #endif char usbDescriptorDevice[];
it passes the issue and on the the next define. not sure why the PROGMEM would be an issue. I'm sure there is nothing wrong with the code itself but I'm so baffled as to what would cause this. Maybe a make file switch? I can't really post much of the code as these files are quite big.
Here is the error
usbdrv/usbdrv.h:452: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'char'
I get about 10 of them.
Does it have to do with the char not being used right not going in to eprom memory? Here is how its used.
const char usbDescrDevice[] PROGMEM = { /* USB device descriptor */ 18, /* sizeof(usbDescrDevice): length of descriptor in bytes */ USBDESCR_DEVICE, /* descriptor type */ 0x01, 0x01, /* USB version supported */ USB_CFG_DEVICE_CLASS, USB_CFG_DEVICE_SUBCLASS, 0, /* protocol */ 8, /* max packet size */ USB_CFG_VENDOR_ID, /* 2 bytes */ USB_CFG_DEVICE_ID, /* 2 bytes */ USB_CFG_DEVICE_VERSION, /* 2 bytes */ #if USB_CFG_VENDOR_NAME_LEN 1, /* manufacturer string index */ #else 0, /* manufacturer string index */ #endif #if USB_CFG_DEVICE_NAME_LEN 2, /* product string index */ #else 0, /* product string index */ #endif #if USB_CFG_SERIAL_NUMBER_LENGTH 3, /* serial number string index */ #else 0, /* serial number string index */ #endif 1, /* number of configurations */ };
The #endifs are not balanced so that snippet does not make sense.
Top
- Log in or register to post comments
ok let me dump that entire header on here. I think you just need to remove the
#ifndef __ASSEMBLER__
to balance it but this may answer further questions.
Top
- Log in or register to post comments
Don't know about IAR but gcc would want #include
Top
- Log in or register to post comments
wow, that filled in the mystery. I used to have it in main, the newer v-usb put it in usbdrv.h. Now that I'm unsing an old verion of usbdrv.h I need it back in my main. dak664, thx so much for spotting that!
Top
- Log in or register to post comments
Added to widen the display format of the above header file post.
You do realise you could have worked this out for yourself? Almost always when you see the "error: expected '=', ',', ';', 'asm' or '__attribute__' before" it's because a type or attribute has been used for which the compiler has not seen a definition. In this case it was "PROGMEM". Another example would be:
In this case the compiler would throw the error on the line that defines 'n'.
In either case you just need to find where "PROGMEM" or "uint16_t" or whatever is defined. Start by grep'ing the local project .h files as it could be a locally invented type/macro/whatever. If that fails search the system header files:
So here you'd know it was pgmspace.h that needed to be included before the use of the symbol. Similarly:
So it's stdint.h needed for:
Top
- Log in or register to post comments | https://www.avrfreaks.net/forum/error-expected-asm-or-attribute-bef | CC-MAIN-2020-10 | refinedweb | 567 | 65.52 |
Daniel Kobras <kobras@debian.org> writes: >; Thats just plain wrong on 32bit systems. You need an #ifdef construct there already, you have to check the size of long at some point. But keeping it your way, the right[TM] way for such compatibility would be to test for stdint.h in the configure script and then #ifndef HAVE_STDINT typedef long int64_t #endif > foo.pc: > Libs: -L${libdir} -lpthread > > You're trying to shoehorn data into binary-all that is inherently > architecture dependent. foo.pc files aparently are in /usr/lib/, that means they go to /usr/lib64/ for 64bit multiarch. But even though there is no architecture dependend information in your example. That foo.pc file could be copied or linked to both places in the -dev arch: all package. If it realy is architecture dependend move it into the -helper, -static, -whatever package you choose to use for the architecture dependend stuff. And yes that means you have to create that one new package you have to create anyway for multiarch. MfG Goswin | https://lists.debian.org/debian-devel/2004/01/msg01297.html | CC-MAIN-2015-18 | refinedweb | 174 | 65.01 |
Kevin,
Sounds like you have made some good progress using the OpenNETCF
library. It looks like the main benefit is the additional appenders that
can be built for the Compact Framework.
Some of the changes to the Config namespace, in my opinion, are not as
significant improvements as to the Appenders. The
DefaultRepositorySelector and the attributes in the log4net.Config
namespace are not needed unless we can find some way to read assembly
level attributes (or make some sort of equivalent).
There are a few things that we may want to incorporate directly into the
log4net NETCF builds as we have done to provide support for Stack and
Guid. For example support for the WinCE equivalents to
GetCurrentProcess().Id and Environment.MachineName could be added to
SystemInfo.cs.
I don't want to make the log4net assembly dependant on the OpenNETCF
library for build simplicity and potential licensing issues. So I think
that the best solution is to make a new assembly, which does reference
the OpenNETCF library, with just the additional appenders. At the moment
I think the most we can do is to include this assembly (in source form)
as an example, i.e. it would go into examples\netcf\1.0\OpenNETCF.
If that is acceptable to you then the way to contribute code is to
create an issue in the log4net issue tracking system
(). Once the issue has been
created you can attach your patch file to the issue by selecting the
Attach file to this issue operation from the left hand menu. When
attaching your patch you must select the 'Grant license to ASF for
inclusion in ASF works' option.
More details here:
Cheers,
Nicko
> -----Original Message-----
> From: Kevin O'Connor [mailto:koconnor@11.com]
> Sent: 08 November 2005 19:14
> To: Log4NET Dev
> Cc: Sean Going; Shawn Becker
> Subject: RE: Interest in OpenNETCF (1.4)
>
> Hi,
> >
> > I am currently working on a .NET compact framework system.
> > We are making use of OpenNETCF Smart Device Framework (v
> 1.4). I was
> > looking at the log4net project as a potential logging
> utility for this
>
> > system. The OpenNETCF SDF provides support for several areas of the
> > full .NET framework that are not part of the compact
> framework in the
> > area of logging (the OpenNETCF.Diagnostics namespace).
> >
> > I did a quick search of the dev list archives and did not find a
> > reference to OpenNETCF. I am curious if there is anyone
> working on an
>
> > implementation of log4net using OpenNETCF SDF, and if not
> if there is
> > any interest in having it done.
> >
> > Kevin
> >
> > Kevin G O'Connor
> > Eleven Technology ?e: koconnor@11.com
> > 45 Dunster St *p: 617.715.3031
> > Cambridge, MA 02138 (m: 617.834.1291
> > <> *f: 617.876.3704
> >
> >
> >
> >
> >
> | http://mail-archives.apache.org/mod_mbox/logging-log4net-dev/200511.mbox/%3CDDEB64C8619AC64DBC074208B046611C7695CD@kronos.neoworks.co.uk%3E | CC-MAIN-2016-18 | refinedweb | 454 | 65.52 |
Hello friends, if you are reading this blog, I assume that you have gone through the first part of my blog . However, if you haven’t, I suggest you to go through the link before reading this blog.
Now let’s recall the concept of first part of this blog that we are going to implement in this part.
We will create all the components related to this project(as shown in figure above). We will also go through how best we can create spot fleet request wisely by choosing the parameters that fits for our purpose and prone to less interruption. I assume that you have previously created VPC, Subnets(at least two), Internet Gateway and have associated it with VPC, Target Group, AMI(nginx server running at 80), Launch Configuration with the same AMI, ASG with launch configuration you created, and associating the tags for the instance(on-demand), also associating the target group you created, Load Balancer(listening on http protocol and directing to target group you created), route53(optional -where one address is mapped to Load Balancer DNS name).
I have made my server public if you want you can make them private. After this we are going to create IAM role, Spot fleet request, Lambda function, and then Cloudwatch rules for our purpose.
Let’s create IAM Role
We are going to create two IAM roles. One for Lambda and other for Spot Fleet Request.
- Go to IAM console. Select Roles from left side navigation pane.
- Click on Create role and follow the screenshot below.
Here we are creating Role for Lambda function.
- Click on Next:Permissions.
- Check on Administrator access to allow lambda to access all AWS services.
- Click on Next:Tags.
- Add tags if you want, then click on Next:Review.
- Type your Role Name and then click on Create role. Role is created now.
- Now again come to IAM console, select Roles from navigation pane.
- Click on Create Role and then follow screenshot below.
This role is for spot fleet request.
- Follow the steps from 3 to 7.
So, by this point we have two IAM Roles let’s say Lambda_role and Fleet_role .
Now we are going to create interesting part which deals with the process to place spot fleet request and also explains each and every related factors which powers us to customize our spot fleet requests according to your needs wisely.
Create Spot Fleet Request
Move to EC2 dashboard,click on Spot Requests. Then click on Request Spot Instances.
- You will see something like below:
Load Balancing Workloads: For instances of same size in any Availability zone.
Flexible Workloads: For instances of any size in any Availability zone.
Big Data Workloads: For instances of same size in single Availability zone.
Now decide among these three options based on your requirements and if you are just learning then leave the choice to default.
The last option ‘Defined duration workloads’ is a bit different. This option provides you a new way to reserve spot instances but for a maximum of 6 hours only with the choices vary from 1 to 6 hours. This will ensure that you will not be interrupted for 1 to 6 hours after you opted to run your workloads for defined duration and because you won’t be interrupted you will have to pay slightly higher price than the spot instances.
So, for this option AWS has another pricing category called Spot Block. Under this model, pricing is based on the requested duration and the available capacity, and is typically 30% to 45% less than On-Demand, with an additional 5% off during non-peak hours for the region. Observe the differences below.
Let us start with a brief comparison of categories into which we can launch our instances.
2. Next we will configure our spot instances.
Launch Template: If you have ‘Launch Template’ you can select it from here. One advantage of using launch template is you will have an option for choosing a part of your total capacity as on-demand instances. If you don’t have launch template you can go with AMI and specify all other parameters.
AMI: Don’t have launch template?? Choose AMI but with this option you won’t be having features to choose a part of your total capacity as on-demand instances.
Minimum Compute Unit: Specify how much capacity you need either in terms of vCPU and memory or as instance types. As the name suggests this is the minimum capacity that we need for our purpose. AWS will choose similar instances based on this option.
Then, you will have options to choose vpc, Availability zone, key-pair name. On additional configuration you can choose security groups, IAM instance profile, user data, tags and many more configurations.
3. Next section is for defining target capacity.
Total target capacity: Specify how much capacity is needed. If you have chosen launch template then you can specify how much of total capacity you want as on-demand.
Maintain target capacity: Once selecting this feature AWS will always maintain your target capacity.Suppose AWS takes your one instance back then under this option it will automatically place request for one spot-instances in order to maintain target capacity. Selecting this option allows you to modify target capacity even after spot-fleet request has been created.
Maintain target cost for Spot: This option allows you to set the maximum hourly price you want to pay for spot instances and it’s optional.
4. Next section is about customizing your spot fleet request.
If you don’t care much about how AWS is going to fulfill your request leave the things to default and proceed to next step, or else uncheck the ‘Apply recommendations’ field which will appear like below:
As i have chosen c3.large as minimum compute unit, AWS chooses similar instances like c3.large or it can even choose instances with more memory than specified but not lesser under almost similar prices. You can also choose more instances by selecting Select instance types, this will strengthen your probability of getting spot instances. Now let’s see how!
Suppose you ordered for only t2.small instance. You will get that only when this instance is available in the Availability Zone you specified. So to increase your chances, you should specify maximum Availability Zone and maximum instance types which is required for your workload. This will increase the number of pools and ultimately the chances of success.
Picture showing the instance pool an Availability Zone can contain.
Instance Pools: You can say it a bag full of same instance types.
Every Availability Zone contains instance pools. So suppose you choose two availability zones and a total of three instances types. You, then, will have 6 instance pools three from each availability zone. Maximum the number of instance pools, maximum is the chance of getting spot instances.
Fleet allocation strategy: AWS allows you to choose allocation strategy i.e., the strategy through which your capacity is going to be fulfilled. One thing to be considered is that AWS will try to evenly distribute your capacity across your specified availability zones.
Lowest price: Instances will be made available to you from the pools with the Lowest Price. Suppose you choose 2 Availability Zones and your capacity is 6 then 3 instances from each Availability Zone comes from pools with lowest cost.
Diversified across n number of pools: Suppose your capacity is 20 and 2 Availability Zones are selected and also you have chosen diversified across 2 instance pools. So 10 instances from each Availability Zone will be provided with further restriction to choose 2 pools to fulfill the capacity of 10 from each Availability Zone. This will make at least one pool available for you even if the other pool is unavailable and hence reducing the risk of interruption.
Capacity Optimized: This option provides you the instances among those pools which are highly available. Suppose your capacity is 20 and 2 Availability Zones are selected. So 10 instances from each Availability Zone will be provided from the pools which is highly available and is going to be highly available in future too.
5. Next section is for choosing the price and other additional configurations.
First of all, Uncheck the Apply defaults. Then, customize your additional settings under the heads:
IAM fleet role: This role allows you to provide tags to your spot instances. Choose the default one or you can create your own.
Maximum price: This option allows you to choose default maximum price which is on-demand price or to set your maximum price you want to pay for an instance per hour.
Next you can specify your spot fleet request validation. Check Terminate instances on request expire.
Load balancing: If you check Receive traffic from one or more load balancer you will get to choose the classic load balancer under which you want to launch your instance or you can choose the target group under which you want to launch your instance.
This is how you can help yourself customize spot fleet request based on your requirements. Lastly i will advise you to visit the link below once when you are on to deciding your suited instance types. After visiting this link you can make estimates of your saving.
Let’s create Lambda function for our purpose
We are going to create two lambda function for our purpose. Follow the steps below:
- Create an IAM role ready to allow lambda function to modify ASG, i prefer to ready an IAM role with admin permission because we are going to require IAM role many times throughout this project.
- Head to AWS Lambda console. On the left side navigation pane click on function.
- Click on Create function tab.
- Leave the default selection Author from scratch.
- Enter function name of your choice.
- Select Runtime as Python 3.7 .
- Expand Choose or create an execution role and select the role you have created for this project.
- Click on Create function.
- Scroll down and put the below code on lambda_function.py.
Copy code from below
import json import boto3 def lambda_handler(event, context): # TODO implement client = boto3.client('autoscaling') response = client.set_desired_capacity( AutoScalingGroupName='spot', DesiredCapacity=1 )
This code increases the desired capacity of ASG with name ‘spot’ to 1.
This is triggered when AWS issues interruption notice. As a result this launches an on-demand instance to maintain total capacity of two.
10. Upon the upper right corner click on save to save the function and come again to AWS Lambda console and one more time select function and then Create function.
11. Give your function name and execution role same as did previously and select Create function to write code to maintain spot capacity to two always.
12. Refer following snap.
Copy code from below
import boto3 ## Python sdk import json ## In this part code is checking if number of spot instances is >= 2, ##then set ASG desired capacity to 0 to terminate running on-demand instances running. def asg_cap(fleet, od): print('in function',fleet) print('in function',od) if fleet >= 2 and od > 0: client = boto3.client('autoscaling') response = client.set_desired_capacity( AutoScalingGroupName='spot', DesiredCapacity=0 ) ##Beginning of the execution def lambda_handler(event, context): cnt = 0 ec3 = boto3.resource('ec2') fleet = 0 od = 0 instancename = [] fleet_ltime = [] od_ltime = [] for instance in ec3.instances.all(): ##looping all instances print (instance.id) print (instance.state) print (instance.tags) print (instance.launch_time) abc = instance.tags ##get tags of all instances ab = instance.state ##get state of all instances print (ab['Name']) if ab['Name'] == 'running': ## checks for the instances whose state is running cnt += 1 for tags in abc: if tags["Key"] == 'Name': ## checks for tag key is 'Name' instancename.append(tags["Value"]) inst = tags["Value"] print (inst) if inst == 'fleet': ## checks if tag key 'Name' has value 'fleet'. Change 'fleet' to your own tag name fleet += 1 fleet_ltime.append(instance.launch_time) if inst == 'Test': ## checks if tag key 'Name' has value 'Test'. Change 'Test' to your own tag name od += 1 od_ltime.append(instance.launch_time) print('Total number of running instances: ', cnt) print(instancename) print('Number of spot instances: ', fleet) print('Number of on-demand instances: ', od) print('Launch time of Fleet: ', fleet_ltime) print('Launch time of on-demand: ', od_ltime) if od > 0: dt_od = od_ltime[0] else: dt_od = '0' if fleet > 1: dt_spot = fleet_ltime[0] dt_spot1 = fleet_ltime[1] elif (fleet > 0) and (fleet < 2): dt_spot = fleet_ltime[0] dt_spot1 = '0' else: dt_spot = '0' dt_spot1 = '0' if dt_od != '0': if dt_spot != '0': if dt_od > dt_spot: if dt_spot1 != '0': if dt_od > dt_spot1: print('On-Demand instance is Launched') # do nothing else: print('Spot instance is Launched') asg_cap(fleet, od) else: print('Only 1 spot instance exist') else: print('1Spot instance is Launched') asg_cap(fleet, od) else: print('No spot instance exist') else: print('No On-Demand instance exist') ## modify the spot fleet request capacity to two client1 = boto3.client('ec2') response = client1.modify_spot_fleet_request( SpotFleetRequestId='sfr-92b7b2f1-163b-498a-ae7c-7bd1b4fdb227', ##replace with your spot fleet rquest TargetCapacity=2 )
13. Save this function.
Till now we have created two lambda function and now we are going to create Cloudwatch Rules which will call lambda function on interruption and state change to running of ec2 instances on our behalf.
Let’s create Cloudwatch Rules.
Steps to create Cloudwatch Rules.
- Go to Cloudwatch console.
- Select Rules from left side navigation pane.
- Click on Create Rule.
- Follow the screenshot below.
We are creating rules here to trigger on interruption notice by AWS.
On left side there is Targets Area, there select Lambda function and then select the first function which is increasing the desired capacity of ASG to 1.
Save the first Rule.
- Now let’s create another cloudwatch rule.
- Create Rule. Follow screenshot.
After this add target as Lambda function and function name to the one which we created secondly a little lengthy one.
Save the second Rule.
Now to verify this automation go to spot fleet request you created with target capacity two. Select that request, click Action tab and click on Modify capacity and replace 2 with 1 there. This will terminate one spot instance and before that it is going to send interruption notice. Observe the changes on Auto scaling group, instance, and spot request dashboards. Wait for couple of minutes, if everything is right and according to our plan then again you will be having two spot instances under your bag.
If you are not having two spot instances at the end, then something is not right. You need to cross-check to verify:
- Check the name of the Auto scaling group you created. Copy it’s name and now go to the first lambda function you created which increase the desired capacity of ASG to 1 and check if the function contain the correct name of Auto scaling group, if not paste the name you copied against AutoScalingGroupName section.
- Check the tag Name value of spot instances and note somewhere. Also check the tag Name of On-demand instance which you configured while creating Auto scaling group and note that too. Now go to second lambda function you created and go to line number 40, here tag Name value of spot instance is given under single quotes, check if that matches with yours. Now at line number 43 check if tag Name of on-demand instance matches with yours.
- Go to Spot request and copy the spot fleet request id you created and go to line number 94 of the second lambda function and make sure the id under single quotes matches with yours.
Now test again, hopefully it will work now. If still you are facing problem or you have not created manually all the above stuffs then no need to worry.
I have created terraform code which will create the whole infra needed for this project. However after running this terraform code successfully you will have to make some changes so that your infra functions properly and for that you need to follow the steps below. Below is the link of github repository, clone the repo and post that follow the steps stated below:
Link:
- Make sure you have terraform version 0.12.8 installed.
- You must have AWS CLI configured too.
- Before running the terraform code go to the folder where you have cloned the repo, then go to infra-spot/infra/infra and open vars.tf on your favourite editor.
- Go through the files and change the default set values as per your choice.
- Run the terraform apply by moving into the folder infra-spot/infra/infra . Follow last three step to assure your infra is going to automate properly.
- Go to the Lambda function console, select first_function and check if the code contains same Autoscaling group name as the name of the Autoscaling group created with terraform. If not match the same with yours.
- On lambda function console select second_function and repeat the previous step and also check the Tag Name of the on-demand and spot instances, they are ‘Test’ and ‘fleet’ respectively in the terraform code. However you should make sure that the Tag Name of on-demand and spot instances matches with the tag mentioned in code.
- Lastly head on to spot request and note the request id and match with second_function SpotFleetRequestId part.
I believe terraform will do everything right for you. If you are still facing problems, i will be happy to resolve your queries.
Good to know
AWS reports shows that the average frequency of interruptions across all regions and instance types is <5% .
For any instance types on-demand price is maximum and we can bid at a maximum of 10 times of on-demand price.
When you will implement spot instances automation for your project then you will come across different scenario, you might need to monitor more events and trigger action based on that. Unfortunately, cloudwatch do not have all the events of AWS covered. But AWS CloudTrail solve this. CloudTrail knows and covered everything you performed on AWS. To use this on cloudwatch you will have to enable CloudTrail and then you can make a rule with service EC2 and Event Type AWS API Call via CloudTrail and then can add any specific operation that is not present as cloudwatch events. However i recommend you to first go through every details about CloudTrail before implementing that. If you have any queries implementing CLoudTrail, you can ask on comment section. I will be happy to help you.
While implementing spot instances for Database you may configure your spot instances such that volume of instance will not be deleted upon spot instance termination assuring that you are not going to loose any data.
Conclusion
With smart automation and monitoring we can have our production server on spot instances with guaranteed failover and high availability. However one who don’t want to run into any risk or the one who has no proper idea or resource to automate the interruption can plan :
- Half or a portion of the total production server on spot instances.
- Development server on spot instances without any worry.
- QA server over spot instances.
- For more capacity prefer spot instances to ease the load on other main server.
- Prefer irregular short-term task on spot instances.
17 thoughts on “Perfect Spot Instance’s Imperfections | part-II”
Giving this a try. Creating issues in github when as I see them. Thanks!
Would you rather I post the issues I have here? Thanks.
Thanks cmtopinka, you can post your queries or issues here too. I will be happy to help.
I saw you closed your issue on github, you can post your issues you have here too.
LikeLiked by 1 person
Working on experimenting with it as in v0.11 and also upgrading to current 0.12+. Need to make it workspace capable and insert terraform.workspace into names and tags. Not sure what’s going on with the issues I found during upgrade. I closed them because only an issue for upgrade. If I would suggest another issue/feature it would be more generally upgrade for 0.12+ and insert idea of workspace envs. But that’s not something I expect you to work on. When we get it working I’ll submit a pr if that’s ok. Or I can put in the issue and maybe we collaborate on it. Not sure how much commitment we have yet for this. It’s something we are interested in though. Excellent post by the way. I did work on a diagram for it if you are interested I can share it. Thanks!
Can you get to this?
Is it fairly accurate? Some of the questions I planned an answering by experimentation
– what happens with min/max settings
– what happens when fleet size greater than 2
– is fleet spread across zones
– what options are there for fleet request and what’s the best strategy
Could use some suggestion on creating an ami for this. Size, Build component, etc. Thanks
Something like this can work
“`
data “aws_ami” “ubuntu” {
most_recent = true
filter {
name = “name”
values = [“ubuntu/images/hvm-ssd/ubuntu-xenial-16.04-amd64-server-*”]
}
filter {
name = “virtualization-type”
values = [“hvm”]
}
owners = [“099720109477”] # Canonical
}
“`
Yes that works. Getting closer now. Currently have this error: (sorry no code blocks here?)
module.spot_fleet_request.aws_spot_fleet_request.cheap_compute: Still creating… (8m30s elapsed)
module.spot_fleet_request.aws_spot_fleet_request.cheap_compute: Still creating… (8m40s elapsed)
module.spot_fleet_request.aws_spot_fleet_request.cheap_compute: Still creating… (8m50s elapsed)
module.spot_fleet_request.aws_spot_fleet_request.cheap_compute: Still creating… (9m0s elapsed)
module.spot_fleet_request.aws_spot_fleet_request.cheap_compute: Still creating… (9m10s elapsed)
module.spot_fleet_request.aws_spot_fleet_request.cheap_compute: Still creating… (9m20s elapsed)
module.spot_fleet_request.aws_spot_fleet_request.cheap_compute: Still creating… (9m30s elapsed)
module.spot_fleet_request.aws_spot_fleet_request.cheap_compute: Still creating… (9m40s elapsed)
module.spot_fleet_request.aws_spot_fleet_request.cheap_compute: Still creating… (9m50s elapsed)
module.spot_fleet_request.aws_spot_fleet_request.cheap_compute: Still creating… (10m0s elapsed)
Error: Error applying plan:
1 error occurred:
* module.spot_fleet_request.aws_spot_fleet_request.cheap_compute: 1 error occurred:
* aws_spot_fleet_request.cheap_compute: Error requesting spot fleet: Error creating Spot fleet request, retrying: InvalidSpotFleetRequestConfig: Parameter: SpotFleetRequestConfig.ValidUntil is invalid.
status code: 400, request id: 882f7ff7-8c35-4149-9e43-6e8caeaa213e
Is it – ?
Should it be ‘now’ based?
I think this will work
valid_until = “${timeadd(timestamp(), “24h”)}”
Is 24h reasonable?
A more difficult problem…
On subsequent applies I’m getting
Error: Error refreshing state: 1 error occurred:
* module.archivetozip1.data.archive_file.zip1: 1 error occurred:
* module.archivetozip1.data.archive_file.zip1: data.archive_file.zip1: error archiving file: could not archive missing file: od_running.py
attempting destroy at that point results in same error. Workaround is create an empty file and then destroy, then remove the empty file. What’s a fix for this? Thanks
I’d also be interested in hearing how you went about putting this together? Spot fleet first and then built incrementally? Were you able to borrow some pieces. Would be a good story in maybe a 3rd post if you can recall.
!!!!!
module.listner.aws_lb_listener.alb_listing: Creation complete after 0s (ID: arn:aws:elasticloadbalancing:us-east-1:…b-sf/ab386c6d7405898b/245bd0f9d005d934)
Apply complete! Resources: 33 added, 0 changed, 0 destroyed.
!!!!!!!!
Excellent. I can see my spots now in the console. It appears they are the same region? Is it possible to spread them across multiple regions? Or is it good enough to have them in different availability zones?
How can I experiment with this to see the reserve on-demand instance come into action? Is it possible to take down a spot instance intentionally that will trigger the rule?
Going overboard on questions here… Would it make sense to spread the fleet across regions or availability zones? Is it more likely that multiple instances in the same region/zone could be interrupted at the same time due to capacity? And do I care since I have the on-demand reserve? Maybe not. What’s been your experience with the frequency that an on-demand instance is needed? | https://blog.opstree.com/2019/11/12/perfect-spot-instances-imperfections-part-ii/?like_comment=1385&_wpnonce=3349b825d9 | CC-MAIN-2021-21 | refinedweb | 3,980 | 65.52 |
- Advertisement
plywoodMember
Content count248
Joined
Last visited
Community Reputation103 Neutral
About plywood
- RankMember
Eclipse build path blues
plywood posted a topic in For Beginners's ForumI am new to Eclipse and would like to set up a specific directory structure for my packages. For example, for my project MyProj (which uses the default MyProj/src and MyProj/bin for I/O), I want the following structure: com.myproj.core com.myproj.core.utils com.myproj.core.widget com.myproj.testing com.myproj.xml So the 'core' package needs to have two "nested" packages named utils and widget. So I right-click my core package in Package Explorer, go to New >> Package. The dialog that pops up (New Java Package) has 2 textfields and a Browse button. One text field is for defining the Source Folder that the package will live in, the other field is for naming the package. The default values for the Source Folder are MyProj/src, and the default name is already populated as "core". When I try to Browse for another package, it doesn't see anything below MyProj/src, and when I try to manually type in MyProj/src/core it gives me an error of Source folder is not on the build path. I have double-checked to make sure that the core package is properly set up to be a top-level package in the src folder. When I right-click MyProj and go to Build Path >> Configure Build Path, it won't let me add core to the build path, giving me an error of Cannot nest 'MyProj/src/core' ins... exclude 'core/' from MyProj/src What is going on here? I just want to add utils and widget to core!?!?
svn server help
plywood posted a topic in For Beginners's ForumI have never installed SVN before and am trying to use it, but the instructions I've found aren't answering some basic questions. I have successfully configured Subversive inside Eclipse, and my *understanding* is that I can now use the Subversive plugin to browser and manipulate SVN repositories that are either local on my machine, or living remotely on a server. I have a web server with a reputable hosting company, and would like to install svn server on it; this is where I want my repository to live. I figured I could download the server's binary(ies) and then ftp them into the web root where I want them to reside. Then all I should need to do is configure Subversive to point to that URL, credentials and repository, and I should be in business. The only thing I'm leary about is whether or not I can install svn server without contacting their tech support first, but that's a separate issue altogether. The first thing I need to do is *find* the svn server binary. Going to tigris' website, it looks like the project has been adopted/bought by Apache. Since I have both a Windows dev machine and web server, I am limited to a set of 4 or 5 available svn server wrappers (CollabNET, VisualSVN Server, etc.). But I don't think these are what I want: they all seem like client-side GUI apps for controlling your remote svn server, just like Subversive already does. How can I find and install the svn server binaries to my web server (assume this doesn't cause a problem with tech support)? Thanks, ply
- coderx75 - Thanks for the good link, I will start digesting it this weekend! Although I'm very interested in release strategies "best practices", I think everybody is so far ahead of me here, that my real question is being overlooked! All I'm asking is: how does code get migrated from a test server to a production server? Is it really just a copy-n-paste? I would think that there would be some automated check to ensure that only the most current release code gets rolled out to prod, eliminating the possibility of (mistakenly) rolling a 5.0 config back to a 2.3 version (which could very well happen if you have human beings copying and pasting targets between directories, etc.). Let's say, just pretend here!, that we had a SVN repo for our project called myproject. And in this repo were many folders, but only the wombat\ folder contained code that should always be in production. When you're ready to launch, your buildmeister uses SVN move to copy files into wombat\. Now then, how do we update production with the configuration that is in wombat\ ?
- What if I want to do the code migration manually? I'm struggling with how code gets "pushed out" (copied, checked out, whatever the applicable term is!) from one environment to the next. For instance, let's say we were ready for a 1.0 release. The tested code is already in SVN and is ready to get copied/checked out/rolled out from the test server to the production server. How does one do this manually?
How code actually gets "rolled out"
plywood posted a topic in For Beginners's ForumSo, using SVN as an example: "MyProject" has a svn repo called myproject. Inside of this, in keeping with standard SVN/VC practices, I create three folders: trunk\, branches\ and tags\. Let's say the project is a web application and so has a dedicated test server for its "testing" environment, as well as a production server for prod. Code needs to migrate from individual developers' sandboxes (say, Apache running as localhost on each dev machine) to the test server, then on to the production server. My *understanding* is that there is only 1 repo per project regardless of however many environments (sandbox, testing, production, etc.) you have configured. This means that if code is declared as being ready for testing, the buildmaster (or whoever has the appropriate privs) must "move"/"copy"/"checkout" code from, say, branches\dev\ to the project root residing on the appropriate server (test server or prod). How does this "rollout" take place, and similarly, "rollbacks" when unstable code is replaced with a stable, previous version? Does SVN have an "export" tool that allows you to copy/deploy one of its folders (branches\dev) to a particular URL? I'm sure everybody does it differently, so I'm just looking for what the normal procedures are for this. Thanks, ply
Free XML generator for Windows and/or *nix?
plywood replied to plywood's topic in For Beginners's ForumSorry I wasn't clear! I have a schema, let's call its widget.xsd. This schema dictates the formatting for the XML that my application consumes. My application accepts widget.xsd-validated XML ("Widget XML") and uses it. My schema is very complicated and results with fairly large XML files. Writing sample/dummy XML by hand for testing purposes will be tedious and time-consuming. Many commercial XML editors have "XML Generator" features that allow you to point them to a schema (widget.xsd) and will use the rules of that schema to generate dummy XML for testing purposes. I've been looking all day, and can't find any for Windows or Linux that are free - and this is the basis of my original post. Hope this helps! ply
Free XML generator for Windows and/or *nix?
plywood posted a topic in For Beginners's ForumSo I have a very complex XSD and I'd like to generate dummy XML for testing with my application. "Big Applications" like Stylus, Oxygen and Altova all have XML generation features, but they're fairly expensive for a poor, dirt-broke soul such as myself. I'll be needing this tool for a *long time*, so downloading trial versions of these programs really isn't feasible for me. Any open-source or freeware generators you all can recommend? Thanks, ply
Why use bash?
plywood posted a topic in Everything UnixWell, more specifically, why use any shell in favor of a GUI such as Gnome or KDE? I am a *brand new* Linux (Ubuntu) user trying to give Linux an honest chance, and so far, I absolutely love it. I love how easy it is to search for & install applications, the enormous myriad open source tools, the concept of user- and group-ownership over file system object permissions, etc. But for the life of me, I can't figure out what the added benefit is to opening a bash terminal and meticulously keying in "sudo mkdir opt\a\b\c\my\directory" vs. just doing the same thing with a few clicks of a GUI desktop system. I'm sure 40,000 Linux users can't be wrong, so there must be some big benefit to scripting shell commands vs. using visual desktops to do trivial work tasks. But I can't see it, and was hoping a some of you could nudge me in the right direction here. Thanks! ply
[web] Getting the image in the last frame of a SWF file
plywood posted a topic in General and Gameplay ProgrammingI am trying to make some heavy modifications to an open source Flash-based graphing utility called FusionCharts Free. For my particular application, I need a way (in ActionScript) to access the last frame of the animation, and get at the actual image file/pic that was used for that last frame. I am not an ActionScript developer, and all my attempts to find an answer on my own have been futile. The closest methods I was able to find were gotoAndPlay(scene,frame) and gotoAndStop(scene, frame). Both return nothing and simply advanced the playhead to a specific scene or frame. To reiterate, let's say I have 100 images that I want to put into a Flash animation (.SWF file) at the rate of 10 fps (with their being a 1:1 image:frame ratio, of course). Then we would have a 10-second animation, with 10 fps, and in the first second we might see the following images "scroll through": 1. ./images/frame00.gif 2. ./images/frame01.gif 3. ./images/frame02.gif 4. ... 10. ./images/frame09.gif In this example, we might expect the last frame to be ./images/frame99.gif (the 100th image in the 100th frame). I need a way to get at that frame99.gif in ActionScript! Because I'm not an ActionScripter, here is some pseudo-code that summarizes what I need to do; I'm not really worried about the semantics/syntax of AS right now as I'm confident I can figure the mechanics out once I know what methods to call: // Obtain the image file var imageFile = getLastFrame(); Thanks for any suggestions or input - thanks!
[web] CSS nav list for a game website
plywood posted a topic in General and Gameplay ProgrammingHi I'm trying to build a simple website to host my Java game. I have a decent amount of Java/OOP development experience but am very weak when it comes to anything web-related. I know that the modern standard is to make horizontal navigation menus using unordered lists (ul tags) combined with CSS. I've read several tutorials but none of them seem to be working for me. I'm using FF 3.6 over Windows XP (not that the OS really makes a difference, or so I think). I'm trying to create a horizontal menu that has drop-down submenus. Both the menu tabs as well as individual items on each of their submenu are links that bring you to a different page. Here is my HTML: <ul id="tabs"> <li>Menu Tab #1</li> <ul> <li>Submenu Item #1</li> <li>Submenu Item #2</li> </ul> <li>Menu Tab #2</li> <ul> <li>Submenu Item #1</li> <li>Submenu Item #2</li> </ul> </ul> Here is my CSS: ul#tabs { margin: 0; padding: 0; list-style: none; width: 150px; } ul#tabs li { position: relative; list-style-type: none; display: inline; } li ul { position: absolute; left: 149px; top: 0; display: none; } Despite specifying my lists to be "inline" and to have no list-style, what I'm getting is just an indented set of links, but they are still vertical, like lists are set to do by default. My menu tabs ("ul#tabs") are in line with the left border of the page, underneath one another, and each of their submenus are simply indented underneath each respective menu tab, like you would normally get when you put a list inside of another list. Can anybody see anything wrong with my CSS? My HTML? Thanks!
Design pattern check...
plywood replied to plywood's topic in For Beginners's ForumThank you rip-off & OrangyTang. OrangyTang, how would the code look via reflection? Let's say our Widget had a protected int member named xType: public abstract class Widget { protected int xType; // ... } Now let's say, that the doSomething() method in each subclass simply sets xType to a different value, particular to that class. How would we define a reflection-based model in the Widget superclass?
Design pattern check...
plywood posted a topic in For Beginners's Forum[Java] I have an abstract base class and several child classes: public abstract class Widget { // ... public abstract void doSomething(); } public class Fidget extends Widget { // ... public void doSomething() { // ... } } public class Foo extends Widget { // ... public void doSomething() { // ... } } public class Fizz extends Widget { // ... public void doSomething() { // ... } } As you can see, Fidget, Foo and Fizz all extend Widget and override its abstract doSomething() class. In my driver, I need to load and invoke the doSomething() method of a class that is dependent on user input. My solution (so far) has been to create a WidgetFactory class that takes the user input and returns an instance of the appropriate class: int x = getUserInput(); Widget widget = WidgetFactory.getWidget(x); widget.doSomething(); My question is: is this the "correct" way of doing things? If not, what is and why?
[java] Tool recommendations
plywood posted a topic in General and Gameplay ProgrammingI'm looking for a good Java code analyzer, and all my preliminary research has turned back mediocre results for each prospective utility. Here are some things I am looking for: (1) I'd like it to have an eclipse plug-in that is invocable from Ant (2) I'd like good coverage of design-quality metrics (3) Good ratings & user reviews (4) It *must* be open source! (5) I'd like it to be an active project that gets updated regularly; the few good ones I was able to find on my own (JCSC, etc.) haven't been updated in 5+ years I appreciate any and all suggestions! Thanks, ply
Build management example
plywood posted a topic in For Beginners's ForumI'm interested in how learning & using a build management tool (like ant, maven, etc.) can help: (1) make me a better developer, and (2) improve control over my projects. I'm currently reading the Apache Ant tutorial, and for the most part I'm understanding everything just fine... But I'm having a tough time seeing how build systems are really useful as opposed to just compiling my code through an IDE. And, every Google search for "build tool examples" or "ant example" just brings me back to a tutorial for how to use the tool (i.e., write the xml config file properly, etc.). I'm not looking for a tutorial on how to use a hammer properly. I'm looking for a reason for why I would need to use a hammer in the first place. I'm wondering if anybody can give me a simple example of how a build management tool is superior to raw compilation. Note: I'm not trying to dispute the usefulness of a build system here. I'm *sure* there are loads of benefits... I just don't see them yet. Thanks, ply
[java] Using the Java DOM properly
plywood posted a topic in General and Gameplay ProgrammingI am new to the Java DOM (package org.w3c.dom) and have read several tutorials on its basic use, but cannot find the answers to what I feel are some very basic questions. In org.w3c.dom (the "Java DOM"), Documents, Elements and Nodes are interfaces all representing the components of an XML document, which is a tree structure where each node can have 0+ children (representing the recursive nature of XML itself). The Document interface represents the entire document, whereas Elements (which extend Nodes) represent a specific tag/element in an XML document, and all of its children (the subtree extending from the Element). QUESTION #1: What *class*, then, actually represents the tree data structure of the XML document? Document, Element and Node are interfaces, meaning they can only provide abstract methods and static members. For instance, Node has a method called "getFirstChild()"... since this is an interface method, it has to be abstract... so where is it defined? Another way to look at this question is: noises.xml ======== <animals> <cow noise="moo"/> <dog noise="woof"/> </animals> DomTestDriver.java ================== DocumentBuilderFactory dbf = new DocumentBuilderFactory() DocumentBuilder db = dbf.newInstance(); Document doc = db.parse("noises.xml"); Element root = doc.getRoot(); Element cow = root.getFirstChild(); Here I have read/parsed noises.xml into a Document object. I am now free to explore the document, modifying it as I wish, etc. When I call root.getFirstChild(), somewhere, somehow, a tree structure is holding an in-memory version of noises.xml, and getFirstChild() queries that structure for the correct Node to return... +what is this structure?!?+ It must be a class... so what is it??? ***End of Question #1*** Second, it would be nice if I could modify a Document object or Element at runtime. For instance: Element horse = new Element(); horse.setTagName("horse"); horse.setAttribute("noise", "naaay"); root.replaceChild(horse, cow); // Now, the 'doc' Document object, which originally parsed noises.xml, looks like: /* <animals> <horse noise="naaay"/> <dog noise="woof"/> </animals> */ Several problems with the code sample above: (1) Element is an interface! I can't instantiate it like "Element horse = new Element();" (2) Neither Element nor Node specify a "setTageName(String)" method, telling me that Java does not want me using the Java DOM like this... why?!?! QUESTION #2: So, if my code sample above doesn't work, how do I create new Element objects and insert them into my Document object, or into another Element's subtree?
- Advertisement | https://www.gamedev.net/profile/117254-plywood/ | CC-MAIN-2018-39 | refinedweb | 3,078 | 62.48 |
> if I understand you correctly, all libraries that software I write depends > on, directly or indirectly, must be free of namespace conflicts. Is that > correct? Well, it may be more accurate to say that class instances have no namespaces, and are all implicitly global. When you import a module, you get all the instances it defines in the global namespace, whether you want them or not. Like I said, there was some argument with people on one side saying importing is a valid way of controlling instance visibility, and another side saying the fact that you have to import at all is an implementation artifact and instances should be considered global. Practically speaking, I buy the second argument more, for the reason you described above. | http://www.haskell.org/pipermail/haskell-cafe/2009-September/066260.html | CC-MAIN-2014-35 | refinedweb | 125 | 58.82 |
Table of Contents
TAO 1.3a derives from the DOC TAO 1.3.1 beta kit with bugfix-related patches
selectively applied to enhance stability. A record of applied patches can be
found in OCIChangeLog files installed with the distribution.
All of ACE/TAO was built using MakeProjectCreator (MPC). This tool is included
with this distribution and may be used for your own projects as well. MPC will
generate GNU make files, Windows project files for both VC++ 6 and 7.1, Borland
make files, and others. It can be extended to other make systems as well. MPC
documentation is available in the distribution at
ACE_wrappers/bin/MakeProjectCreator/README or in the OCI Developer's Guide for
TAO 1.3a. This chapter can be viewed from in
html or downloaded in pdf.
Thus, all of the previous make files and project files, except for Visual Age
project files (which do not yet have a MPC generator), have been removed and
only generated files are present in this distribution.
With the exception of Windows operating systems, ACE and TAO were built with
GNU Make. While one can use other tools to build applications using ACE &
TAO, using GNU Make permits the leveraging of the existing build system
distributed with ACE & TAO.
Version 1.3a of ACE/TAO, being based on DOC TAO 1.3.1, requires that the
compiler be able to support namespaces, at least minimally. Any compiler that
does not support namespaces cannot be used with this version, for example,
Sun's 4.2 compiler and Tornado 2.0.
It's possible, and maybe even desirable, to use explicit template instantiation
for any platform. This can not only decrease compile times, but it helps
prevent submitting errors in the explicit instantiation sections of source
files. Just add "#define ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION" to config.h
to enable this feature. A related setting for gcc, suncc, and others can be
enabled by adding "templates=explicit" to platform_macros.GNU. This has the
same effect as above, but additionally *requires* explicit instantiation. Since
all current compilers support implicit templates, there is less need for this
setting. However, this setting is still the default for suncc compilers,
therefore you should probably add "templates=automatic" to your
platform_macros.GNU for suncc. Currently there is an additional side-effect to
enabling explicit template instantiation, regardless of which method you use to
do it. It changes the default setting for TAO_USE_SEQUENCE_TEMPLATES, so that a
non-template base class is used for all corba sequences. This means that you'll
typically want to also add a "#define TAO_USE_SEQUENCE_TEMPLATES" to your
config.h, whenever you add the "#define
ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION".
Many important new features and bug fixes have been introduced in TAO 1.3a.
They are described briefly here. These and many other features of TAO 1.3a are
detailed in OCI's TAO
Developer's Guide, Version 1.3a, available separately.
-AllocateTaskPerProxy
-x
-f
-ORBListenEndpoints
-ORBEndpoint
hostname_in_ior
-ORBDottedDecimalAddresses
TAO/tests/IOR_Endpoint_Hostnames
-ORBDottedDecimalAddresses
1
Wed May 25
12:10:40 2005 Chris Cleeland <cleeland@ociweb.com>
-ORBPreferredInterfaces 192.168.*=127*,*.ociweb.com=132.*
-ORBConcurrency thread-per-connection
CLOSE_WAIT
static UTF16_BOM_Factory "-forceBE [0|1]"
libadm
This added capability is working correctly. However, the new test added to
verify it has exposed a problem that has been in the Naming Service for a long
time. The problem occurs only on static builds and only on some platforms. It
is that only the first client can add a context, subsequent clients quietly
fail when trying to add contexts, but they can add objects to existing
contexts.
"-ORBClientConnectionHandler
mt_noupcall"
"-ORBClientConnectionHandler rw"
The changes are in TAO_Connection_Handler. Using TAO_IIOP_Connection_Handler
as an example (it's a pluggable transport just like anything else), the
following code:
TAO_Connection_Handler
TAO_IIOP_Connection_Handler
// OLD handle_input
int
TAO_IIOP_Connection_Handler::handle_input (ACE_HANDLE h)
{
int result =
this->handle_input_eh (h, this);
if (result == -1)
{
this->close_connection ();
return 0;
}
return result;
}
// OLD handle_input
int
TAO_IIOP_Connection_Handler::handle_input (ACE_HANDLE h)
{
int result =
this->handle_input_eh (h, this);
if (result == -1)
{
this->close_connection ();
return 0;
}
return result;
}
// New and improved handle_input
int
TAO_IIOP_Connection_Handler::handle_input (ACE_HANDLE h)
{
return this->handle_input_eh (h, this);
}
// New and improved handle_input
int
TAO_IIOP_Connection_Handler::handle_input (ACE_HANDLE h)
{
return this->handle_input_eh (h, this);
}
handle_input
However, if your pluggable transport's handle_input doesn't
look like the old handle_input, you will need to look at TAO_Connection_Handler::handle_input_eh()
and integrate the code that appears at the beginning of that method, i.e.,
TAO_Connection_Handler::handle_input_eh()
{...
}
-ORBClientConnectionHandler
-ORBWaitStrategy
virtual TAO_Profile * corbaloc_scan (const char *ior,
size_t &len
ACE_ENV_ARG_DECL);
# define ACE_NATIVE_CHAR_CODESET_ID ACE_CODESET_ID_ISO_8859_1
# define ACE_NATIVE_WCHAR_CODESET_ID ACE_CODESET_ID_ISO_UTF_16
# define ACE_NATIVE_WCHAR_SIZE 2
TAO/orbsvcs/orbsvcs/AV/md5c.c
TAO/orbsvcs/orbsvcs/AV/md5c.cpp
$TAO_ROOT/orbsvcs/orbsvcs/AV/md5c.c
-ORBVerboseLogging
VERBOSE
VERBOSE_LITE
ACE_Log_Msg
-ORBTransportMuxStrategy muxed
-ORBTransportMuxStrategy
exclusive
ACE_wrappers/TAO/docs/tutorials/
Many bugs have been fixed or work-arounds provided since TAO 1.2a. Here we
highlight a few of the more important bug fixes since TAO 1.2a, focusing
especially on fixes for bugs that could cause crashes, deadlocks, resource
leakage, or race conditions. Each bug is referenced by a number as assigned by
the DOC group Bugzilla bug database found at.
* Bug 1020 ()
deserves special explanation. The problem, as described in the bug report,
could cause a multithreaded client with a connection to a server to crash if
the server died. A client thread, trying to send a request to the server, may
attempt to close the connection. Meanwhile, another thread might awaken in the
reactor and also attempt to close the connection, resulting in a segmentation
violation and crash. The partial solution, designed and implemented by
Balachandran Natarajan, is similar in spirit to how the TCP state machine
models connection teardown. Connection closure in the ORB is now modeled as an
event that is handled through the ORB's leader-followers mechanism. In
addition, event handling along the invocation path and along the connection
handling path were separated for better separation of concerns. A regression
test, $TAO_ROOT/tests/Bug_1020_Regression, was also added.
$TAO_ROOT/tests/Bug_1020_Regression
All of the Solaris builds used the recommended OCI build
flags
in addition to the platform_macros.GNU and config.h files already set up for
the SunOS platform and compiler.
Files Used for SunOS Builds
Use the fast=1 instead of optimize=1 for optimizing with Sun compilers because
it selects a combination of compilation options for optimum execution speed.
Other optimization levels may reduce the footprint, but do not have a
corresponding flag in ACE/TAO.
No ACE tests fail on any platform. A scattering of TAO tests fail, but no
test/feature fails across platforms.
All of the Red Hat builds used the recommended OCI build
flags
in addition to the platform_macros.GNU and config.h files already set up for
the Linux platform and compiler.
Files Used for Red Hat Builds
All of the Windows builds used the recommended OCI build
flags
in a config.h file as shown below.
Files Used for Windows Builds
We also test infrequently using a wider variety compilers. Various combinations
of the following. We're reasonably sure that most sensible versions of the
following will work correctly, but we can't guarantee a configuration unless we
test it regularly.
Operating Systems
Compilers
Libraries
The following config.h file is used for all Windows nightly builds.
// contents of config.h
#define ACE_DISABLE_WIN32_ERROR_WINDOWS
#define ACE_HAS_STANDARD_CPP_LIBRARY 1
#include "config-win32.h"
The first line disables the popup of error windows when running the automated
tests. It is not normally needed for ordinary user programs. It would only be
used if an automated build was being done.
The platform_macros.GNU file is not used for Windows platforms.
ssl = 1
qos = 1
mwc.pl -type vc71 -recurse
You can now use this perl script to set up a build for ACE/TAO, so that
multiple builds can share a single code base (this is a new feature with 1.3a).
You must run this command from within the ACE_wrappers directory, and
ACE_wrappers\bin should be in your path. Example:
create_ace_build.pl vc71
By default, it's assumed that you will use MPC to generate any project files
for the new build, so no project files or Makefiles are linked from
ACE_wrappers.
A scattering of ACE and TAO tests fail, but no test/feature fails across
platforms. In addition, the notify service will not load when building release
mode Borland 5.5. (This will likely be fixed in a subsequent patch release.)
The Tru64 builds used the recommended OCI build flags
in addition to the platform_macros.GNU and config.h files already set up for
the Tru64 platform and compiler.
Files Used for Tru64 Builds
In addition
The default ulimits on these platform are not sufficient to
build TAO. The problem is the virtual memory limits, vmemory and
data must be increased to the maximum allowed. For us, this is
vmemory=4194304 and data=1048576
.
In addition the operating system must be configured to have larger limits for
semaphore operations.
ipc:
sem_mni = 250
sem_msl = 125
sem_opm = 100
sem_ume = 100
There is a problem with the Naming Service when built with Compaq C++ compilers
and optimization. The source in question is Bindings_Iterator_T.cpp and the
modules that use this are Persistent_Naming_Context.o and
Transient_Naming_Context.o in library libTAO_CosNaming.so. The problem exists
on C++ V6.2 to V6.5 and on UNIX 5.1 and 4.0F. The problem occurs at all
optimization levels from O1 through O4. It is unknown when a fix will be
available
2 ACE tests fail
All of the AIX builds used the recommended OCI build flags OCI
build flags
in addition to the platform_macros.GNU and config.h files already set up for
the AIX platform and compiler.
When using GNU Make that is part of
AIX toolbox for Linux applications, it may be necessary to modify the
file access permissions of the make executable to ensure the LIBPATH
environment variable is propagated to make system properly. This can be done as
follows:
chmod 755 /opt/freeware/bin/make
See this
message for further information.
NOTE: The preprocessor for VA C++ 5 does not function correctly when used by
tao_idl. Therefore, the GNU Preprocessor was used for tao_idl by setting
TAO_IDL_PREPROCESSOR=g++ in platform_macros.GNU.
No ACE tests fail on this platform. The AVStreams tests are known not to work
on this platform.
All of the HPUX builds used the recommended OCI build flags
OCI build flags
in addition to the platform_macros.GNU and config.h files already set up for
the HPUX platform and compiler.
Files Used for HPUX Builds
Tests
No ACE tests fail on HP-UX 11.00. The ACE Multicast_Test fails on HPUX 11.20
due to platform implementation differences. The TAO RTCORBA tests fail due to
lack of support for the HP-UX thread priorities.
The SGI IRIX build used the recommended OCI build flags
in addition to the platform_macros.GNU and config.h files already set up for
the IRIX platform and compiler.
Files Used for IRIX Builds
The ACE Multicast test fails due to platform implementation differences. A few
TAO tests fail. In many cases this is due to a possible bug in the way the
compiler deals with exceptions. For one test, TAO/tests/AMH_Exceptions/,
the test server locks up and cannot be killed. This test will not be executed
if ACE_wrappers/bin/auto_run_tests.pl
is used the run the tests.
TAO/tests/AMH_Exceptions/
ACE_wrappers/bin/auto_run_tests.pl
All of the Mac OS X builds used the recommended OCI build
flags
in addition to revised platform_macros.GNU and config.h files developed for the
Mac OS X platform and compiler.
Files Used for Mac OS X Builds
The Apple Developer Kit Dec 2002 is required and two additional packages will
have to be loaded from open source available on the net.
#define ACE_NEEDS_DL_UNDERSCORE
The major problem with getting TAO to run on Mac OS X was lack of full
initialization of static objects. About half of the tests were failing. Apple
is aware of the problem, but a fix does not appear to be imminent. Seems to be
somewhat difficult problem with some legacy implications. Thus, for ACE/TAO the
Mac will not be supportable for any earlier versions than 1.3a of ACE/TAO and
10.2.x of Mac OS X.
There are three or four environment variables that are required to be defined
in the user's environment.
And, if you are building ACE/TAO and wish to run the tests,
The VxWorks builds used the recommended OCI build flags
with static libraries only and no exceptions in addition to the
platform_macros.GNU and config.h files already set up for the VxWorks platform
and compiler.
Files Used for VxWorks Builds
The build was cross-compiled on a Solaris platform for a PPC 604 target. A
cross-compile using Windows for a PPC 604 target has also been done.
The VxWorks build was for static libraries only, since that is the most common
use on this platform. Also, the build was without native exceptions again,
since that is the most common.
This build also uses "#define ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION" in its
config.h since it was found that implicit template instantiation does not work
in all cases.
Not all of the orbsvcs and orbsvcs tests will build on VxWorks.
Basic ACE and TAO tests work on VxWorks.
These are platforms for which some amount of work has been done. This does not
mean that these platforms are fully supported, only that they may be usable in
circumstances similar to those in which they were tested.
The 5.3a version of ACE has been built and tested with the Green Hills tool
kits versions 3.5 and 4.0 on both Solaris for Solaris, Solaris for VxWorks, and
Linux for Linux.
The 1.3a version of ACE/TAO has been built with the Green Hills Integrity
toolkit 4.0 running on Windows for the Green Hills Integrity OS. Green Hills
Integrity is a fairly new Real-Time OS for embedded systems. As such, systems
on which it runs are generally limited in the resources which they can provide.
For example, the system on which we tested was very limited in memory, so very
little of the standard tests could be run.
If you're doing your own build, you can have the following flags set which OCI
uses in its own builds. For UNIX and UNIX-like platforms that use GNU Make, use
platform_macros.GNU. For Windows/Visual C++ builds, use config.h. If an option
is not listed below, let it default.
Turned on:
Turned off:
Variable--dependent on platform and other settings: | http://www.theaceorb.com/1.3a/OCIReleaseNotes.html | crawl-001 | refinedweb | 2,427 | 57.77 |
Open another QML window
- AriosJentu last edited by
Hi. I'm newbie in development in QT, and I have a question about loading another window when clicking on button in first window. I have two QML files with different styles. I need to open window from second QML when clicking on first.
I have this:
My main file calendar.qml:
import QtQuick 2.2 import QtQuick.Window 2.10 .... Window { id: root visible: true .... someclasses { property variant win; MouseArea { onClicked: { if (mouse.button === Qt.RightButton) { .... } else { var component = Qt.createComponent("viewevent.qml"); win = component.createObject(); //win.show(); //win.setEvent(maincalendar.selectedDate, modelData); } } } } }
My viewevent.qml file:
import QtQuick 2.2 import QtQuick.Window 2.10 .... Window { id: eventWindow visible: true someclasses { .... } function setEvent(date, event) { .... } }
So, how can I open window eventWindow from my root, or maybe change view for it, like part of child window in main window. Or maybe any another ideas for creating another 'activity' for application (because it will run on android). Or maybe I need to add in engine this QML, and if it is, how can I do that. And when creating child, how execute it's function (here is setEvent). Thank you.
- Diracsbracket last edited by Diracsbracket
Hi @AriosJentu
Have a look at
- AriosJentu last edited by
This post is deleted! | https://forum.qt.io/topic/103688/open-another-qml-window | CC-MAIN-2022-40 | refinedweb | 218 | 61.93 |
Executes a file.
Standard C Library (libc.a)
#include <unistd.h>
extern char **environ;
int execl (
Path,
Argument0 [, Argument1, ...], 0)
const char *Path, *Argument0, *Argument
1, ...;
int execle (
Path,
Argument0 [, Argument1, ...], 0,
EnvironmentPointer)
const
char *Path, *Argument0, *Argum
ent
1, ...;
char *const EnvironmentPointer[ ];
int execlp (
File,
Argument0 [, Argument1
, ...], 0)
const char *File, *Argument0, *Argument
1, ...;
int execv (
Path,
ArgumentV)
const char *Path;
char *const ArgumentV[ ];
int execve (
Path,
ArgumentV,
EnvironmentPointer)
const char *Path;
char
*const ArgumentV[ ], *EnvironmentPointer
[ ];
int execvp (
File,
ArgumentV)
const char *File;
char *const ArgumentV[ ];
int exect (
Path,
ArgumentV,
EnvironmentPointer)
char *Path, *ArgumentV, *EnvironmentPointer [ ];
The exec subroutine, in all its forms, executes a new program in the calling process. The exec subroutine does not create a new process, but overlays the current program with a new one, which is called the new-process image. The new-process image file can be one of three file types:
The new-process image inherits the following attributes from the calling process image: session membership, supplementary group IDs, process signal mask, and pending signals.
The last of the types mentioned is recognized by a header with the following syntax:
#! Path [String]
The #! is the file magic number, which identifies the file type. The path name of the file to be executed is specified by the Path parameter. The String parameter is an optional character string that contains no tab or space characters. If specified, this string is passed to the new process as an argument in front of the name of the new-process image file. The header must be terminated with a new-line character. When called, the new process passes the Path parameter as ArgumentV[0]. If a String parameter is specified in the new process image file, the exec subroutine sets ArgumentV[0] to the String and Path parameter values concatenated together. The rest of the arguments passed are the same as those passed to the exec subroutine.
The exec subroutine attempts to cancel outstanding asynchronous I/O requests by this process. If the asynchronous I/O requests cannot be canceled, the application is blocked until the requests have completed.
The exec subroutine is similar to the load (load Subroutine) subroutine, except that the exec subroutine does not have an explicit library path parameter. Instead, the exec subroutine uses the LIBPATH environment variable. The LIBPATH variable is ignored when the program that the exec subroutine is run on has more privilege than the calling program, for example, the suid program.
The exect subroutine is included for compatibility with older programs being traced with the ptrace command. The program being executed is forced into hardware single-step mode.
Note: exect is not supported in 64-bit mode.
When a C program is run, it receives the following parameters:
main (ArgumentCount, ArgumentV, EnvironmentPointer) int ArgumentCount; char *ArgumentV[ ], *EnvironmentPointer[ ];
In this example, the ArgumentCount parameter is the argument count, and the ArgumentV parameter is an array of character pointers to the arguments themselves. By convention, the value of the ArgumentCount parameter is at least 1, and the ArgumentV[0] parameter points to a string containing the name of the new-process image file.
The main routine of a C language program automatically begins with a runtime start-off routine. This routine sets the environ global variable so that it points to the environment array passed to the program in EnvironmentPointer. You can access this global variable by including the following declaration in your program:
extern char **environ;
The execl, execv, execlp, and execvp subroutines use the environ global variable to pass the calling process current environment to the new process.
File descriptors open in the calling process remain open, except for those whose close-on-exec flag is set. For those file descriptors that remain open, the file pointer is unchanged. (For information about file control, see the fcntl.h file.)
The state-of-conversion descriptors and message-catalog descriptors in the new process image are undefined. For the new process, an equivalent of the setlocale subroutine, specifying the LC_ALL value for its category and the "C" value for its locale, is run at startup.
If the new program requires shared libraries, the exec subroutine finds, opens, and loads each of them into the new-process address space. The referenced counts for shared libraries in use by the issuer of the exec are decremented. Shared libraries are searched for in the directories listed in the LIBPATH environment variable. If any of these files is remote, the data is copied into local virtual memory.
The exec subroutines reset all caught signals to the default action. Signals that cause the default action continue to do so after the exec subroutines. Ignored signals remain ignored, the signal mask remains the same, and the signal stack state is reset. (For information about signals, see the sigaction subroutine.)
If the SetUserID mode bit of the new-process image file is set, the exec subroutine sets the effective user ID of the new process to the owner ID of the new-process image file. Similarly, if the SetGroupID mode bit of the new-process image file is set, the effective group ID of the new process is set to the group ID of the new-process image file. The real user ID and real group ID of the new process remain the same as those of the calling process. (For information about the SetID modes, see the chmod subroutine.)
At the end of the exec operation the saved user ID and saved group ID of the process are always set to the effective user ID and effective group ID, respectively, of the process.
When one or both of the set ID mode bits is set and the file to be executed is a remote file, the file user and group IDs go through outbound translation at the server. Then they are transmitted to the client node where they are translated according to the inbound translation table. These translated IDs become the user and group IDs of the new process.
Note: setuid and setgid bids on shell scripts do not affect user or group IDs of the process finally executed.
Profiling is disabled for the new process.
The new process inherits the following attributes from the calling process:
Upon successful completion, the exec subroutines mark for update the st_atime field of the file.
execlp("ls", "ls", "-al", 0);
The execlp subroutine searches each of the directories listed in the PATH environment variable for the ls command, and then it overlays the current process image with this command. The execlp subroutine is not returned, unless the ls command cannot be executed.
Note: This example does not run the shell command processor, so operations interpreted by the shell, such as using wildcard characters in file names, are not valid.
execl("/usr/bin/sh", "sh", "-c", "ls -l *.c", 0);
This runs the sh command with the -c flag, which indicates that the following parameter is the command to be interpreted. This example uses the execl subroutine instead of the execlp subroutine because the full path name /usr/bin/sh is specified, making a path search unnecessary.
Running a shell command in a child process is generally more useful than simply using the exec subroutine, as shown in this example. The simplest way to do this is to use the system subroutine.
#! /usr/bin/awk -f { for (i = NF; i > 0; --i) print $i }
If this file is named reverse, entering the following command on the command line:
reverse chapter1 chapter2
This command runs the following command:
/usr/bin/awk -f reverse chapter1 chapter2
Note: The exec subroutines use only the first line of the new-process image file and ignore the rest of it. Also, the awk command interprets the text that follows a # (pound sign) as a comment.
Upon successful completion, the exec subroutines do not return because the calling process image is overlaid by the new-process image. If the exec subroutines return to the calling process, the value of -1 is returned and the errno global variable is set to identify the error.
If the exec subroutine
is unsuccessful, it returns one or more of the following error codes:
If the exec subroutine
is unsuccessful because of a condition requiring path name resolution, it
returns one or more of the following error codes:
In addition, some errors can occur when using the new-process file after the old process image has been overwritten. These errors include problems in setting up new data and stack registers, problems in mapping a shared library, or problems in reading the new-process file. Because returning to the calling process is not possible, the system sends the SIGKILL signal to the process when one of these errors occurs.
If an error occurred while mapping
a shared library, an error message describing the reason for error is written
to standard error before the signal SIGKILL is sent to the
process. If a shared library cannot be mapped, the subroutine returns
one of the following error codes:
If NFS is installed on the system,
the exec subroutine can also fail if the following is true:
These subroutines are part of Base Operating System (BOS) Runtime.
Note: Currently, a Graphics Library program cannot be overlaid with another Graphics Library program. The overlaying program can be a nongraphics program. For additional information, see the /usr/lpp/GL/README file.
The alarm (getinterval, incinterval, absinterval, resinc, resabs, alarm, ualarm, getitimer or setitimer Subroutine) or incinterval (getinterval, incinterval, absinterval, resinc, resabs, alarm, ualarm, getitimer or setitimer Subroutine) subroutine, chmod (chmod or fchmod Subroutine) or fchmod (chmod or fchmod Subroutine) subroutine, exit (exit, atexit, or _exit Subroutine) subroutine, fcntl (fcntl, dup, or dup2 Subroutine) subroutine, fork (fork, f_fork, or vfork Subroutine) subroutine, getrusage (getrusage, getrusage64, times, or vtimes Subroutine) or times (getrusage, getrusage64, times, or vtimes Subroutine) subroutine, nice (getpriority, setpriority, or nice Subroutine) subroutine, profil (profil Subroutine) subroutine, ptrace (ptrace, ptracex, ptrace64 Subroutine) subroutine.
The semop subroutine, settimer (gettimer, settimer, restimer, stime, or time Subroutine) subroutine, sigaction, signal, or sigvec subroutine, shmat subroutine, system subroutine, ulimit subroutine, umask subroutine.
The awk command, ksh command, sh command.
The environment file.
The XCOFF object (a.out) file format.
The varargs macros.
Asynchronous I/O Overview in AIX 5L Version 5.1 Kernel Extensions and Device Support Programming Concepts. | http://ps-2.kev009.com/wisclibrary/aix51/usr/share/man/info/en_US/a_doc_lib/libs/basetrf1/exec.htm | CC-MAIN-2022-27 | refinedweb | 1,717 | 52.19 |
From: Andrey Vagin <ava...@openvz.org> The operation of destroying netns is heavy and it is executed under net_mutex. If many namespaces are destroyed concurrently, net_mutex can be locked for a long time. It is impossible to create a new netns during this period of time.
Advertising
In our days when userns allows to create network namespaces to unprivilaged users, it may be a real problem. On my laptop (fedora 24, i5-5200U, 12GB) 1000 namespaces requires about 300MB of RAM and are being destroyed for 8 seconds. In this patch, a number of namespaces which can be cleaned up concurrently is limited by 32. net_mutex is released after handling each portion of net namespaces and then it is locked again to handle the next one. It allows other users to lock it without waiting for a long time. I am not sure whether we need to add a sysctl to costomize this limit. Let me know if you think it's required. Cc: "David S. Miller" <da...@davemloft.net> Cc: "Eric W. Biederman" <ebied...@xmission.com> Signed-off-by: Andrei Vagin <ava...@openvz.org> --- net/core/net_namespace.c | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/net/core/net_namespace.c b/net/core/net_namespace.c index 989434f..33dd3b7 100644 --- a/net/core/net_namespace.c +++ b/net/core/net_namespace.c @@ -406,10 +406,20 @@ static void cleanup_net(struct work_struct *work) struct net *net, *tmp; struct list_head net_kill_list; LIST_HEAD(net_exit_list); + int i = 0; /* Atomically snapshot the list of namespaces to cleanup */ spin_lock_irq(&cleanup_list_lock); - list_replace_init(&cleanup_list, &net_kill_list); + list_for_each_entry_safe(net, tmp, &cleanup_list, cleanup_list) + if (++i == 32) + break; + if (i == 32) { + list_cut_position(&net_kill_list, + &cleanup_list, &net->cleanup_list); + queue_work(netns_wq, work); + } else { + list_replace_init(&cleanup_list, &net_kill_list); + } spin_unlock_irq(&cleanup_list_lock); mutex_lock(&net_mutex); -- 2.7.4 | https://www.mail-archive.com/netdev@vger.kernel.org/msg132304.html | CC-MAIN-2016-50 | refinedweb | 289 | 57.87 |
NAME | SYNOPSIS | DESCRIPTION | RETURN VALUES | USAGE | EXAMPLES | ATTRIBUTES | SEE ALSO
#include <time.h>
extern int getdate_err;struct tm *getdate(const char .
Locale's abbreviated month name.
Hour (24-hour clock) [0,23]; leading zero is permitted but not required.
Hour (12-hour clock) [1,12]; leading zero is permitted but not required.
Day number of the year [1,366]; leading zeros are permitted but not required.
Month number [1,12]; leading zero is permitted but not required.
Minute [0,59]; leading zero is permitted but not required.
Any white space.
Locale's equivalent of either a.m. or p.m.
Appropriate time representation in the 12-hour clock format with %p.
Time as %H:%M.
Seconds [0,61]; leading zero is permitted but not required. The range of values is [00,61] rather than [00,59] to allow for the occasional leap second and even more occasional double leap second.
Any white space.
Time as %H:%M:%S.).)
NAME | SYNOPSIS | DESCRIPTION | RETURN VALUES | USAGE | EXAMPLES | ATTRIBUTES | SEE ALSO | http://docs.oracle.com/cd/E19683-01/817-0710/6mgg8q8js/index.html | CC-MAIN-2015-06 | refinedweb | 168 | 62.75 |
Weekend Scripter: A Cool Music Explorer Script
Microsoft Scripting Guy Ed Wilson here. I don’t know about you, but I have thousands of music files on my computer. In fact, I have exactly 4,018 music files. I used this Windows PowerShell command to count them:
PS E:\Music> (dir -Include *.mp3,*.wma -Recurse | Measure-Object).count
4018
PS E:\Music>
One problem with having 4,018 music files on my computer is that at times I am not sure what I want to listen to, or even what a particular song might sound like. Whereas the Zune software is really cool and has several nice modes for playing music, at times I prefer a bit more automated operation. Unfortunately, there are no Zune HD cmdlets available—at least none that I know of.
Luckily, Windows PowerShell has access to the .NET Framework, and using some basic Windows PowerShell techniques and an easy-to-use .NET Framework class, a pretty cool music explorer script can be easily crafted.
The system.windows.media.mediaplayer .NET Framework class is just the tool that we need. Actually, the class name is mediaplayer, and it is found in the system.windows.media .NET Framework namespace. Namespaces in the .NET Framework work like folders that group similar items together, or like DNS domain names that group computers into domains. The MSDN .NET Framework documentation makes fascinating reading, and the fact that the classes are grouped into namespaces makes it easy to peruse. I often spend entire weekends browsing the namespaces, selecting interesting classes, and trying them out in Windows PowerShell scripts. The system.windows.media .NET Framework namespace documentation is shown in the following image.
I just click through the classes until I see something that sounds cool. I then read about it, and try it out. Often, there are useful code samples that illustrate using the classes; unfortunately, there are almost no code samples in Windows PowerShell. A few of the Microsoft PowerShell MVPs such as Thomas Lee have added useful samples written in Windows PowerShell for some of the major .NET Framework classes (these show up in the discussion section at the very bottom of the page).
The mediaplayer class is not immediately available. The first thing to do is to load the assembly that contains the class. MSDN tells you in which assembly a class resides, and that is what you will use with the Add-Type Windows PowerShell cmdlet. The mediaplayer class resides in an assembly called presentationCore. To load the presentationCore assembly, use the command shown here:
Add-Type -AssemblyName presentationCore
After the assembly has been loaded, it is time to create an instance of the mediaplayer class. To do this, you will need to look up the mediaplayer constructor on MSDN. Luckily, we do not need to pass anything to New-Object when we create the instance of the mediaplayer class. Sometimes, .NET Framework classes require one or more parameters to be supplied when creating a new instance of the class, and therefore it is always a good idea to review the constructor details in MSDN before attempting to create the class. Because the mediaplayer class requires no parameters, the code to create the class is simple and is shown here:
$mediaPlayer = New-Object system.windows.media.mediaplayer
The path variable is used to store the path to the music files I wish to gather, and the Get-ChildItem cmdlet is used to collect those files. The script retrieves both MP3 and WMA files and stores the returned system.io.fileinfo objects in the $files variable, as shown here:
$path = "E:\Music\classical\Luciano Pavarotti"
$files = Get-ChildItem -path $path -include *.mp3,*.wma -recurse
After the collection of files is stored in the $files variable, the Foreach statement is used to walk through the collection. Inside the loop, each file is referenced by the $file variable. This is shown here:
foreach($file in $files)
{
The basename property was added in Windows PowerShell 2.0 to the fileinfo class, and it is the file name minus the file extension. This is used to display an indicator of the song that is being played and is shown here:
"Playing $($file.BaseName)"
The fullname property from the fileinfo class contains the complete path to the file. This path is converted to a system.uri .NET Framework class, and is passed to the open method of the mediaplayer class. One of the system.uri constructors accepts a string. When accessing a .NET Framework class, the name can be placed inside square brackets and the Word system left off. This gives us [uri]. The constructor is then supplied to it directly. This is illustrated here:
PS C:\> [uri]"E:\Music\classical\Luciano Pavarotti\Live 1961-1966\01.wma"AbsolutePath : E:/Music/classical/Luciano%20Pavarotti/Live%201961-1966/01.wma
AbsoluteUri :.
wma
Authority :
Host :
HostNameType : Basic
IsDefaultPort : True
IsFile : True
IsLoopback : True
IsUnc : False
LocalPath : E:\Music\classical\Luciano Pavarotti\Live 1961-1966\01.wma
PathAndQuery : E:/Music/classical/Luciano%20Pavarotti/Live%201961-1966/01.wma
Port : -1
Query :
Fragment :
Scheme : file
OriginalString : E:\Music\classical\Luciano Pavarotti\Live 1961-1966\01.wma
DnsSafeHost :
IsAbsoluteUri : True
Segments : {/, E:/, Music/, classical/…}
UserEscaped : False
UserInfo :PS C:\>
Because the open method of the mediaplayer class accepts a system.uri, I do not need to worry about which property to supply. The mediaplayer class is smart enough to choose what I need from the incoming object. A subexpression is used on the fullname property of the fileinfo class to retrieve the string path to the file. This portion of the script is shown here:
$mediaPlayer.open([uri]"$($file.fullname)")
The remainder of the script is really easy. I call the play method fr
om the mediaplayer class, use the Start-Sleep Windows PowerShell cmdlet to pause the script for 10 seconds, and then call the stop method to halt playing the tune. I then loop around to the next file in the $files collection. This is shown here:
$mediaPlayer.Play()
Start-Sleep -Seconds 10
$mediaPlayer.Stop()
}
The complete PlayMedia.ps1 script is shown here.
PlayMedia.ps1
Add-Type -AssemblyName presentationCore
$mediaPlayer = New-Object system.windows.media.mediaplayer
$path = "E:\Music\classical\Luciano Pavarotti"
$files = Get-ChildItem -path $path -include *.mp3,*.wma -recurse
foreach($file in $files)
{
"Playing $($file.BaseName)"
$mediaPlayer.open([uri]"$($file.fullname)")
$mediaPlayer.Play()
Start-Sleep -Seconds 10
$mediaPlayer.Stop()
}
When the script runs, each file name is displayed in either the Windows PowerShell console or the Windows PowerShell ISE output pane, depending on how you launched the script. | https://devblogs.microsoft.com/scripting/weekend-scripter-a-cool-music-explorer-script/ | CC-MAIN-2019-47 | refinedweb | 1,094 | 57.37 |
is a method that must not proceed until a shared variable
joy has been set by another thread. Such a method could, in theory, simply loop until the condition is satisfied, but that loop is wasteful, since it executes continuously while waiting.
public void guardedJoy() { // Simple loop guard. Wastes // processor time. Don't do this! while(!joy) {} System.out.println("Joy has been achieved!"); }
A more efficient guard invokes
Object.wait to suspend the current thread.!"); }
waitinside a loop that tests for the condition being waited for. Don't assume that the interrupt was for the particular condition you were waiting for, or that the condition is still true.
Like many methods that suspend execution,
wait can throw
InterruptedException. In this example, we can just ignore that exception we only care about the value of
joy.
Why is this version of
guardedJoy synchronized? Suppose
d is the object we're using to invoke
wait. When a thread invokes
d.wait, it must own the intrinsic lock for
d otherwise an error is thrown. Invoking
wait inside a synchronized method is a simple way to acquire the intrinsic lock.
When
wait is invoked, the thread releases the lock and suspends execution. At some future time, another thread will acquire the same lock and invoke
Object.notifyAll, informing all threads waiting on that lock that something important has happened:
public synchronized notifyJoy() { joy = true; notifyAll(); }
Some time after the second thread has released the lock, the first thread reacquires the lock and resumes by returning from the invocation of
wait..
public(); } }
The producer thread, defined in
, sends a series of familiar messages. The string "DONE" indicates that all messages have been sent. To simulate the unpredictable nature of real-world applications, the producer thread pauses for random intervals between messages.
Producer
import"); } }
The consumer thread, defined in
, simply retrieves the messages and prints them out, until it retrieves the "DONE" string. This thread also pauses for random intervals.
Consumer
import) {} } } }
Finally, here is the main thread, defined in
, that launches the producer and consumer threads.
ProducerConsumerExample
public class ProducerConsumerExample { public static void main(String[] args) { Drop drop = new Drop(); (new Thread(new Producer(drop))).start(); (new Thread(new Consumer(drop))).start(); } }
Dropclass was written in order to demonstrate guarded blocks. To avoid re-inventing the wheel, examine the existing data structures in the Java Collections Framework before trying to code your own data-sharing objects. For more information, refer to the Questions and Exercises section. | http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html | CC-MAIN-2016-40 | refinedweb | 413 | 58.58 |
queries
Java Queries
datatypes queries
Hibernate named queries
Hibernate named queries Hi,
What is named queries in Hibernate?
Thanks
link tag in jsp - JSP-Servlet
this in jsp page it will work although it is html tag. Visit for more information.
Thanks...link tag in jsp Hi,
how to write link in a jsp page.
give me
JPA Sub-Queries
JPA Sub-Queries
In this section, you will see how to use sub-queries
in your JPA application. Sub-queries allows you for querying the vast number of
data
JSP SQL Tag
sql tag in
jsp.
JSTL?s database library supports database queries and transactions. JSP
pages can import this library with the following directive:
<...
JSP SQL Tag
jsp - JSP-Servlet
visit for more information. sir, can we include more java code asif we do in servlet programing.
And pls say how to introduse the session handling methods in jsp.
JSP - JSP-Servlet
it and visit to :
Google Ranking Update for Spammy Queries
ranking update today for some spammy queries". This update was worldwide and many... in their ranking and disappeared from search results.
This update targets spam queries... percent of English queries. It is a work in progress and will be completely
Session Problem in JSP - JSP-Servlet
in JSP platform. I have created normal session in JSP page. It is running in my... normally from Remote machine by only writing JSP code. Hi friend... for more information.
multiuser in java/jsp? - JSP-Servlet
://
Thanks...multiuser in java/jsp? Hi!!! Rose India Team,
Kindly let me know what is exact meaning of multiuser in java?
I made an web application using jsp
MySQL allowMultiQueries JSP Example
MySQL allowMultiQueries JSP Example
In this section we will discuss about how to run multiple sql queries in
Java.
This example is given here for demonstrating you about how to write multiple
queries in a single query in Java
Execute SQL Queries with Java Application
Execute SQL Queries with Java Application
This is detailed java program to connect java application and execute queries
like create table in mysql database, insert some
java - JSP-Servlet
for more information: How to use sessions in JSP pages?
I am using the following code for sessions in jsp pages to send and recieve sessions but i am not able
servlets and jsp - JSP-Servlet
servlets and jsp HELLO GOOD MORNING,
PROCEDURE:HOW TO RUN A SERVLET AND JSP IN COMMANDPROMPT AND ALSO IN NETBEANS IDE6.0,IT'S VERY URGENT......
well if u ahve any queries regarding the solved problem still write to me
struts - JSP-Servlet
:// Hello
My question is
How can I pass the values into jsp... Servlet to JSP :
"MyServlet.java"
import java.io.*;
import javax.servlet. paging - JSP-Interview Questions
jsp paging I am working in JSP paging with ms-access but i have... name in all the queries:
"select count(*) from tablename"
"tablename" is created Correct or not.
For more on Paging in JSP visit to :
http
JPA-QL Queries
JPA-QL Queries
In this section, we will use the simple JPA-QL
query in our JPA application. Here JPA-QL query used with createQuery()
method of EntityManager
Sessions
Sessions how to set JSESSIONID in JSP login page...
Hi Friend,
Please visit the following links:
Thanks
Ask Questions
Ask Questions
In the move of resolving the queries of software developers... on the following topics.
Java Questions
JSP questions
Code Works - JSP-Servlet
Code Works Hi
The code provided is working fine along with the pagination . i edited the queries and that makes difference..
here is the code.
Thank you
Regards
Eswaramoorthy
Pagination of JSP page
Map | Business Software
Services India
JSP Tutorial Section
Intro
to JSP |
JSP Technology
| JSP Architecture
| JSP Actions
|
JSP tags |
JSP Declaratives
|
JSP Scriptlets and JSP Expressions | Writing
java - Java Interview Questions
java how to get session object Hi Friend,
Please visit the following link:
Hope that it will be helpful for you.
Thanks
session in jsp
For more detail you may follow the link in jsp
In this section you will learn about session in JSP. Here you will learn
about how to use the HttpSession in JSP.
session in JSP is defined
JSP Code - Java Beginners
JSP Code Hi frnds,
This is reference to solution which u have............. Hi Friend,
We have changed the queries. Now try the following:
Pagination of JSP page
Roll No
Name
Marks
Grade
Roseindia JSP Tutorial
related to JSP, we are here to solve your queries. Just post your questions...Roseindia JSP tutorials provides you with a library of best JSP tutorials for beginners as well as experienced programmers as the JSP tutorials
JSP Tutorials - Page2
JSP Tutorials page 2
JSP Examples
Hello World JSP Page... world" on your browser. Jsp can be learned very
easily. This is just... Directive
in JSP Page
This section illustrates you about the page
Employee Details - JSP-Servlet
in process.jsp, in Home Page. Because, for jsp or html elements like radio buttons... code.
Because, queries are different for each radiobutton. You have to decide... to do that, you have to forward form to either java action class or to some jsp (i.e
Error in using java beans - JSP-Servlet
run the jsp code.
type Exception report
description The server...: Unable to load class for JSP... for JSP
org.apache.jasper.JspCompilationContext.load
How to create discussion forum? - JSP-Servlet
a discussion forum where if any one is having any queries or to discuss some new cases can communicate with each other. I using JSP as a front end and SQL SERVER
JSP FILE UPLOAD-DOWNLOAD code USING JSP
jsp
jsp how to write hindi in jsp and store in database as unicode
jsp
jsp how to pass jsp variable to an html
Advertisements
If you enjoyed this post then why not add us on Google+? Add us to your Circles | http://www.roseindia.net/tutorialhelp/comment/94904 | CC-MAIN-2015-48 | refinedweb | 977 | 73.78 |
Generating plane triangulations
Does sage have a function that generates plane triangulations? Something like PLANTRI? If not, is it possible to use plantri from within sage and how?
Thank you
asked 2013-12-21 14:22:30 +0200
updated 2019-03-12 21:11:42 +0200
Does sage have a function that generates plane triangulations? Something like PLANTRI? If not, is it possible to use plantri from within sage and how?
Thank you
answered 2013-12-21 17:12:04 +0200
If you have plantri installed and somewhere in your PATH variable you can easily adapt the code of
graphs.nauty_geng to make it work with plantri. Something along the following lines might do the job:
def plantri(self, options=""): import subprocess sp = subprocess.Popen("plantri -g {0}".format(options), shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) gen = sp.stdout while True: try: s = gen.next() except StopIteration: raise StopIteration("Exhausted list of graphs from plantri") G = graph.Graph(s[:-1], format='graph6') yield G
plantri is an optional package that you can install using
sage -i plantri
You will then be able to use the iterator over connected planar triangulations
sage: list(graphs.triangulations(6)) [Graph on 6 vertices, Graph on 6 vertices] sage: all(g.is_planar() for g in graphs.triangulations(10)) True
Please start posting anonymously - your entry will be published after you log in or create a new account.
Asked: 2013-12-21 14:22:30 +0200
Seen: 548 times
Last updated: Mar 13 '19
embed planar graph with prescribed outer face
Combinatorial data for planar graph
How do I get the external face of a planar embedded graph?
How to create random cubic planar graphs?
Drawing a planar multigraph with loops
How to triangulate polygon with sage?
Graph theory: Make vertex labels in plots bigger
A faster way to obtain orbits of a partition of the verrtex set
How to get an arbitrary orientation of a graph. | https://ask.sagemath.org/question/10851/generating-plane-triangulations/?sort=oldest | CC-MAIN-2021-39 | refinedweb | 328 | 58.38 |
This is your resource to discuss support topics with your peers, and learn from each other.
02-17-2013 02:13 PM
Since the QML method of share invocations is currently broken (purposely or otherwise) I'm left with c++
void MyApp::share(QString name, QString surname, QString age) { printf("Share invoked"); m_pInvocation = Invocation::create( InvokeQuery::create() .parent(this) .mimeType("text/plain") .data(name.toUtf8() + surname.toUtf8() + age.toUtf8())); QObject::connect(m_pInvocation, SIGNAL(armed()), this, SLOT(onArmed())); QObject::connect(m_pInvocation, SIGNAL(finished()), m_pInvocation, SLOT(deleteLater())); } // Declare the following method as SLOT on your .hpp file void MyApp::onArmed() { m_pInvocation->trigger("bb.action.SHARE"); }
found a few samples & this one is most relevant to what i need but it when i try to declare the invocation in my .hpp i get
'Invocation' does not name a type
private: Invocation* m_pInvocation;
I've included in my .cpp
#include <bb/cascades/Invocation>
#include <bb/cascades/InvokeQuery>
Solved! Go to Solution.
02-17-2013 02:18 PM
02-17-2013 02:27 PM
Thanks Zmey, its working perfectly now..... still odd that the qml method freezes the app, i'm going to file a issue report on it
02-17-2013 05:40 PM
Would you mind posting both the cpp and the hpp? I can't figure it out and I need this as well...
Staff UI Prototyper (read: full-time hacker)
My BB10 apps: Screamager | Scientific RPN Calculator | The Last Weather App
02-17-2013 05:59 PM
Nevermind! I got it to work as well.
This post was Godsent for me. I spent all night last night trying to get sharing to work with QML. This code did the job. Awesome!!!
Staff UI Prototyper (read: full-time hacker)
My BB10 apps: Screamager | Scientific RPN Calculator | The Last Weather App
02-17-2013 06:21 PM
Glad its working for you too, i've been puzzling over the QML part for over a week & when you mentioned c++ yesterday i figured that was the best we'd get
I only found the invocation method in this post & with Zmey's help got it patched together
... I did file an issue on the QML side not working as it should | https://supportforums.blackberry.com/t5/Native-Development/Invocation-from-c/m-p/2171973 | CC-MAIN-2016-50 | refinedweb | 367 | 62.38 |
- YEAH BRAH!!!!!!!!!!!!!!!!!!!! —RomanDogBird (Talk•Morgan Freeman•eat my shorts nigga•Hawkman•suck my balls) 05:38, September 12, 2009 (UTC)
- Patrick Swayze)
- RIP TED KENNEDY. —Unführer Guildy Ritter von Guildensternenstein 14:13, September 12, 2009 (UTC)
- Also, AotM and PotM are for relatively specific categories/namespaces, so just because there's not a lot of activity one month (which is only, like, 1/3 over at this point), it doesn't mean they're dead in the sense that they're going to be perpetually inactive--it's just a slow month for UnScripts, or whatever. A lot of the other stuff you've mentioned I've never even heard of, and I've been here almost 8 months now, so all of that would qualify as being "dead." —Unführer Guildy Ritter von Guildensternenstein 14:13, September 12, 2009 (UTC)
- Also, looking through that stuff again, I think we should bring back Rate Your Admin, because that seems/seemed like it was kind of a cool idea. —Unführer Guildy Ritter von Guildensternenstein 14:14, September 12, 2009 (UTC)
- We could bring it back but we used all of our phoenix downs. --Hotadmin4u69 [TALK] 19:59, September 12, 2009 (UTC)
this forum was my favorite
why did you have to resolve the drama moredildo? -- Soldat Teh PWNerator (pwnt!) 04:14, September 14, 2009 (UTC)
- Because he's an admin and that's his job. Now go to your room. DAP Dame Pleb Com. Miley Spears (talk) 04:19, September 14, 2009 (UTC)
- Oh well, it was fun while it lasted... I actually should go to my room, it's getting late... hmmm, you act like a mother and you seem psychic.... you're not my mom are you? -- Soldat Teh PWNerator (pwnt!) 04:23, September 14, 2009 (UTC)
- Not unless you're Whyner's sockpuppet! :) DAP Dame Pleb Com. Miley Spears (talk) 05:02, September 14, 2009 (UTC)
I never called my adopter "Mommy"...
Then again, it was Zana Dark who adopted me, and I never graduated... 21:42, September 15, 2009 (UTC)
- You can call me Mommy if you like. Or Daddy. --Hotadmin4u69 [TALK] 17:10, September 16, 2009 (UTC)
- I didn't graduate either. I just left home. :) DAP Dame Pleb Com. Miley Spears (talk) 01:35, September 17, 2009 (UTC)
- Ooh, shes a little runaway. Daddys girl learned fast. Now she works the night away. --Hotadmin4u69 [TALK] 02:26, September 17, 2009 (UTC)
- That sounds like you read the messages I left on my Daddy's talk page! lol Really he said he wouldn't be active he's only made one edit here in over a month. And really I talk to him on another website anyway. DAP Dame Pleb Com. Miley Spears (talk) 03:25, September 17, 2009 (UTC) | http://uncyclopedia.wikia.com/wiki/Forum:Imperial_Colonization_3:_The_Revenge | CC-MAIN-2015-48 | refinedweb | 463 | 74.59 |
Section 3.6
More on Program Design
UNDERSTANDING HOW PROGRAMS WORK IS ONE THING. Designing a program to perform some particular task is another thing altogether. In Section 2.5,, that you can work on separately; your main algorithm will merely call the subroutine. This, of course, is just a way of breaking your problem down into separate, smaller problems. This is still a top-down approach because the top-down analysis of the problem tells you what subroutines to write. In the bottom-up approach, you start by writing or obtaining subroutines that are relavant to the problem domain, and you build your solution to the problem on top of that foundation of subroutines.
Let's work through an example. Suppose that I have this idea for a neat animation. I am thinking of a window full of little colored squares lined up in rows and columns. The colors of the squares are all random. The animation that I want is to randomly change the colors of squares. This might mean several things, but after thinking for a while, I decide it would be neat to have a "disturbance" that wanders randomly around the window, changing the color of each square that it encounters.
Let's say that I manage to obtain a class, MosaicWindow, for working with windows full of little colored squares. If mosaic is a variable of type MosaicWindow, and if R and C are integers, then the statment
mosaic = new MosaicWindow(R,C);
will create a window object with R rows and C columns of squares, and will set the variable mosaic to refer to that window. ("new MosaicWindow(R,C)" is a special kind of function called a constructor -- a kind of factory for creating objects. For now, you should just accept this constructor, along with the rest of the MosaicWindow class, as a black box. I'll discuss constructors in the next chapter.)
The MosaicWindow class provides a number of subroutines, but the only thing I really need is to be able to set the color of one of the little squares in the window. This can be done with the statement
mosaic.setColor(row,column,r,g,b);
where "row" is an integer giving the number of the row whose color I want to set, "column" is an integer giving the number of the column, and "r", "g", and "b" are of type double and specify the red, blue, and green compontents of the color I want. To use this method correctly, you need to know a few more things: If the window has R rows, the rows are numbered top-to-bottom from 0 to R-1, so the value of the parameter row must be between 0 and R-1. Similarly, columns are numbered from 0 to C-1, where C is the number of columns in the window, so columns must be between 0 and C-1. Each of the numbers r, g, and b must be in the range 0.0 to 1.0. If r has a value of 0.0, then the color contains no red component at all; if r has a value of 1.0, then it contains the maximum possible amount of red; intermediate values give intermediate levels of red. The other two color components work in the same way. All this is part of the contract of the subroutine, that is, the specification of how the subroutine is used and what it does.
With basic routines for manipulating the window in hand as a foundation, I can turn to the specific problem at hand. A basic outline for my program isOpen the window; Fill window with random colors; Move around, changing squares at random.
I already have a subroutine to do the first step.. Thus we can refine the algorithm to:Open the window; Fill window with random colors; Set the current position to the middle square in the window; Repeat forever: Randomly change color of current square; Move current position up, down, left, or right, at random;
I need to represent the current position in some way. That can be done with two int variables named currentRow and currentColumn. To open the window, we need to know how many rows and columns there are. Let's represent these quantities with constants named ROWS and COLUMNS. Giving names to the subroutines that I still have to write and using "while (true)" to implement an infinite loop, we get:mosaic = new MosaicWindow(ROWS, COLUMNS); fillWithRandomColors(); currentRow = ROWS / 2; // middle row, halfway down the window currentColumn = COLUMNS / 2; // middle column while (true) { changeToRandomColor(currentRow, currentColumn); randomMove(); }
With the proper wrapper, this is the main() routine of my program. I still have to write the subroutines fillWithRandomColors(), changeToRandomColor(int,int), and randomMove().:for (row = 0; row < ROWS; row++) for (column = 0; column < COLUMNS; column++) changeToRandomColor(row,column);
I could go on to discuss the other two subroutines, but you get the idea. Here is the complete program:public class RandomMosaicWalk { /* Program shows a window full of randomly colored squares. A "disturbance" moves randomly around in the window, randomly changing the color of each square that it visits. The program runs in an infinite loop, and so will never end on its own. */ final static int ROWS = 10; // number of rows of squares // (The rows of squares are numbered from 0 to ROWS-1) final static int COLUMNS = 20; // number of columns of squares // (The columns of squares are numbered from 0 to COLUMNS-1) static MosaicWindow mosaic; // the actual window static int currentRow; // row currently containing the disturbance static int currentColumn; // column currently containing disturbance public static void main(String[] args) { // Main program creates the window, fills it with // random colors, then moves the disturbance in // a random walk around the window. MosaicWindow mosaic = new MosaicWindow(ROWS,COLUMNS); fillWithRandomColors(); int currentRow = ROWS / 2; // start at center of window int currentColumn = COLUMNS / 2; while (true) { changeToRandomColor(currentRow, currentColumn); randomMove(); } } // end of main() static void fillWithRandomColors() { // fill every square, in each row and column, // with a random color for (row=0; row < ROWS; row++) { for (column=0; column < COLUMNS; column++) { changeToRandomColor(row, column); } } } // end of fillWithRandomColors() static void changeToRandomColor(int rowNum, int colNum) { // change the square in row number rowNum and // column number colNum to a random color. double red = Math.random(); // choose random levels in range double green = Math.random(); // 0.0 to 1.0 for red, green, double blue = Math.random(); // and blue color components = (int)(4*Math.random()); // directionNum is randomly set to 0, 1, 2, or 3 switch (directionNum) { case 0: // move up currentRow--; if (currentRow < 0) currentRow = ROWS - 1; break; case 1: // move right currentColumn++; if (currentColumn >= COLUMNS) currentColumn = 0; break; case 2: // move down currentRow ++; if (currentRow >= ROWS) currentRow = 0; break; case 3: currentColumn--; if (currentColumn < 0) currentColumn = COLUMNS - 1; break; } } // end of randomMove() } // end of class RandomMosaicWalk
End of Chapter 3
[ Next Chapter | Previous Section | Chapter Index | Main Index ] | http://math.hws.edu/eck/cs124/notes98/c3/s6.html | CC-MAIN-2018-47 | refinedweb | 1,159 | 58.01 |
Unity 5.1.2
The Unity 5.1.2 release brings you a several improvements, a couple of changes and a large number of fixes. Read the release notes below for details.
For more information about the previous main release, see the Unity 5.1
- Analytics: Added cloudProjectId to hwstat.
- Android: Audio - Enabled OpenSL for GearVR.
- Animation: Group material color channel curves. Removing one curve will automatically remove other channel curves of the same color property.
- Documentation: Docs for Audio / VR / UNet updated.
- Editor: Informative message will be shown in the material inspector when the material property block values are used.
- Graphics: Added options for opaque object sorting control, see Camera.opaqueSortMode.
- iOS/IL2CPP: Load embedded resources in memory-mapped files so that the memory used by those embedded resources is marked as constant.
- Terrain: Expose TerrainData.SetHeightsDelayedLOD and Terrain.ApplyDelayedHeightmapModification to allow users to achieve high frame rates while doing interactive terrain editing.
- Windows Editor Installer: Use dism.exe to install .net framework5, for a more silent experience when using /S silent installer option.
- Xbox One: Unity now builds with the June 2015 XDK. You must have the June XDK installed on your PC and use the matching or later recovery on your console.
Changes
- 2D: SpriteRenderer will have light and reflection probes turned off by default. They can still be turned on manually.
Fixes
- (699578) - 2D: Fixed the issue where it was unable to set Sprite mode to multiple.
- (701438) - Animation: Animating properties of the material with the custom shader does not cause error on the first play in editor.
- (699383) - Animation: Reject avatar creation when the skeleton is missing intermediary bones.
- (665246) - Animation: Remove relative material property blocks when the animator component is being removed.
- (706635) - Asset Loading: Ignoring hidden dll files.
- (690156) - Asset Management: Now allow prefab instances with a missing prefab template to be reparented.
- (670070) - Audio: Audio clip "Force to Mono" now has an option for applying normalization after downmix.
- (705599) - Audio: Fixed: FSBTool crashed during audio import on Windows XP / N platforms and very short audio files.
- (694539) - CacheServer: Asset bundle names are not properly imported from metafiles.
- (702628) - Deployment Management: Fixed crash when selecting 'Scripting Backend' in standalone Player Settings.
- (670391) - DX11: Don't spam refCount==0 error messages when some 3rd party tools hook into DX11.
- (703205) - DX11: Fixed non-native resolution fullscreen being too dark when in Linear color space.
- (686697) - Editor OSX: Fixed custom cursor getting set back to default arrow when used in the editor.
- (686697) - Editor OSX: Fixed games setting the cursor to null wouldn't take affect in the editor.
- (692047) - Editor: Removed MSVCRT dependency for WebGL build.
- (705649) - Editor: Search correct 32/64bit program files on windows for diff tools.
- (none) - Editor: Texture3D sizes up to 2048 are now allowed (previously the limit was 1024).
- (none) - GearVR: Removed log spam about user profile.
- (705573) - GI: Fixed intermittent crash related to realtime lightprobes.
- (none) - GLES: Fix for TC Particles package from the Asset Store.
- (699694) - GLES: Fixed crash when using multithreaded renderer and using shader that uses vertex colors when the mesh data doesn't contain vertex colors.
- (705269) - GLES: Fixed shader compiler crash for some shaders that use scalar pixel shader inputs, and other issues.
- (696397) - GLES: Fixed standard shader rendering issues with Mali GPUs.
- (707361) - GLES: Fixed tessellation shaders when multiple texcoords are packed into one vec4.
- (none) - GLES: Workaround for Adreno 4xx driver bug where binary shaders would break if the shader program contains geometry shaders.
- (700474) - Graphics: Fixed a bug when loading single channel JPEGs using Texture2D.LoadImage.
- (698775) - Graphics: Fixed issue in Texture2D.LoadImage when loading indexed PNG images that contain an alpha channel.
- .
- (704699) - iOS: Added support for Xcode 7 beta.
- (689410) - iOS: Allow to append builds made with different scripting backend.
- (705241) - iOS: Don't add header files to il2cpp Xcode project.
- (699907) - iOS: Don't include managed dll files in il2cpp build.
- (710126) iOS: Fixed a regression which caused appending builds with native plugins to fail
- (710818) iOS: Fixed a regression which disables appending builds in folders more than one level away from the project folder
- (702900) - iOS: Fixed stuck "Launch screen type" setting.
- (682882) - iOS: Include iOS Xcode API documentation.
- (685439) - iOS: Lightmapped objects with legacy shaders lit with realtime light in legacy deferred no longer render incorrectly.
- (695118) ,(701548) - iOS/IL2CPP: Added support for PreserveAttribute to prevent classes, methods, fields and properties from being stripped in IL2CPP.
- (705724) - iOS/IL2CPP: Allow Type.GetType(string) to return a proper value on 32-bit ARMv7 builds.
- (708137) - iOS/IL2CPP: Avoid boxing of value types during null checks in generic code.
- (700507) - iOS/IL2CPP: Avoid deadlock during UnloadUnusedAssets.
- (691607), (667147) - iOS/IL2CPP: Corrected an exception during code conversion which has the error message "Invalid global variables count" when converting some UnityScript assemblies.
- (704018) - iOS/IL2CPP: Ensure that GetCurrentMethod returns the proper value, even when the generated native method is inlined.
- (none) - iOS/IL2CPP: Fix embedded resources.
- 7860) - iOS/IL2CPP: Fixed codegen issue when using a field type a struct that has no instance fields.
- .
- (702879) - iOS/IL2CPP: Fixed marshaling arrays of structs marked with [Out] attribute.
- (696745) - iOS/IL2CPP: Generate correct C++ code for the IL add opcode with pointers in unsafe C# code.
- (699644) - iOS/IL2CPP: Handle 'void' type parameter.
- (706613) - iOS/IL2CPP: Handle invalid IL generated by UnityScript compiler for delegates.
- (698589) - iOS/IL2CPP: iOS/IL2CPP: Correct RPC implementation for the UnityEngine.Networking namespace.
- (696187) - iOS/IL2CPP: Prevent a C++ compiler error in generated code about an undeclared identifier with the test "Unused local just for stack balance".
- (702203) - iOS/IL2CPP: Prevent a C++ compiler error in generated code which happens when a pointer is assigned a value which is a uintptr_t in converted unsafe C# code.
- (691077) - iOS/IL2CPP: Prevent a crash in the NetworkManager initialization when the Stipping Level option is not set to Disabled.
- (702696) - iOS/IL2CPP: Prevent a runtime exception with IL code in an enumerator's MoveNext method when the enumerator's return type is a constrained generic type.
- (693259) - iOS/IL2CPP: Prevent AES encryption types from being incorrectly stripped when they are used.
- (703294) - iOS/IL2CPP: Prevent an exception during code generation when the default value of a field is not the same type as the field.
- (695319) - iOS/IL2CPP: Prevent an intermittent crash on ARM64 when an live object is incorrectly reclaimed but the garbage collector.
- .
- (708137) - iOS/IL2CPP: Speed up generic method calls on value types.
- (705860) - iOS/IL2CPP: The Preserve attribute can now be used in the managed code for an assembly to preserve all of the code in an assembly.
- (705860) - iOS/IL2CPP: The preserve attribute can now be used with the assembly element in a link.xml file to preserve all of the code in an assembly.
- (691008) - iOS/IL2CPP: When compiling scripts for the player, appropriate UnityEngine.UI.dll will be referenced now.
- (704998) - License: Added network timeout for all pending operations.
- (704271) - License: Clear error message once valid serial is entered.
- (700738) - License: Fixed an issue with Operating System ID changing on Windows 10.
- (702313) - License: License activation staying stuck in Updating or Connecting screen.
- (704270) - License: Replace generic invalid serial message with more meaningful message
- (706183) - Linux: Fixed key release regression.
- (none) - Mecanim: Fixed assert when using Optimize Game Object on object that are parented.
- (none) - Mecanim: Fixed continuity in FixedTime transition with ExitTime.
- (none) - Mecanim: Fixed crash when using AnimatorController in asset bundles.
- (697582) - Merge Tool: Fixwd merging of scenes/prefabs with out of order objects.
- (700533) - MonoDevelop: Fixed issue with Attach button in attach to process dialog not responding to clicks.
- (673868) - MonoDevelop: Fixed Unity crash when inspecting enum value in MonoDevelop debugger.
- (699556) - MonoDevelop: Fixed Unity crash when using the debugger to inspect a property that only has a getter that returns a struct. E.g. Sprite.bounds.
- (701421) - Networking: Added missing check for NetworkIdentity on NetworkManager object.
- (699613) - Networking: Added missing error message for more than 32 SyncVars in a NetworkBehaviour script.
- (692633) - Networking: Added missing error message for multiple NetworkManagers in a scene.
- (697809) - Networking: Added missing validation for invalid method signatures on network methods.
- (693234) - Networking: Added missing validation for SyncVars of invalid types.
- (697118) - Networking: Adding missing error message for using network custom attributes in non NetworkBehaviour derived scripts.
- (701760) - Networking: Fix for allowing multiple network components on the same game object.
- (697682) - Networking: Fix for ClientRpc call failing when called on a base class.
- (698103) - Networking: Fix for ClientRpc calls being invoked out of order on localClient.
- (696932) - Networking: Fix for ClientRpc calls not being invoked for scene objects on a local client.
- (697824) - Networking: Fix for exception when sending a game object component as an argument to RPC calls.
- (696579) - Networking: Fix for foldouts in NetworkManager inspector not saving state.
- (none) - Networking: Fix for garbage at the end of broadcast messages.
- (697502) - Networking: Fix for implementing Update() in a class derived from NetworkManager causing client connection callbacks to not be called.
- (none) - Networking: Fix for IsAcksLong flag doesn't work.
- (697754) - Networking: Fix for isServer still being true after server was stopped.
- (701235) - Networking: Fix for not being able to detect idle connections.
- (697730) - Networking: Fix for setting MaxConnection to zero causing exception in NetworkManager.
- (697102) - Networking: Fix for SyncVars not working with script inheritance.
- (698321) - Networking: Fix for UNetWeaver exception generating an exception when SyncListStruct used directly without a derived class.
- (698732) - Networking: Fix for unserializating NetworkIdentity references failing on a dedicated server.
- (none) - Networking: Fixed - localdiscovery doesn't work on osx and ios.
- (704949) - Networking: Fixed the problem with host which was added removed and added back. Last add will finish with error - cannot open socket.
- (none) - Networking: Fixed the problem with long acks.
- (701313) - Networking: Fixed UNetWeaver exception when processing large projects, also improved speed with large projects.
- (697117) - Networking: NetworkTransform now auto-detects CharacterController and pick the correct sync method when added to a game object.
- (577228) - Physics 2D: Ensure that both friction and bounce are updated when the PhysicsMaterial2D is set on a Collider2D from script.
- (705901) - Physics 2D: Ensure that Rigidbody2D interpolation or extrapolation do not modify the Transform Z position.
- (703846) - Physics 2D: Fixed a child Rigidbody2D not correctly updating its position/orientation when it's using interpolation and the parent transform changes.
- (683964), (696095) - Physics 2D: Fixed various One-Way behaviour issues in PlatformEffector2D.
- (702907) - Physics 2D: MotorSpeed on SliderJoint2D is now in meters/sec (linear motor) not degrees/sec (not angular motor).
- (697547) - Physics 2D: Restore the Rigidbody2D linear-velocity after a Rigidbody2D.MovePosition has completed.
- (701932) - Physics 2D: Rigidbody2D constraints are now based upon the center-of-mass and not the body position.
- (701202) - Physics 2D: Stop crash if 2D effector is needed but there is none.
- (697637) - Physics 2D: Stop NullReferenceException when editing PolygonCollider2D.
- (699169) - Physics: Fixed a crash when trying to report a MeshCollider error while the MeshCollider's SharedMesh was null.
- (685107) - Physics: Fixed an issue in PhysX where a capsule would fail to collide with a triangle mesh.
- (441764) - Physics: Fixed an issue in PhysX where capsule-capsule collision detection would erroneously fail when the capsules' axes were almost aligned.
- (698701), (698702) - Physics: Fixed HingeJoint SetMotor, SetLimits, SetSpring only being set correctly if the said properties was already enabled.
- (697543) - Physics: Fixed issue in PhysX where PhysX would hang on certain Android devices.
- (705471) - Physics: Fixed problem in PhysX that would cause SphereColliders to bounce when rolling over the triangles of a MeshCollider.
- (697849) - Physics: HingeJoint now correctly measures the hinge angle regardless of the initial rotation between the two hinged bodies.
- (686576) - Revert baked lightmap texture compression quality from best back to normal. Speeds up compositing step.
- (none) - Samsung TV: Resolved security issue that allowed for arbitrary code execution.
- (none) - SamsungTV: Fixed security false-positive. The 2013 and 2014 TVs can now be deployed to successfully.
- (none) - Script Editors: Generate and open solution when External Script Editor is set to Xamarin Studio.
- (693537) - Serialization: Disallow EditorOnlyPlayerSettings custom properties usage without initialization
- (none) - Shaders: Fixed broken constant buffer info on OpenGL ES compute shaders with multiple kernels
- (705485) - Shaders: Fixed GLSL/Metal translation of shaders that use all uppercase SV_TARGET semantic.
- (670391) - Shaders: Fixed GLSL/Metal translation of shaders that use non-uppercase SV_Position semantic.
- (704497), (704501) - Shaders: Fixed resource binding regression breaking TC Particles asset store package.
- (none) - Shaders: Increased timeout for shader import time processing; helps with complex compute shaders.
- (676585) - Substance: Fix hang/crash when entering playmode with the Profiler window open.
- (none) - Tizen: Added docs about native plugins on Tizen.
- (none) - Tizen: Added Tizen to the default platforms list.
- (none) - Tizen: Fixed plugin loading.
- (689600) - UI: Number of batches created for UI scene back down to 5.0 number.
- (697556) - Unified GL: Fix for DX11-style Depth-of-Field image effect: fix boolean variable handling in shader compiler.
- (none) - Unified GL: Fix for shader errors when swizzles were incorrectly applied to scalar values.
- (697556) - Unified GL: Fixed a crash when current and pending framebuffers have different attachment counts.
- (707761) - Update Checker: Wait for Home Window to be closed before checking for updates
- (none) - VR: Don't update the head pose until Camera has latched the reference frame.
- (702042) - VR: Enabling / disabling virtual reality support in the editor nolonger affects standalone players.
- (704263) - VR: Fix issue where GUI could be inadvertently flipped.
- (none) - VR: Fix issues with VRSettings.loadedDevice
- (709060), (703989) - VR: Fix rendering issues when camera parent is scaled.
- (none) - VR: Fixed anti aliasing.
- (none) - VR: Fixed aspect ratio of game view and standalone window.
- (705638) - VR: Fixed GearVR crash with Android Personal Edition.
- (none) - VR: Fixed linear lighting.
- (706852) - VR: Fixed upgrade issue from 5.1.1 which could result in VR loss of functionality.
- (none) - VR: Reset camera-to-origin pose on scene load to prevent gross error.
- (none) - WebGL: Fixed an issue using System.IO.Compression.DeflateStream API.
- (none) - WebGL: Fixed error messages when refreshing or unloading the page.
- (none) - WebGL: Fixed WWW Downloads failing if they take longer then 5 seconds.
- (none) - WebGL: Prevent a runtime error due to the NetworkManager and MasterServerInterface not being correctly stripped.
- (704102) - Windows Phone 8: Fixed crash when building from Editor.
- (694021) - Windows Phone 8.1: Fixed simulator build.
- (703879) - Windows Phone: Fixed build failure when using certain classes from System.Net namespace.
- (none) - Windows Store Apps: Fixed a rare crash at boot when reading AppxManifest.xml.
- (693303) - Windows Store Apps: Fixed extended splash screen sizing on wp8.1 and scaled WSA.
- (709350) - Windows Store Apps/Windows Phone: Fix rare build failure while copying plugins.
- (none) - Windows Store Apps/Windows Phone: Fix Universal apps build, when project name contains whitespaces
- (702282) - Windows Store Apps/Windows Phone: Fixed an issue with connecting to server using UNet.
- (670992) - Windows Store Apps/Windows Phone: Fixed serialization when inheriting from class from another assembly with internal field
- (699656) - Windows Store Apps/Windows Phone: Fixed variable synchronization between WinRT and Mono players (UNet).
- (695285) - Xbox One: Disabled standard splash screen on Xbox One, which was showing up as a blank grey screen after the initial OS load splash screen.
- (690152) - Xbox One: Fixed a bug that could cause game chat to fail when more than two players are involved.
- (none) - Xbox One: Socket descriptions now require template to function (as of April XDK). The editor GUI has been updated to make templates mandatory for all socket descriptions.
- (none) - Xbox One: The auto-added port for script debugging now implements a template, and works again. It will also get auto-added if you specify to auto-connect the profiler.
Changeset: afd2369b692a
Unity 5.1.2 | https://unity3d.com/ru/unity/whats-new/unity-5.1.2 | CC-MAIN-2019-39 | refinedweb | 2,603 | 58.18 |
In this tutorial, we’ll be focusing on creating a dashboard for an Online Retail Store. Online Retail Stores generate revenue across other e-commerce giants, apart from their own website. This dashboard focuses on showcasing a monthly performance of an online store across three e-commerce aggregators - Amazon, Ebay and Etsy. Further, we have used a combination of Charts, Maps, and KPI elements to showcase how different sources of revenue are performing, and from which geo locations are maximum orders are coming in from. Hope you have as much fun building this dashboard, as I did!
Table of Contents
Before we go ahead setting up, I wanted to show you a preview of the Online Retail Dashboard you’ll be able to create, once you’ve gone through this tutorial. Here’s a live link to dashboard in action.
Setting up the Environment
Including Dependencies We’ll be using the following dependencies for this project. To create the dashboard, you’ll need to set-up these dependencies as explained below:
- React, Bootstrap
- FusionCharts Core Package, its React Component and FusionMaps package
Including React We’ll be using Facebook’s React boilerplate today, which will set-up React along with all the utilities that we need. So, in your terminal, go ahead and enter:
$ npx create-react-app ecommerce-dashboard
To know more about
create-react-app, please refer to this link. Now, we will be adding a few more components that we will need for this tutorial, as explained below:
Including Bootstrap We will be using Bootstrap to create the layout and user-interface for our app. So, in the terminal go ahead and enter:
$ npm install --save bootstrap
Including FusionCharts core package, it's React Component and FusionMaps package We will be using FusionCharts to render charts in our dashboard app. You can go ahead and check out more about it here.
There are multiple ways to install FusionCharts, for general instructions you can check out this documentation page.
FusionCharts Direct Download
You can directly download JS files from FusionCharts website using this link and include them in your application using
<script> tag in
/public/index.html of application.
Using NPM (we will be using this!)
So, in the terminal, navigate to our working directory i.e.
ecommerce-dashboard and enter:
$ npm install --save fusioncharts
To render maps, we will need also FusionMaps definition files. There are multiple ways to install them, for more details you can check out this developer documentation page.
Direct Download
You can directly download JS files for all the maps from FusionCharts website using this link and include the respective map file which you want to render using
<script> tag in
/public/index.html of application.
Using NPM (we will be using this!)
So, in the terminal, navigate to our working directory i.e.
ecommerce-dashboard and enter:
$ npm install --save fusionmaps
FusionCharts also provides a lightweight and simple-to-use component for React that can be used to add JS charts in react app without any hassle. We will be using it in our app. Let’s install it using the command below:
$ npm install --save react-fusioncharts
You can learn more about FusionCharts react component using this link. Now that we have included all the dependencies, we will go ahead and set-up Google Sheets API.
Google Sheets API Setup
We’ll start by creating a new project for our application on developer console to fetch data from Google Sheets. For this article, I’m naming it
ecommerce-dashboard.
You can create a new project through this link.
Once the project is created, you’ll be redirected to Google Developer API dashboard. Now, we will enable Google Sheets API for our app. For this in the APIs box, click “Go to APIs overview”. Once you click “Enable APIs and Services” you’ll be presented with the API Library and we’ll go ahead and search for “Google Sheets API”.
Once you find it, click “Enable” and after it is processed you should be seeing the page below.
In the sidebar, head over to “Credentials” and click the “Create credentials” button and select “API Key”. Click the “Restrict Key” and set a name for it (I’ve named it as
EcommerceDashboardAPIKey).
Save the key generated, as we’ll need it to pull data from our Google Sheet later.
Under “API Restrictions” select the “Google Sheets API” and save. Now, we are good to go for our next step where we’ll connect Google Sheets API and fetch the data.
Connecting Google Sheets and Fetching data
Now, let’s head to the Google Sheet that we will be using for this application. Here’s a screenshot of how it looks. I’ve collected random data for 13 months focusing on KPIs of for online retail business.
Now, we will make the sheet public so that anyone can see it. For this in the File menu, click “Share”. Once you click “Get shareable link” and after it’s processed, the sheet will be shared for “Anyone with link can view” access by default.
Since we want to make the sheet public, head over to “Anyone with link can view” and click the “More” option in the drop-down. Select “On - Public on the web” option and save.
You can access the sheet I’ll be using from this link. We’ll keep a note of the spreadsheet ID (this can be found in the URL for Google Sheets, for me its
1sCgmzBIq2K9jUckLuYSWbDq4CuNUfdtuE6a5xI3I5Hw).
We will be using
batchGet method for our dashboard app. It returns one or more ranges of values from a spreadsheet. You can learn more about it here.
Let’s open up our working directory (
ecommerce-dashboard for me) in a code editor and create a new file with name
config.js. Input your API key and spreadsheet ID in it.
export default { apiKey: 'YOUR-API-KEY', spreadsheetId: '1sCgmzBIq2K9jUckLuYSWbDq4CuNUfdtuE6a5xI3I5Hw' }
Now let’s head over to
App.js file. We’ll be adding everything directly to
App.js, which came with the boilerplate. This is not ideally the best architecture, rather just a display of the concepts.
Now let’s look at the steps below to show how I’ll connect our dashboard app to Google Sheets API and fetch data from it:
- Import
config.jswe created using the code below and declare a variable with request URL for Google Sheets API.
import config from './config'; const url = `{ config.spreadsheetId }/values:batchGet?ranges=Sheet1&majorDimension=ROWS&key=${ config.apiKey }`;
- Now, we’ll set an empty array in
this.stateas shown in the code below:
constructor() { super(); this.state = { items:[] }; }
- Fetch the JSON data from React’s lifecycle
componentDidMountmethod:
componentDidMount() { fetch(url).then(response => response.json()).then(data => { let batchRowValues = data.valueRanges[0].values; const rows = []; for (let i = 1; i < batchRowValues.length; i++) { let rowObject = {}; for (let j = 0; j < batchRowValues++[++i].length; j++) { rowObject[batchRowValues[0][j]] = batchRowValues[i][j]; } rows.push(rowObject); } this.setState({ items: rows }); }); }
Awesome! Now that we have established a connection with our Google Sheets, we will start building the layout for our dashboard.
Note: You can verify the connection by logging the
items variable inside state.
Building the Dashboard Layout
We’ll be using Bootstrap to build the layout for our application. We have already installed it, now let’s import it in our application. Head over to
index.js and import the Bootstrap’s CSS file:
import "bootstrap/dist/css/bootstrap.css";
Now let’s divide our application’s layout into 4 parts:
- Navigation Section
- KPI Section
- KPI and Mini Charts Section
- Charts Section
We will also over-write some of the default styles provided by Bootstrap using our own CSS that will be present in the file
style.css which is included in
index.js file.
Creating the Navigation Section
To create this, we will consume
nav component provided by Bootstrap. You can check it out here. Below is the HTML snippet for the same:
<Nav className="navbar navbar-expand-lg fixed-top is-white is-dark-text"> <div className="navbar-brand h1 mb-0 text-large font-medium"> Online Retail Dashboard </div> <div className="navbar-nav ml-auto"> <div className="user-detail-section"> <span className="pr-2">Hi, Sean</span> <span className="img-container"> <-- add image uri here --> <img src="" className="rounded-circle" alt="user" /> </span> </div> </div> </Nav>
Since we have two navigation sections in our application we will repeat the process above and customize the second navigation section using CSS.
Now, that our navigation section is ready, we’ll create a
container to house the next three sections of our application. Here’s the HTML snippet for the same:
<div className="container-fluid"> <!-- kpi section --> <!-- kpi + mini charts section --> <!-- charts section --> </div>
You can learn more about Bootstrap containers here.
Creating the KPI Section To create this, we’ll use rows, columns and cards provided by Bootstrap to create the layout for our KPI section as shown in the image above. Below is the HTML snippet for the same:
<div className="row"> <div className="col-lg-3 col-sm-6"> <div className="card"> <div className="card-heading"> <div> Total Revenue </div> </div> <div className="card-value"> <span>$</span> </div> </div> </div> </div>
The above snippet will create one KPI card (for “Total Revenue”). Similarly, we will create cards for all 4 KPIs that we want to showcase. You can learn more about rows, columns and cards from Bootstrap’s documentation using this link.
Creating the KPI and Mini-Charts Section To create this, we’ll again use rows, columns and cards provided by Bootstrap as we did in the previous step to create the layout for our KPI section as shown in the image above. Below is the HTML snippet for the same:
<div className="row"> <div className="col-md-4 col-lg-3"> <!-- kpi layout as in previous step --> </div> <div className="col-md-8 col-lg-9"> <div className="card"> <div className="row"> <!-- row to include all mini-charts --> <div className="col-sm-4"> <div className="chart-container"> <!-- chart will come here --> </div> </div> </div> </div> </div> </div>
The above snippet will add one KPI to the left and one mini-chart section inside the card to the right. Similarly, we will add other two mini-charts layout inside the card as shown in the dashboard snapshot at the beginning of the article.
Creating the Mini-Charts Section To create this, we’ll again use rows, columns and cards provided by Bootstrap as we did in previous steps to create the layout for our charts as shown in the dashboard snapshot at the beginning of the article. Below is the HTML snippet for the same:
<div className="row"> <div className="col-md-6"> <div className="card"> <div className="chart-div"></div> <!-- chart will come here --> </div> </div> </div>
The above snippet will add one card. We can repeat the above step to create another card. If you’ve followed the above steps till now you should have a similar layout as in the dashboard snapshot at the beginning of the article. If not - don’t worry I’ll be adding the link to Github repo for this dashboard at the end of this tutorial.
Creating KPI’s
Now that our layout is ready, we will define functionality for elements and feed data to them from Google Sheets. For this, we will define a function called
getData in our component which will take the month as an argument to de-structure google sheets data present in the app’s state.
Now, we’ll loop through the data to calculate values as needed for KPIs. Below is the code to create the KPI for “Revenue from Amazon”.
getData = arg => { // google sheet data const arr = this.state.items; const arrLen = arr.length; // kpi's // amazon revenue let amRevenue = 0; for (let i = 0; i < arrLen; i++) { if (arg === arr[i]["month"]) { if (arr[i]["source"] === "AM") { amRevenue += parseInt(arr[i].revenue); } } } // setting state this.setState({ amRevenue: amRevenue }); };
Similarly, we will define variables for other KPIs and assign a value to them upon looping through the data using the above code snippet.
Once the value for KPI is calculated we will set its value in app’s state to consume it in the layout as needed. Below is an example to consume the value from the state.
<div className="row"> <div className="col-lg-3 col-sm-6"> <div className="card"> <div className="card-heading"> <div> Revenue from Amazon </div> </div> <div className="card-value"> <span>$</span> {this.state.amRevenue} </div> </div> </div> </div>
Creating Charts
Now that our KPI’s are ready, we will loop through data and prepare JSON arrays for our charts and use FusionCharts and its React component to render the charts.
For this, we will be using
getData function that we created in the previous step.
Now, we will create a file called
chart-theme.js to create a theme for charts that we will be using. This theme will have cosmetics options for all our charts so that we don’t have to define them each time we create one. Here’s how it looks like:
window.FusionCharts.register("theme", { name: "ecommerce", theme: { base: { chart: { bgAlpha: "0", canvasBgAlpha: "0", baseFont: "basefont-regular", baseFontSize: "14", baseFontBold: "0", chartBottomMargin: "0", chartTopMargin: "0", chartLeftMargin: "0", chartRightMargin: "0", canvasBottomMargin: "0", canvasTopMargin: "0", canvasRightMargin: "0", canvasLeftMargin: "0", showBorder: "0", showCanvasBorder: "0", baseFontColor: "#ffffff", captionFontBold: "0", captionFontSize: "14", subCaptionFontSize: "14", tooltipColor: "#ffffff", tooltipBgColor: "#000000", tooltipBgAlpha: "60", tooltipPadding: "5", toolTipBorderAlpha: "10", toolTipBorderRadius: "3", showValues: "0", legendBgAlpha: "0", legendBorderAlpha: "0", legendBorderThickness: "0" } }, bar2d: { chart: { placeValuesInside: "0", usePlotGradientColor: "0", showAlternateVGridColor: "0", chartLeftMargin: "5", canvasLeftMargin: "5", divLineAlpha: "10", divLineColor: "#ffffff", captionFontColor: "#8091ab", paletteColors: "#1D91C0", valuePadding: "5", yAxisName: "Orders", yAxisNameAlpha: "50", yAxisNameFontSize: "12", yAxisNamePadding: "20", valueFontBold: "0", valueFontSize: "12", plotToolText: "<div>$label<br><b>$value orders</b>", captionAlignment: "left", captionPadding: "20" } }, doughnut2d: { chart: { captionFontSize: "14", captionFontColor: "#8091ab", showLabels: "0", showValues: "0", use3DLighting: "0", showPlotBorder: "0", defaultCenterLabel: "75%", pieRadius: "45", doughnutRadius: "33", showTooltip: "0", enableRotation: "0", enableSlicing: "0", startingAngle: "90" } }, geo: { chart: { captionFontSize: "14", captionFontColor: "#8091ab", legendScaleLineThickness: "0", legendaxisborderalpha: "0", legendShadow: "0", plotFillAlpha: "85", showBorder: "1", borderColor: "#ffffff", borderThickness: "0.3", nullEntityColor: "#17202e", nullEntityAlpha: "50", entityFillHoverColor: "#17202e", captionAlignment: "left", entityToolText: "<div>$lname<br><b>$value orders</b>", chartLeftMargin: "40" } } } });
You can learn more about FusionCharts themes from this documentation page.
Now let’s begin with creating mini-charts. We will be using Doughnut Chart (
doughtnut2d) for this. You can learn more about this chart here.
getData = arg => { // google sheets data const arr = this.state.items; const arrLen = arr.length; let purchaseRate = 0; for (let i = 0; i < arrLen; i++) { if (arg === arr[i]["month"]) { purchaseRate += parseInt(arr[i].purchase_rate / 3); } } // setting state this.setState({ purchaseRate: purchaseRate }); };
Now that our mini-chart’s value is set in the state we will initiate chart instance via FusionCharts’ React component and form JSON array to render the chart. Below is code for the same:
<div className="chart-container full-height"> <ReactFC {...{ type: "doughnut2d", width: "100%", height: "100%", dataFormat: "json", dataSource: { chart: { caption: "Purchase Rate", theme: "ecommerce", defaultCenterLabel: `${this.state.purchaseRate}%`, paletteColors: "#3B70C4, #000000" }, data: [ { label: "active", value: `${this.state.purchaseRate}` }, { label: "inactive", alpha: 5, value: `${100 - this.state.purchaseRate}` } ] } }} /> </div>
This will create a mini-chart for “Purchase Rate”. Similarly, we can follow the above steps to create the other two mini-charts.
Now, let’s move to our charts section.
For this, we will define an empty array inside
getData function and push data to it, after looping through Google Sheets data. Below is code snippet for the same:
getData = arg => { // google sheets data const arr = this.state.items; const arrLen = arr.length; // order trend by brand let ordersTrendStore = []; for (let i = 0; i < arrLen; i++) { if (arg === arr[i]["month"]) { if (arr[i]["source"] === "AM") { ordersTrendStore.push({ label: "Amazon", value: arr[i].orders, displayValue: `${arr[i].orders} orders` }); } else if (arr[i]["source"] === "EB") { ordersTrendStore.push({ label: "Ebay", value: arr[i].orders, displayValue: `${arr[i].orders} orders` }); } else if (arr[i]["source"] === "ET") { ordersTrendStore.push({ label: "Etsy", value: arr[i].orders, displayValue: `${arr[i].orders} orders` }); } } } // setting state this.setState({ ordersTrendStore: ordersTrendStore }); };
Now that our chart’s data array is ready, we will initiate the charts instance via FusionCharts’ React component and form JSON array to render the chart.
<div className="chart-container"> <ReactFC {...{ type: "bar2d", width: "100%", height: "100%", dataFormat: "json", dataSource: { chart: { theme: "ecommerce", caption: "Orders Trend", subCaption: "By Stores" }, data: this.state.ordersTrendStore } }} /> </div>
This will create Bar Chart (
bar2d) chart in our application. You can learn more about this chart here.
Now that our first chart is ready, we will create our last chart which is a USA region map. For this, we have to import respective map definition file from FusionMaps package that we installed earlier. Below is code for the same:
import Maps from "fusioncharts/fusioncharts.maps"; import USARegion from "fusionmaps/maps/es/fusioncharts.usaregion";
To render the map, we will again define an empty array inside
getData function and push data to it corresponding to respective ID which can be taken from this map specification sheet, after looping through Google Sheets data. Below is code snippet for the same:
getData = arg => { // google sheets data const arr = this.state.items; const arrLen = arr.length; // order trend by region let ordersTrendRegion = []; let orderesTrendnw = 0; let orderesTrendsw = 0; let orderesTrendc = 0; let orderesTrendne = 0; let orderesTrendse = 0; for (let i = 0; i < arrLen; i++) { orderesTrendnw += parseInt(arr[i].orders_nw); orderesTrendsw += parseInt(arr[i].orders_sw); orderesTrendc += parseInt(arr[i].orders_c); orderesTrendne += parseInt(arr[i].orders_ne); orderesTrendse += parseInt(arr[i].orders_se); } ordersTrendRegion.push({ id: "01", value: orderesTrendne }, { id: "02", value: orderesTrendnw },{ id: "03", value: orderesTrendse }, { id: "04", value: orderesTrendsw }, { id: "05", value: orderesTrendc }); // setting state this.setState({ ordersTrendRegion: ordersTrendRegion }); };
Now that our map’s data array is ready, we will initiate the charts instance via FusionCharts’ React component and form JSON array to render the map.
<div className="chart-container"> <ReactFC {...{ type: "usaregion", width: "100%", height: "100%", dataFormat: "json", dataSource: { chart: { theme: "ecommerce", caption: "Orders Trend", subCaption: "By Region" }, colorrange: { code: "#F64F4B", minvalue: "0", gradient: "1", color: [ { minValue: "10", maxvalue: "15", code: "#EDF8B1" }, { minvalue: "15", maxvalue: "20", code: "#18D380" } ] }, data: this.state.ordersTrendRegion } }} /> </div>
This will render our map. You can know more about maps and how to use them here.
We will now call
getData function with
Jan 2019 as an argument from
componentDidMount method so that our dashboard loads with Jan 2019 data present in Google Sheet by default. If you’ve followed the above steps till now you should have a functional dashboard as in the image below:
I hope this tutorial will help you create this dashboard using Google Sheets! Now you can work your magic on adding more UI elements, charts, KPIs and more features.
I have added some styling and functionality myself and also used Styled Components for ease. You can know more about Styled Components here. And, you can check out the final live dashboard here.
For any references, you can check out the source code from this Github repository. If you have any questions/feedback, comment below or yell at me on Twitter! | https://scotch.io/tutorials/building-an-online-retail-dashboard-in-react | CC-MAIN-2019-22 | refinedweb | 3,192 | 55.54 |
User Tag List
Results 1 to 3 of 3
- Join Date
- Apr 2006
- Location
- MA, USA
- 38
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Looking For Feedback: What do you think about this array structure?
I'm creating a personal CMS (no flames please lol).
I'm working on the interface users will use to create new plugins/modules/addons. I came up with this idea last night while lying in bed last night, and starting working on it this morning. This is what I've come up with so far.
The back end is OO, I plan on sticking to the PSR guidelines, and no, I don't want to use Drupal or Wordpress :-p (trying to head off any unhelpful comments here).
A parsing class will parse this array to build what the site needs regarding routing and permissions. It's still a work in progress, but I think I have something to go on. I'm an intermediate developer and it would be great if I could get positive constructive criticism from the community.
This is a little description of the array:
Here are a couple examples of how it would be used to create a hello_world plugin:
Single Page Simple Example -
Single Array Complex Example -
Multiple Pages and Blocks Example -
Overrides Example -
What is OO? Do you mean Object-Oriented Programming? If you do mean OOP then to be honest you are wasting your time and effort.
I also want to add what you're talking about has nothing to do with setting up a personal Content Management System, I have (still creating) a CMS website <snip/>
PSR guidelines are nice, but in my opinion it is more important to write proper code with commenting than sticking to something that few people follow faithfully.
Last edited by Mittineague; Aug 4, 2013 at 21:18. Reason: removing unnecessary link
- Join Date
- Apr 2006
- Location
- MA, USA
- 38
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Yes, I meant the back end is Object Oriented. And the whole point of mentioning that stuff was to head off any discussion about it.
And the PSR guidelines are mainly focused on code naming conventions and white space (spaces vs tabs), not the actual algorithms you're creating. Just like the PEAR and Zend coding styles. They have nothing to do with the code itself, just how it looks and making it easier to know what's what when you're looking at it (maybe not quite so much with PSR-0, but that's just a recommended namespace/folder structure for auto-loading classes if that's your thing, and haven't really looked too far into PSR-3 yet).
But this thread doesn't have anything to do with that. I'm just curious about feedback regarding the data structure.
And this data structure does have a lot to do with setting up a CMS if it's part of the API you're creating for plugin developers. In the back-end I'll be parsing that array and setting up and creating the features/routes/permissions for pages and blocks, along with allowing other plugins the opportunity to override any settings and add to the settings without having to touch another plugins code base, while at the same time allowing the back-end to check for any conflicts inside the plugin overrides, and any conflicts with other 3rd party plugin overrides, before executing the overrides so it can exit gracefully instead of having strange side effects or just blowing up on you.
And I believe this structure will allow me to add to it in the future without breaking existing plugins; like adding more properties (i.e. permissions); or different content types (i.e. pages, blocks).
So with those things in mind, is there any additional feedback?
Bookmarks | http://www.sitepoint.com/forums/showthread.php?1134693-Looking-For-Feedback-What-do-you-think-about-this-array-structure | CC-MAIN-2014-23 | refinedweb | 641 | 64.75 |
The onto2vocabulary tool creates files that require -I/sopranoprefix/include/soprano, but soprano.pc only provides -I/sopranoprefix/include. This patch adds the required -I flag to the .pc file.
Could you please provide an example. I do not see where onto2vocabularyclass would use any soprano includes.
For me, the generated header file always has the line
which is installed in /prefix/include/soprano. I'll try to manufacture a dummy example to recreate the problem.
(First and foremost, I should've mentioned this is on Karmic, hence Soprano 2.3.1. However, no mention in the changelog about any similar bug.)
Dammit! Sourceforge is acting up and not allowing me to upload a sample. I put a schema file up on pastie, it's at. I generated C++ code from that schema with the command
onto2vocabularyclass --name Example --encoding rdfxml --namespace example schema.rdfs
In the resulting header file you may see the problematic include.
I see. This is a default that is there for historical reasons. I suggest using --no-visibility-export or if you want to export the symbols in a lib --export-module.
Log in to post a comment. | https://sourceforge.net/p/soprano/bugs/13/ | CC-MAIN-2017-51 | refinedweb | 193 | 60.31 |
This morning we had homemade popovers for breakfast - they were great!! So great that I forgot to take a picture until after I finished one and had ripped open the second.
I’m not making any promises, but if you’re at our house in the winter months and you ask nicely, you too could enjoy this treat.
December 30, 2018
December 21, 2018
"...if you want to learn something, I can't stop you. If you don't...I cannot teach you."<<
August 28, 2018
Some observations of doing a bit of data analysis with DBSCAN and pandas in a Jupyter notebook
Here is a Jupyter notebook I was using today to parse the classifications from the Steelpan Vibrations project. I'm leaving some of the notes here as a reminder to myself for the future. (I learned how to put the Jupyter notebook into the blog from this page.)
I really want to share this because in all my reading on using DBSCAN to do cluster analysis, I had a hard time finding any page online that was describing how the coordinates of the points identified in a cluster could be paired with matched data from the larger (original) data set. When I found the solution (see link in the comments between cells below) it was really obvious, but it was painful not knowing even how to google for what I was looking for.
Function to do the cluster identification with DBSCAN:
In [31]:
def dbscan(crds): bad_xy = [] #might need to change this X = np.array(crds) db = DBSCAN(eps=18, min_samples=3).fit(X) core_samples_mask = np.zeros_like(db.labels_, dtype=bool) core_samples_mask[db.core_sample_indices_] = True labels = db.labels_ n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0) unique_labels = set(labels) colors = plt.cm.Spectral(np.linspace(0, 1, len(unique_labels))) for k, col in zip(unique_labels, colors): if k == -1: # Black used for noise. col = 'k' class_member_mask = (labels == k) # These are the definitely "good" xy values. xy = X[class_member_mask & core_samples_mask] plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=col, markeredgecolor='k', markersize=14) #print("\n Good? xy = ",xy) #print("X = ",X) # These are the "bad" xy values. Note that some maybe-bad and maybe-good are included here. xy = X[class_member_mask & ~core_samples_mask] plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=col, markeredgecolor='k', markersize=6) #print("\n Bad? xy = ",xy) bad_xy.append(xy) plt.title('Estimated number of clusters: %d' % n_clusters_) plt.xlim(0, 512) plt.ylim(0, 384) clusters = [X[labels == i] for i in range(n_clusters_)] #print(clusters) #print(db.labels_) return clusters, labels
Import the classifications into a pandas DataFrame. I'm using header=None because there were no headings in the csv file:
In [32]:
import pandas as pd df=pd.read_csv('averages-strike1.csv', sep=',',header=None)
This is the main part of the code that ends up calling the dbscan function at the end:
In [34]:
from matplotlib.patches import Ellipse import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib.colors as col cmap_1 = cm.ScalarMappable(col.Normalize(1, 11, cm.gist_rainbow)) import numpy as np from sklearn.cluster import DBSCAN x_val = [] y_val = [] frng = [] crds = [] ell = [] for centers in df.values: x_val.append(centers[0]) y_val.append(centers[1]) frng.append(centers[3]) crds.append([centers[0], centers[1]]) ell.append(Ellipse(xy=[centers[0], centers[1]], width=centers[4], height=centers[5], angle=centers[6])) centers_raw = {'XVal': x_val, 'YVal': y_val, 'Fringe': frng} centers_df = pd.DataFrame(centers_raw, columns=['XVal', 'YVal', 'Fringe']) plt.figure(0) plt.scatter(centers_df.XVal, centers_df.YVal, s=20, c=cmap_1.to_rgba(centers_df.Fringe), alpha=.6) plt.xlim(0, 512) plt.ylim(0, 384) #plt.title('Subject id = %s'%(coords_x[0][2])) plt.show() #print(crds) plt.figure(1) clusters, labels = dbscan(crds)
/>
/>
/Users/amorriso/anaconda/lib/python3.6/site-packages/matplotlib/lines.py:1206: FutureWarning: comparison to `None` will result in an elementwise object comparison in the future. if self._markerfacecolor != fc:
Check the DataFrame once, and then check it again after renaming the columns:
In [30]:
df[:15]
Out[30]:
In [7]:
labels
Out[7]:
array([0, 0, 0, ..., 0, 1, 3])
These next two lines are the magic that connect the clusters identified by DBSCAN with the original classifications so that we can plot the fringe measurements for each cluster over time.
Finally figured this out by reading the question posted here:
Finally figured this out by reading the question posted here:
In [8]:
cluster=pd.Series(labels) df["cluster"] = cluster
Rename the DataFrame columns:
In [10]:
df = df.rename(index=str, columns={0: "x", 1: "y",2:"filename", 3:"fringe",4:"rx", 5:"ry",6:"angle"})
Assign each cluster its own variable:
In [27]:
cluster0 = df[df['cluster']==0] cluster1 = df[df['cluster']==1] cluster2 = df[df['cluster']==2] cluster3 = df[df['cluster']==3] cluster4 = df[df['cluster']==4] cluster5 = df[df['cluster']==5] cluster6 = df[df['cluster']==6] cluster7 = df[df['cluster']==7]
Make plots!!!
In [29]:
plt.scatter(cluster0.index, cluster0.fringe) plt.show()
/>
In [36]:
plt.scatter(cluster1.index, cluster1.fringe) plt.show()
/>
In [37]:
plt.scatter(cluster2.index, cluster2.fringe) plt.show()
/>
In [38]:
plt.scatter(cluster3.index, cluster3.fringe) plt.show()
/>
In [39]:
plt.scatter(cluster4.index, cluster4.fringe) plt.show()
/>
In [43]:
plt.scatter(cluster5.index, cluster5.fringe) plt.show()
/> | http://blog.drewsday.com/2018/ | CC-MAIN-2020-16 | refinedweb | 887 | 51.95 |
Follow @jongalloway:
I'm sure I'm missing a few, and I'll update the list.
Building a Twitter network that follows topics you're interested in allows you to use other tools like Cadmus to automatically summarize top content by leveraging the collective input of many users.?
These posts aren't automatically drawn from a pool of RSS feeds or anything - I pick a new post for each day of the year.
I have a few important selection criteria:.
The Community Spotlight is available as an RSS feed, so you might want to subscribe to it:
If you're an ASP.NET developer, you might consider setting the ASP.NET Community Spotlight as the content for your Visual Studio Start Page. It's really easy - here's how to do it in Visual Studio 2010:
Now, every time you start up Visual Studio you'll see great content from members of the ASP.NET community:
You can also configure - and disable, if you'd like - the Visual Studio start page in the Tools / Options / Environment / Startup dialog.?
I recently mentioned how I contributed C# syntax for CodeMirror; what I didn't talk about was how incredibly easy it was. I think the biggest obstacles to open source contribution are:
What you might not know is that you can contribute useful code to a project in just a few minutes, even without having git installed or any git know-how - you could submit a patch from your mobile-device-of-choice if you really wanted to.
Note for the haters: The normal workflow to contributing to a project is via the standard git tooling, and I've done that. I was happily surprised to see that the github site supports project contribution without requiring that full workflow, which is nice for simple cases. The method I'm showing here is only appropriate for very simple changes.
If you're looking to contribute, you'll generally want the most current source. The simplest way to do that is to hit the download button, then grab the zip.
In my case, I made a change, verified I didn't break anything, and gave it the Works On My Machine official certification. At this point, I decided I wanted to contribute my change. Make sure to follow the standard practices here:
If you're new to distributed version control systems (git, mercurial, etc.) the term "fork" may kind of throw you off. In the open source world, forking a project previously used to indicate that you were in some way unhappy with the original project and were starting up a new project. In DVCS, forking is good, natural, healthy, and beautiful. Try it: go fork a random project, check out your fork, and delete it. No harm done.
Forking a project on GitHub is literally a one-click thing:
Word up. Now you have your own fork and can start making changes.
Here's the trick I came across: if you're making a simple change, you don't need to do the git clone / push remote business. If you're planning to continue working on your fork long-term, of course, you'd want to do that, but if you're doing a drive-by contribution there's no need for any of that. You can browse to the file on your repo and edit it-place.
So, click the edit button, copy your local edits in, enter a commit message, and commit your changes.
Make sure you're happy with your changes, then submit a pull request. That's as easy as clicking the Pull Request link near the top of the page.
If you already had a code change that you were happy with, you could easily follow the above steps in under 5 minutes. Don't torment project owners with low quality pull requests, but as someone who's admin'd several open source projects, I'm always thrilled to get a thoughtful submission. I'm generally more of a CodePlex / BitBucket fan, but you gotta hand it to GitHub - they've made the drive-by commit drop dead simple.: void volatile while add alias ascending descending dynamic from get" +
" global group into join let orderby partial remove select set value var yield")
});
The key is to find a similar language which is already supported and modify it..
To recap from before, most of the samples you'll see for using Mono.CSharp look like this (undoubtedly copied from Miguel's blog):
var report = new Report(new ConsoleReportPrinter());
var evaluator = new Evaluator(new CompilerSettings(), report);
evaluator.Run("DateTime.Now");
The problem is that the ConsoleReportPrinter writes to Console output, which isn't doing me any good.
// Mono.CSharp.ConsoleReportPrinter
public override void Print(AbstractMessage msg)
{
base.Print(msg);
if (base.Stacktrace)
{
Console.WriteLine(ConsoleReportPrinter.FriendlyStackTrace(new StackTrace(true)));
}
}
ConsoleReportPrinter's base is StreamReportPrinter, though, and that works just fine with a StringWriter, like this:
var reportWriter = new StringWriter();
try
{
var report = new Report(new StreamReportPrinter(reportWriter));
var evaluator = new Evaluator(new CompilerSettings(), report);
evaluator.Run("using System.ComponentModel.DataAnnotations;");
evaluator.Run(modelDefinition);
object model = evaluator.Evaluate("new Monkey();");
return View(model);
}
catch
{
string result = reportWriter.ToString();
return Content(result);
}
Running this gives some useful output, indicating the compilation results:
{interactive}(1,30): error CS0234: The type or namespace name `DataAnnotations' does not exist in the namespace `System.ComponentModel'. Are you missing an assembly reference? {interactive}(1,30): error CS0234: The type or namespace name `DataAnnotations' does not exist in the namespace `System.ComponentModel'. Are you missing an assembly reference? {interactive}(1,6): error CS0246: The type or namespace name `Monkey' could not be found. Are you missing a using directive or an assembly reference?
Now that we've got the results as a string, they can be logged or handled appropriately.
Recently, while reviewing the VB.NET translation of the MVC Music Store tutorial, I noticed that none of the controllers / models / classes in general have namespaces. I was going to blow up on the person who did the translation like a bad FxCop, but I fired up a new MVC 3 / VB.NET app and saw the project template doesn't use namespaces, and that the New Controller wizard doesn't use a namespace, etc. After checking with the ASP.NET team, I decided to post the VB.NET source code without explicit namespaces in each class, because that's how the code would look if you followed the steps in the tutorial.
I'm sure developers who work with both VB.NET and C# regularly know this; I pretty much moved from VB6 to C# and this was news to me, so I thought I'd share it.
When you're creating a new class in a C# application, the class will have a namespace that matches its path in the application. The default project structure for an ASP.NET MVC application has a Controllers directory, so all controller classes in the MvcMusicStore application (for example) are in the MvcMusicStore.Controllers namespace.
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using MvcMusicStore.Models;
namespace MvcMusicStore.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
// ...
Note: that's just the default. You can use any namespace you'd like; ASP.NET MVC doesn't use the namespace / directory location in locating your controllers.
Controller classes created using the "Add Controller" tooling in Visual Studio will look like this:
Public Class HomeController
Inherits Controller
Public Function Index() As ActionResult
' ...
However, if you reflected over the assembly, you'd see that the HomeController class is in the MvcMusicStore namespace, as are all other classes in the assembly. That's because in VB.NET you have a default namespace that's set in the project properties, and that namespace is applied to all the generated assemblies.
I'd have guessed that I could drop a namespace definition into the class and it would then work like I'm used to with C#, but that's not the case. If I added the same namespace that's in my C# class (using Namespace MvcMusicStore.Controllers) it would be still be prefixed by the project's default namespace, so I'd end up with my HomeController class in MvcMusicStore.MvcMusicStore.Controllers.
In the end, I decided it was best to follow the When In Rome approach and fit with how the standard ASP.NET MVC VB project templates work. Looking back on my first steps from VB into C#, I remember being a little confused and frustrated by the implied requirement to drop namespaces everywhere, and I didn't even really reconsider it until I read Jeff Atwood's A Modest Namespace Proposal post asking why we're all slavishly adding unnecessary namespaces in cases when they add no value.
Note: Many posts that compare or even mention both C# and VB bring out the crazies. Be warned that I will probably edit any "my language is better that your language" comments, replacing bile with lyrics from contemporary popular music. | http://weblogs.asp.net/jgalloway/archive/2011/06.aspx | CC-MAIN-2014-15 | refinedweb | 1,509 | 54.63 |
In the last article, we learned what goes into planning for a community-driven site. We saw just how many considerations are needed to start accepting user submissions, using what I learned from my experience building Style Stage as an example.
Now that we’ve covered planning, let’s get to some code! Together, we’re going to develop an Eleventy setup that you can use as a starting point for your own community (or personal) site.
This article will cover:
- How to initialize Eleventy and create useful develop and build scripts
- Recommended setup customizations
- How to define custom data and combine multiple data sources
- Creating layouts with Nunjucks and Eleventy layout chaining
- Deploying to Netlify
The vision
Let’s assume we want to let folks submit their dogs and cats and pit them against one another in cuteness contests.
We’re not going to get into user voting in this article. That would be so cool (and totally possible with serverless functions) but our focus is on the pet submissions themselves. In other words, users can submit profile details for their cats and dogs. We’ll use those submissions to create a weekly battle that puts a random cat up against a random dog on the home page to duke it out over which is the most purrrfect (or woof-tastic, if you prefer).
Let’s spin up Eleventy
We’ll start by initializing a new project by running
npm init on any directory you’d like, then installing Eleventy into it with:
npm install @11ty/eleventy
While it’s totally optional, I like to open up the
package-json file that’s added to the directory and replace the
scripts section with this:
"scripts": { "develop": "eleventy --serve", "build": "eleventy" },
This allows us to start developing Eleventy in a development environment (
npm run develop) that includes Browsersync hot-reloading for local development. It also adds a command that compiles and builds our work (
npm run build) for deployment on a production server.
If you’re thinking, “npm what?” what we’re doing is calling on Node (which is something Eleventy requires). The commands noted here are intended to be run in your preferred terminal, which may be an additional program or built-in to your code editor, like it is in VS Code.
We’ll need one more npm package, fast-glob, that will come in handy a little later for combining data. We may as well install it now:
npm install --save-dev fast-glob.
Let’s configure our directory
Eleventy allows customizing the input directory (where we work) and output directory (where our built work goes) to provide a little extra organization.
To configure this, we’ll create the
eleventy.js file at the root of the project directory. Then we’ll tell Eleventy where we want our input and output directories to go. In this case, we’re going to use a
src directory for the input and a
public directory for the output.
module.exports = function (eleventyConfig) { return dir: { input: "src", output: "public" }, }; };
Next, we’ll create a directory called
pets where we’ll store the pets data we get from user submissions. We can even break that directory down a little further to reduce merge conflicts and clearly distinguish cat data from dog data with
cat and
dog subdirectories:
pets/ cats/ dogs/
What’s the data going to look like? Users will send in a JSON file that follows this schema, where each property is a data point about the pet:
{ "name": "", "petColor": "", "favoriteFood": "", "favoriteToy": "", "photoURL": "", "ownerName": "", "ownerTwitter": "" }
To make the submission process crystal clear for users, we can create a
CONTRIBUTING.md file at the root of the project and write out the guidelines for submissions. GitHub takes the content in this file and uses displays it in the repo. This way, we can provide guidance on this schema such as a note that
favoriteFood,
favoriteToy, and
ownerTwitte are optional fields.
A
README.md file would be just as fine if you’d prefer to go that route. It’s just nice that there’s a standard file that’s meant specifically for contributions.
Notice
photoURL is one of those properties. We could’ve made this a file but, for the sake of security and hosting costs, we’re going to ask for a URL instead. You may decide that you are willing to take on actual files, and that’s totally cool.
Let’s work with data
Next, we need to create a combined array of data out of the individual cat files and dog files. This will allow us to loop over them to create site pages and pick random cat and dog submissions for the weekly battles.
Eleventy allows node
module.exports within the
_data directory. That means we can create a function that finds all cat files and another that finds all dog files and then creates arrays out of each set. It’s like taking each cat file and merging them together to create one data set in a single JavaScript file, then doing the same with dogs.
The filename used in
_data becomes the variable that holds that dataset, so we’ll add files for cats and dogs in there:
_data/ cats.js dogs.js
The functions in each file will be nearly identical — we’re merely swapping instances of “cat” for “dog” between the two. Here’s the function for cats:
const fastglob = require("fast-glob"); const fs = require("fs"); module.exports = async () => { // Create a "glob" of all cat json files const catFiles = await fastglob("./src/pets/cats/*.json", { caseSensitiveMatch: false, }); // Loop through those files and add their content to our `cats` Set let cats = new Set(); for (let cat of catFiles) { const catData = JSON.parse(fs.readFileSync(cat)); cats.add(catData); } // Return the cats Set of objects within an array return [...cats]; };
Does this look scary? Never fear! I do not routinely write node either, and it’s not a required step for less complex Eleventy sites. If we had instead chosen to have contributors add to an ever growing single JSON file with
_data, then this combination step wouldn’t be necessary in the first place. Again, the main reason for this step is to reduce merge conflicts by allowing for individual contributor files. It’s also the reason we added fast-glob to the mix.
Let’s output the data
This is a good time to start plugging data into the templates for our UI. In fact, go ahead and drop a few JSON files into the
pets/cats and
pets/dogs directories that include data for the properties so we have something to work with right out of the gate and test things.
We can go ahead and add our first Eleventy page by adding a
index.njk file in the src directory. This will become the home page, and is a Nunjucks template file format.
Nunjucks is one option of many for creating templates with Eleventy. See the docs for a full list of templating options.
Let’s start by looping over our data and outputting an unordered list both for cats and dogs:
<ul> <!-- Loop through cat data --> {% for cat in cats %} <li> <a href="/cats/{{ cat.name | slug }}/">{{ cat.name }}</a> </li> {% endfor %} </ul> <ul> <!-- Loop through dog data --> {% for dog in dogs %} <li> <a href="/dogs/{{ dog.name | slug }}/">{{ dog.name }}</a> </li> {% endfor %} </ul>
As a reminder, the reference to
cats and
dogs matches the filename in
_data. Within the loop we can access the JSON keys using dot notation, as seen for
cat.name, which is output as a Nunjucks template variable using double curly braces (e.g.
{{ cat.name }}).
Let’s create pet profile pages
Besides lists of cats and dogs on the home page (
index.njk), we also want to create individual profile pages for each pet. The loop indicated a hint at the structure we’ll use for those, which will be
[pet type]/[name-slug].
The recommended way to create pages from data is via the Eleventy concept of pagination which allows chunking out data.
We’re going to create the files responsible for the pagination at the root of the
src directory, but you could nest them in a custom directory, as long as it lives within src and can still be discovered by Eleventy.
src/ cats.njk dogs.njk
Then we’ll add our pagination information as front matter, shown for cats:
--- pagination: data: cats alias: cat size: 1 permalink: "/cats/{{ cat.name | slug }}/" ---
The
data value is the filename from
_data. The
alias value is optional, but is used to reference one item from the paginated array.
size: 1 indicates that we’re creating one page per item of data.
Finally, in order to successfully create the page output, we need to also indicate the desired permalink structure. That’s where the
alias value above comes into play, which accesses the
name key from the dataset. Then we are using a built-in filter called
slug that transforms a string value into a URL-friendly string (lowercasing and converting spaces to dashes, etc).
Let’s review what we have so far
Now is the time to fire up Eleventy with
npm run develop. That will start the local server and show you a URL in the terminal you can use to view the project. It will show build errors in the terminal if there are any.
As long as all was successful, Eleventy will create a
public directory, which should contain:
public/ cats/ cat1-name/index.html cat2-name/index.html dogs/ dog1-name/index.html dog2-name/index.html index.html
And in the browser, the index page should display one linked list of cat names and another one of linked dog names.
Let’s add data to pet profile pages
Each of the generated pages for cats and dogs is currently blank. We have data we can use to fill them in, so let’s put it to work.
Eleventy expects an
_includes directory that contains layout files (“templates”) or template partials that are included in layouts.
We’ll create two layouts:
src/ _includes/ base.njk pets.njk
The contents of base.njk will be an HTML boilerplate. The
<body> element in it will include a special template tag,
{{ content | safe }}, where content passed into the template will render, with safe meaning it can render any HTML that is passed in versus encoding it.
Then, we can assign the homepage,
index.md, to use the
base.njk layout by adding the following as front matter. This should be the first thing in
index.md, including the dashes:
--- layout: base.njk ---
If you check the compiled HTML in the
public directory, you’ll see the output of the cat and dog loops we created are now within the
<body> of the
base.njk layout.
Next, we’ll add the same front matter to
pets.njk to define that it will also use the
base.njk layout to leverage the Eleventy concept of layout chaining. This way, the content we place in
pets.njk will be wrapped by the HTML boilerplate in
base.njk so we don’t have to write out that HTML each and every time.
In order to use the single
pets.njk template to render both cat and dog profile data, we’ll use one of the newest Eleventy features called computed data. This will allow us to assign values from the cats and dogs data to the same template variables, as opposed to using
if statements or two separate templates (one for cats and one for dogs). The benefit is, once again, to avoid redundancy.
Here’s the update needed in
cats.njk, with the same update needed in
dogs.njk (substituting
cat with
dog):
eleventyComputed: title: "{{ cat.name }}" petColor: "{{ cat.petColor }}" favoriteFood: "{{ cat.favoriteFood }}" favoriteToy: "{{ cat.favoriteToy }}" photoURL: "{{ cat.photoURL }}" ownerName: "{{ cat.ownerName }}" ownerTwitter: "{{ cat.ownerTwitter }}"
Notice that
eleventyComputed defines this front matter array key and then uses the alias for accessing values in the
cats dataset. Now, for example, we can just use
{{ title }} to access a cat’s name and a dog’s name since the template variable is now the same.
We can start by dropping the following code into
pets.njk to successfully load cat or dog profile data, depending on the page being viewed:
<img src="{{ photoURL }}" /> <ul> <li><strong>Name</strong>: {{ title }}</li> <li><strong>Color</strong>: {{ petColor }}</li> <li><strong>Favorite Food</strong>: {{ favoriteFood if favoriteFood else 'N/A' }}</li> <li><strong>Favorite Toy</strong>: {{ favoriteToy if favoriteToy else 'N/A' }}</li> {% if ownerTwitter %} <li><strong>Owner</strong>: <a href="{{ ownerTwitter }}">{{ ownerName }}</a></li> {% else %} <li><strong>Owner</strong>: {{ ownerName }}</li> {% endif %} </ul>
The last thing we need to tie this all together is to add
layout: pets.njk to the front matter in both
cats.njk and
dogs.njk.
With Eleventy running, you can now visit an individual pet page and see their profile:
We’re not going into styling in this article, but you can head over to the sample project repo to see how CSS is included.
Let’s deploy this to production!
The site is now in a functional state and can be deployed to a hosting environment!
As recommended earlier, Netlify is an ideal choice, particularly for a community-driven site, since it can trigger a deployment each time a submission is merged and provide a preview of the submission before sending it for review.
If you choose Netlify, you will want to push your site to a GitHub repo which you can select during the process of adding a site to your Netlify account. We’ll tell Netlify to serve from the
public directory and
run npm run build when new changes are merged into the main branch.
The sample site includes a
netlify.toml file which has the build details and is automatically detected by Netlify in the repo, removing the need to define the details in the new site flow.
Once the initial site is added, visit Settings → Build → Deploy in Netlify. Under Deploy contexts, select “Edit” and update the selection for “Deploy Previews” to “Any pull request against your production branch / branch deploy branches.” Now, for any pull request, a preview URL will be generated with the link being made available directly in the pull request review screen.
Let’s start accepting submissions!
Before we pass Go and collect $ 100, it’s a good idea to revisit the first post and make sure we’re prepared to start taking user submissions. For example, we ought to add community health files to the project if they haven’t already been added. Perhaps the most important thing is to make sure a branch protection rule is in place for the main branch. This means that your approval is required prior to a pull request being merged.
Contributors will need to have a GitHub account. While this may seem like a barrier, it removes some of the anonymity. Depending on the sensitivity of the content, or the target audience, this can actually help vet (get it?) contributors.
Here’s the submission process:
- Fork the website repository.
- Clone the fork to a local machine or use the GitHub web interface for the remaining steps.
- Create a unique .json file within src/pets/cats or src/pets/dogs that contains required data.
- Commit the changes if they’re made on a clone, or save the file if it was edited in the web interface.
- Open a pull request back to the main repository.
- (Optional) Review the Netlify deploy preview to verify information appears as expected.
- Merge the changes.
- Netlify deploys the new pet to the live site.
A FAQ section is a great place to inform contributors how to create pull request. You can check out an example on Style Stage.
Let’s wrap this up…
What we have is fully functional site that accepts user contributions as submissions to the project repo. It even auto-deploys those contributions for us when they’re merged!
There are many more things we can do with a community-driven site built with Eleventy. For example:
- Markdown files can be used for the content of an email newsletter sent with Buttondown. Eleventy allows mixing Markdown with Nunjucks or Liquid. So, for example, you can add a Nunjucks for loop to output the latest five pets as links that output in Markdown syntax and get picked up by Buttondown.
- Auto-generated social media preview images can be made for social network link previews.
- A commenting system can be added to the mix.
- Netlify CMS Open Authoring can be used to let folks make submissions with an interface. Check out Chris’ great rundown of how it works.
My Meow vs. BowWow example is available for you to fork on GitHub. You can also view the live preview and, yes, you really can submit your pet to this silly site. 🙂
Best of luck creating a healthy and thriving community!
The post A Community-Driven Site with Eleventy: Building the Site appeared first on CSS-Tricks.
You can support CSS-Tricks by being an MVP Supporter. | http://design-lance.com/tag/building/ | CC-MAIN-2020-40 | refinedweb | 2,867 | 63.7 |
import local function from a module housed in another directory with relative imports in jupyter notebook using python3
I have a directory structure similar to the following
meta_project project1 __init__.py lib module.py __init__.py notebook_folder notebook.jpynb
When working in
notebook.jpynb if I try to use a relative import to access a function
function() in
module.py with:
from ..project1.lib.module import function
I get the following error
SystemError Traceback (most recent call last) <ipython-input-7-6393744d93ab> in <module>() ----> 1 from ..project1.lib.module import function SystemError: Parent module '' not loaded, cannot perform relative import
Is there any way to get this to work using relative imports?
Note, the notebook server is instantiated at the level of the
meta_project directory, so it should have access to the information in those files.
Note, also, that at least as originally intended
project1 wasn't thought of as a module and therefore does not have an
__init__.py file, it was just meant as a file-system directory. If the solution to the problem requires treating it as a module and including an
__init__.py file (even a blank one) that is fine, but doing so is not enough to solve the problem.
I share this directory between machines and relative imports allow me to use the same code everywhere, & I often use notebooks for quick prototyping, so suggestions that involve hacking together absolute paths are unlikely to be helpful.
Edit: This is unlike Relative imports in Python 3, which talks about relative imports in Python 3 in general and – in particular – running a script from within a package directory. This has to do with working within a jupyter notebook trying to call a function in a local module in another directory which has both different general and particular aspects.
I had almost the same example as you in this notebook where I wanted to illustrate the usage of an adjacent module's function in a DRY manner.
My solution was to tell Python of that additional module import path by adding a snippet like this one to the notebook:
import os import sys module_path = os.path.abspath(os.path.join('..')) if module_path not in sys.path: sys.path.append(module_path)
This allows you to import the desired function from the module hierarchy:
from project1.lib.module import function # use the function normally function(...)
Note that it is necessary to add empty
__init__.py files to project1/ and lib/ folders if you don't have them already.
From: stackoverflow.com/q/34478398 | https://python-decompiler.com/article/2015-12/import-local-function-from-a-module-housed-in-another-directory-with-relative-im | CC-MAIN-2020-10 | refinedweb | 424 | 54.22 |
Red Hat Bugzilla – Bug 24987
Problems with installation
Last modified: 2007-04-18 12:30:55 EDT
After redhat tries to pull the base files off the CDROM, this error occurs
Running anaconda - may take some time
to load...
Could not find platform independent libraries
<prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_
prefix>]
'import file' failed; use -v for traceback
Traceback (innermost last):
File "/usr/bin/anaconda", line 3, in ?
import sys, os, signal
ImportError: No module named os
install exited abnormaly
System:
Intel P3 800 /w Intel motherboard
Vodoo 5500 AGP
2 Maxtor UATA 66 Harddrives
2 IDE Cdroms
Linksys Ethernet Card
Aureal A3D SQ2500
Assigning to a developer.
Is this from stock box-set media?
Yes it is, Redhat 7.0 Standard
The first thing I would try is contacting our support department and get some
new media. Yours may be defective.
Could you tell me a little about your hardware?
What other information do you need?
oh, right - missed that bit. I'm betting bad media at this point. | https://bugzilla.redhat.com/show_bug.cgi?id=24987 | CC-MAIN-2017-17 | refinedweb | 172 | 65.01 |
The problem Largest Substring Between Two Equal Characters Leetcode Solution, asks us to find the length of the largest substring. Here, a condition is imposed on the substring. The substring should be between the same characters. So, the string must contain at least two equal characters so that the output happens to be a natural number else -1 is returned. But before moving ahead with the solution let us take a look at a few examples.
s = "aa"
0
Explanation: The input contains two ‘a’s and the string between them happens to be the longest substring satisfying the imposed conditions. Thus, the output is correct.
s = "abca"
2
Explanation: There exists only a single character having at least two instances in the input string. So, the optimal output will contain “bc”.
Approach for Largest Substring Between Two Equal Characters Leetcode Solution
The solution for the problem Largest Substring Between Two Equal Characters Leetcode Solution is easy to understand. In the problem, we are only asked to find the length of the largest substring but not the string itself. So, we simply create two arrays that store the first and last index of any character. Initially, we fill these arrays with -1 which denotes no occurrence of a character. Once we find a character we store the index in the first array if it is filled with -1. If that does not have -1, we store the index in the second array.
Using these two arrays, we find the maximum length. We run a loop starting from 0 until 25 checking all the indices of both the arrays. We update the answer in each iteration if the indices are valid. In the end, we return the answer.
Code for Largest Substring Between Two Equal Characters Leetcode Solution
C++ code
#include <bits/stdc++.h> using namespace std; int maxLengthBetweenEqualCharacters(string s) { vector<int> f1(26, -1), f2(26, -1); int n = s.size(); for(int i=0;i<n;i++){ if(f1[s[i]-'a'] == -1) f1[s[i]-'a'] = i; else f2[s[i]-'a'] = i; } int ans = -1; for(int i=0;i<26;i++) if(f2[i] != -1) ans = max(ans, f2[i]-f1[i]-1); return ans; } int main(){ cout<<maxLengthBetweenEqualCharacters("aa"); }
0
Java code
import java.util.*; import java.lang.*; import java.io.*; class Main { public static int maxLengthBetweenEqualCharacters(String s) { int[] f1 = new int[26]; int[] f2 = new int[26]; for(int i=0;i<26;i++){ f1[i] = -1; f2[i] = -1; } int n = s.length(); for(int i=0;i<n;i++){ if(f1[s.charAt(i)-'a'] == -1) f1[s.charAt(i)-'a'] = i; else f2[s.charAt(i)-'a'] = i; } int ans = -1; for(int i=0;i<26;i++) if(f2[i] != -1) ans = Math.max(ans, f2[i]-f1[i]-1); return ans; } public static void main (String[] args) throws java.lang.Exception { String s = "aa"; System.out.print(maxLengthBetweenEqualCharacters(s)); } }
0
Complexity Analysis
Time Complexity
O(N), because traverse the entire input string.
Space Complexity
O(1), because we used constant size arrays. | https://www.tutorialcup.com/leetcode-solutions/largest-substring-between-two-equal-characters-leetcode-solution.htm | CC-MAIN-2021-25 | refinedweb | 515 | 66.84 |
Opened 2 years ago
Closed 2 years ago
#9146 closed bug (invalid)
GHC.TypeLits import don't quite work
Description
If you explicitly import any of the things that are Compiler Magic from GHC.TypeLits you get an error:
import GHC.TypeLits ((+), (-)) ...
[1 of 1] Compiling Main ( typelit_export_bug.hs, interpreted ) typelit_export_bug.hs:1:22: Module `GHC.TypeLits' does not export `(+)' typelit_export_bug.hs:1:27: Module `GHC.TypeLits' does not export `(-)' Failed, modules loaded: none.
If you do the opposite, it also doesn't work
import GHC.TypeLits hiding ((+), (-)) ...
[1 of 1] Compiling Main ( typelit_export_bug.hs, interpreted ) typelit_export_bug.hs:3:1: Warning: Module `GHC.TypeLits' does not export `(+)' typelit_export_bug.hs:3:1: Warning: Module `GHC.TypeLits' does not export `(-)'
The use case is that I would like to define my own + and have one instance for Nat and others for other types of my choosing. It isn't more than a minor annoyance, however, there aren't many thing defined in GHC.TypeLits so I can write import qualified GHC.TypeLits; import GHC.TypeLits (Nat, natVal, Symbol, symbolVal ...
Change History (1)
comment:1 Changed 2 years ago by rwbarton
- Resolution set to invalid
- Status changed from new to closed
Note: See TracTickets for help on using tickets.
Your import statement tries to import (ordinary value-level) functions (+), (-) from GHC.TypeLits. Instead, use the ExplicitNamespaces language extension and write | https://ghc.haskell.org/trac/ghc/ticket/9146 | CC-MAIN-2016-18 | refinedweb | 227 | 54.39 |
def median(array) sorted = array.sort len = sorted.length return (sorted[(len - 1) / 2] + sorted[len / 2]) / 2.0 end
I understand everything up to the return statement. Can some describe to me how the return statement plays out with an array = [1, 2, 3, 4, 5]. For example, with an array length of 5 I don't understand how the second half of the numerator of the return statement works. What does it mean to have sorted[5/2] ------ I interpret this as accessing the 2.5th element in the sorted array. I'm confused. Thank you for your assistance!
This post has been edited by xclite: 16 December 2013 - 01:41 PM
Reason for edit:: Adding code tags. | http://www.dreamincode.net/forums/topic/336679-i-cant-figure-out-how-this-code-works/page__pid__1947955__st__0 | CC-MAIN-2016-18 | refinedweb | 120 | 77.43 |
In software development we often unit test our code (hopefully). And code written for Spark is no different. So here I want to run through an example of building a small library using PySpark and unit testing it. I'm using Visual Studio Code as my editor here, mostly because I think it's brilliant, but other editors are available.
Building the demo library
I really wanted to avoid the usual "lets add two numbers together" example and use something a little more like something you might come across day-to-day. So, I'm going to create a library with some methods around creating a date dimension.
A date dimension is something you will tend to come across in any Data Warehouse or Data LakeHouse environment where you're working with dates. And really that's pretty much everywhere! This kind of dimension is typically created to contain information about days of a year which users might want to slice-and-dice data with later on. If you can join your fact tables to a date dimension based on a date key, and then want to see all data in a given month, quarter, last week, over weekends, it gets much easier.
I'm going to stick with a fairly simple date dimension for brevity, so it will just include the key, basic information about the day, month, and year, and the ISO week number.
The ISO week number is the kicker here, and it's better explained over on Wikipedia but it gets interesting because, contrary to popular belief, there aren't always 52 weeks in a year (dates are always so much fun). This isn't something for which a function in Spark exists, but fortunately this is a piece of functionality we can get straight out of python, as the datetime class has an isocalendar function which gives us the ISO values back as a tuple.
But... We can't just call Python code directly from PySpark (well, we can do, but we shouldn't because it's really bad for performance). So we're going to need to create a user defined function.
PySpark has gotten a lot easier to work with in recent years, and that's especially true of UDFs with the arrival of Pandas UDFs. If you want to know why then I suggest you read the docs as it's a bit long winded for here, but it means we can write User Defined Functions in Python which are significantly more performant. Still not quite as good as Scala, but when you think about what it needs to do under the hood, they're very impressive.
The ISO week number function
Write, lets dive into the code for the User Defined Function then.
def get_iso_weeknumber(dt: Union[date, datetime]) -> int: if type(dt) is not datetime and type(dt) is not date: return None return dt.isocalendar()[1] @pandas_udf(IntegerType()) def iso_week_of_year(dt: pd.Series) -> pd.Series: return dt.apply(lambda x: get_iso_weeknumber(x) if not pd.isnull(x) else pd.NA)
I've deliberately broken it into 2 functions here, and I probably could have used some better names but meh. The reason for breaking it down is because of testing. Where possible we want to test custom logic outside of Spark so we don't need to spin up a new session, this means we can write a lot of tests and execute them quickly to check it's working, and that's the purpose of the
get_iso_weeknumber function.
In the
iso_week_of_year function we're getting a Pandas Series as our input, and we're returning another Pandas Series. This is a Series-to-Series function and the output must be the same length as the input. The code in this function is deliberately brief as we want to keep as much logic out of here as possible, it should really just care about applying the
get_iso_weeknumber function to the input. And that's all it's doing, as long as the input value isn't null.
The date dimension
Now that we're able to create our ISO week number we can create a date dimension on demand. There's a few different ways of doing this, but my preferred method is using the
SparkSession.range function using UNIX timestamps.
def create_date_dimension(spark: SparkSession, start: datetime, end: datetime) -> DataFrame: if spark is None or type(spark) is not SparkSession: raise ValueError("A valid SparkSession instance must be provided") if type(start) is not datetime: raise ValueError("Start date must be a datetime.datetime object") if type(end) is not datetime: raise ValueError("End date must be a datetime.datetime object") if start >= end: raise ValueError("Start date must be before the end date") if start.tzinfo is None: start = datetime.combine(start.date(), time(0, 0, 0), tzinfo=timezone.utc) if end.tzinfo is None: end = datetime.combine(end.date(), time(0, 0, 0), tzinfo=timezone.utc) end = end + timedelta(days=1) return ( spark.range(start=start.timestamp(), end=end.timestamp(), step=24 * 60 * 60) .withColumn("date", to_date(from_unixtime("id"))) .withColumn("date_key", date_format("date", "yyyyMMdd").cast("int")) .withColumn("day", dayofmonth("date")) .withColumn("day_name", date_format("date", "EEEE")) .withColumn("day_short_name", date_format("date", "EEE")) .withColumn("month", month("date")) .withColumn("month_name", date_format("date", "MMMM")) .withColumn("month_short_name", date_format("date", "MMM")) .withColumn("year", year("date")) .withColumn("week_number", iso_week_of_year("date")) )
There's a lot of setup in this function, just to make sure we're giving all the right information to create the dimension, but the actual generation is pretty straight forward. You can see on the last line we're using our
iso_week_of_year UDF to get the week number and calling it just like any other Spark function.
Using the
SparkSession.range function with a step of 86,400 means we're incrementing by 1 day at a time, regardless of any time component we're passing in to the function in the first place.
Running this gives us a table looking like the following:
>>> start = datetime(2021, 1, 1) >>> end = datetime(2021, 1, 10) >>> create_date_dimension(spark, start, end).show() +----------+----------+--------+---+---------+--------------+-----+----------+----------------+----+-----------+ | id| date|date_key|day| day_name|day_short_name|month|month_name|month_short_name|year|week_number| +----------+----------+--------+---+---------+--------------+-----+----------+----------------+----+-----------+ |1609459200|2021-01-01|20210101| 1| Friday| Fri| 1| January| Jan|2021| 53| |1609545600|2021-01-02|20210102| 2| Saturday| Sat| 1| January| Jan|2021| 53| |1609632000|2021-01-03|20210103| 3| Sunday| Sun| 1| January| Jan|2021| 53| |1609718400|2021-01-04|20210104| 4| Monday| Mon| 1| January| Jan|2021| 1| |1609804800|2021-01-05|20210105| 5| Tuesday| Tue| 1| January| Jan|2021| 1| |1609891200|2021-01-06|20210106| 6|Wednesday| Wed| 1| January| Jan|2021| 1| |1609977600|2021-01-07|20210107| 7| Thursday| Thu| 1| January| Jan|2021| 1| |1610064000|2021-01-08|20210108| 8| Friday| Fri| 1| January| Jan|2021| 1| |1610150400|2021-01-09|20210109| 9| Saturday| Sat| 1| January| Jan|2021| 1| |1610236800|2021-01-10|20210110| 10| Sunday| Sun| 1| January| Jan|2021| 1| +----------+----------+--------+---+---------+--------------+-----+----------+----------------+----+-----------+
You can see that the first few days of 2021 were part of week 53, and week 1 didn't actually start until the 4th January.
Unit testing the code
But the title of this post is about unit testing the code, so how is that done?
Well we've seen that the ISO week number functions are broken out, so unit testing
get_iso_weeknumber is pretty straight forward and can be tested just like any other Python code.
Whilst we can test the
iso_week_of_year function we lose the ability to capture any coverage information because of the way Spark calls the function. If you're using Coverage.py then you can add patterns to your
.coveragerc file to exclude these functions like this from your coverage results such as the following.
[report] exclude_lines = def .* -> pd.Series
We're going to test our
create_date_dimension function which will call the
iso_week_of_year function.
We'll need a Spark Session to test the code with, and the most obvious way of doing that would be like this (I'm using the Python unittest library here).
class DateDimensionTests(unittest.TestCase): def test_simple_creation(self): spark = SparkSession.builder.appName("unittest").master("local[*]").getOrCreate() df = create_date_dimension(spark, datetime(2021, 1, 1), datetime(2021, 1, 5))
But there's a problem with this. For every single test we're going to be creating a brand new Spark Session, which is going to get expensive. And if we need to change any of the spark configuration, we're going to need to do it in every single test!
So what's a better way? Well, we can create our own test class based on
unittest.TestCase which does all of the set up for us.
class PySparkTestCase(unittest.TestCase): @classmethod def setUpClass(cls) -> None: conf = SparkConf() conf.setAppName("demo-unittests") conf.setMaster("local[*]") conf.set("spark.sql.session.timezone", "UTC") cls.spark = SparkSession.builder.config(conf=conf).getOrCreate() @classmethod def tearDownClass(cls) -> None: cls.spark.stop() def tearDown(self) -> None: self.spark.catalog.clearCache() def assert_dataframes_equal(self, expected: DataFrame, actual: DataFrame, display_differences: bool = False) -> None: diff: DataFrame = actual.subtract(expected).cache() diff_count: int = diff.count() try: if diff_count != 0 and display_differences: diff.show() self.assertEqual(0, diff_count) finally: diff.unpersist
What have we got now? Well, we have our
setUpClass method which is doing the work of setting up our Spark Session for us; and we have our
tearDownClass method which clears up the Spark Session once we're done.
We've also added in a
tearDown method which clears up after each test, in this case it's clearing out the cache, just in case. And there's a new method for comparing data frames which abstracts a lot of repetitive code we might write in our unit tests.
One of the other things that's different in this setup is the line
conf.set("spark.sql.session.timezone", "UTC"). Timestamps are evil. It's that simple. A date is sort of okay, it represents a point in the calendar so they're nice to work with. But the range we're creating is using seconds from the epoch, and so we're in the world of Timestamps, and that world has Daylight Savings Times and Timezones! And how they work varies based on your OS of choice.
Running the following on my Windows 10 laptop using Python 3 gives an error of
OSError: [Errno 22] Invalid argument
from datetime import datetime datetime(1066, 10, 14).timestamp()
But running it in Ubuntu 20.04 on WSL gives a result of
-28502755125.0. Now, running it again in both, but with timezone information provided.
from datetime import datetime, timezone datetime(1066, 10, 14, tzinfo=timezone.utc).timestamp()
Well, now they both give an answer of
-28502755200.0. So, setting the spark session timezone to UTC means that it's going to be handling timestamps consistently, regardless of where in the world I am or on what OS I'm running.
Writing the tests themselves
Now that we have our test case class, we can write some unit tests, and by putting a number of them under the same test class we're going to use the same Spark Session, which means that we're not going to incur a performance penalty for constantly re-creating it.
class DateDimensionTests(PySparkTestCase): def test_simple_creation(self): expected = self.spark.read.csv( self.get_input_file("simple_date_dim.csv"), header=True, schema=DateDimensionTests.get_dimension_schema()) result = create_date_dimension(self.spark, datetime(2021, 1, 1), datetime(2021, 1, 5)) self.assert_dataframes_equal(expected, result, display_differences=True) def test_simple_range_week53(self): week_53_day_count = ( create_date_dimension(self.spark, datetime(2020, 12, 1), datetime(2021, 1, 31)) .filter(col("week_number") == 53) .count() ) self.assertEqual(7, week_53_day_count)
These can now be executed using the Visual Studio Code test runner...
... or from the command line.
python -m unittest discover -v -s ./tests -p test_*.py
They're still not as performant as tests which don't require a Spark Session and so, where possible, make sure business logic is tested outside of a Spark Session. But if you need one, then this is definitely a way to go.
Summary
Phew. So this is my first post to Dev.to. I've been sat reading content from others for a while and thought it was time I contributed something of my own. Hopefully it helps someone out, or gives someone a few ideas for doing something else.
If you can think of anything which could be improved, or you have a different way of doing things then let me know, things only improve with collaboration.
If you want to have a look at the code, or use it in any way (it's MIT licensed), then you can find it over on Github.
Discussion (0) | https://practicaldev-herokuapp-com.global.ssl.fastly.net/dazfuller/unit-testing-your-pyspark-library-e5j | CC-MAIN-2021-21 | refinedweb | 2,111 | 63.9 |
Draft.jsDraft.js
StatusStatus
THIS PROJECT IS CURRENTLY IN MAINTENANCE MODE. It will not receive any feature updates, only critical security bug patches. On 31st December 2022 the repo will be fully archived.
For users looking for an open source alternative, Meta have been working on migrating to a new framework, called Lexical. It's still experimental, and we're working on adding migration guides, but, we believe, it provides a more performant and accessible alternative.
Draft.js is a JavaScript rich text editor framework, built for React and backed by an immutable model.
- Extensible and Customizable: We provide the building blocks to enable the creation of a broad variety of rich text composition experiences, from basic.
Draft.js is used in production on Facebook, including status and comment inputs, Notes, and messenger.com.
API NoticeAPI Notice
Before getting started, please be aware that we recently changed the API of Entity storage in Draft.
Previously, the old API was set to be removed in
v0.11.0. Since, the plans have changed—
v0.11.0 still supports the old API and
v0.12.0 will remove it. Refer to the docs for more information and information on how to migrate.
Getting StartedGetting Started
npm install --save draft-js react react-dom or yarn add draft-js react react-dom
Draft.js depends on React and React DOM which must also be installed.
Using Draft.jsUsing Draft.js
import React from 'react'; import ReactDOM from 'react-dom'; import {Editor, EditorState} from 'draft-js'; function MyEditor() {') );
Since the release of React 16.8, you can use Hooks as a way to work with
EditorState without using a class.
import React from "react"; import { Editor, EditorState } from "draft-js"; import "draft-js/dist/Draft.css"; export default function MyEditor() { const [editorState, setEditorState] = React.useState(() => EditorState.createEmpty() ); const editor = React.useRef(null); function focusEditor() { editor.current.focus(); } return ( <div style={{ border: "1px solid black", minHeight: "6em", cursor: "text" }} onClick={focusEditor} > <Editor ref={editor} editorState={editorState} onChange={setEditorState} </div> ); }
Note that the editor itself is only as tall as its contents. In order to give users a visual cue, we recommend setting a border and a minimum height via the
.DraftEditor-root CSS in the
/examples directory of this repo.
Building Draft.jsBuilding Draft.js
Draft.js is built with Yarn v1. Using other package managers mgiht work, but is not officially supported.
To clone and build, run:
git clone cd draft-js yarn install yarn run build
ExamplesExamples
To run the examples in the
/examples directory, first build Draft.js locally as described above. Then, open the example HTML files in your browser.
Browser SupportBrowser Support
[1] May need a shim or a polyfill for some syntax used in Draft.js (docs).
[2] IME inputs have known issues in these browsers, especially Korean (docs).
[3] There are known issues with mobile browsers, especially on Android (docs).
Resources and EcosystemResources and Ecosystem
Check out this curated list of articles and open-sourced projects/utilities: Awesome Draft-JS.
Discussion and SupportDiscussion and Support
Join our Slack team!
ContributeContribute
We welcome pull requests. Learn how to contribute.
LicenseLicense
Draft.js is MIT licensed.
Examples provided in this repository and in the documentation are separately licensed. | https://githubhelp.com/facebook/draft-js | CC-MAIN-2022-40 | refinedweb | 538 | 50.33 |
Unit Testing with OCUnit
Pages: 1, 2
The easiest way to implement test cases using OCUnit is to implement them as
subclasses of SenTestCase. Here is a complete (though by no means
thorough) test case for the CheckbooX CheckbookEntry class.
SenTestCase
CheckbookEntry
// TestCheckbookEntry.h
#import <SenTestingKit/SenTestingKit.h>
@class CheckbookEntry;
@interface TestCheckbookEntry : SenTestCase
{
CheckbookEntry *entry;
}
// Note that you don't have to declare your test
// methods here.
@end
// TestCheckbookEntry.m
#import "TestCheckbookEntry.h"
#import "CheckbookEntry.h"
@implementation TestCheckbookEntry
- (void) setUp {
entry = [[CheckbookEntry alloc] init];
}
- (void) tearDown {
[entry release];
}
- (void) testEntryAmount {
[entry setAmountInPennies:123];
STAssertEquals(123L, [entry amountInPennies],
@"bad amount; 123 != %ld",
[entry amountInPennies]);
STAssertEquals((float)1.23, [entry amount],
@"bad amount; 1.23 != %f",
[entry amount]);
}
@end
I added a new "Testing" group to the top level of the project. Next, I created
a new Objective-C class named TestCheckbookEntry, remembering to
uncheck the "CheckbooX" target and to check the "Testing" target instead.
TestCheckbookEntry
I entered and saved the code above. Next, I tried running this simple test.
Related Reading
Objective-C Pocket Reference
By Andrew M. Duncan
I made sure that "Testing" was the active target and clicked the "Build"
button. After a few false starts (I started with C strings instead of
NSStrings in the error message arguments), the code compiled. The linker then
complained that it didn't know about CheckbookEntry. So I added
both CheckbookEntry and Checkbook to the "Sources"
section of the "Testing" target, clicked "Build," and voilà! I saw in the
build window:
NSStrings
Checkbook
// ...build stuff...
-[TestCheckbookEntry testEntryAmount] :
Type mismatch -- bad amount; 123 != 123
-[TestCheckbookEntry testEntryAmount] :
Type mismatch -- bad amount; 1.23 != 1.230000
-[TestCheckbookEntry testEntryAmount] :
<3ff3ae14 7ae147ae >' should be equal to
'<3f9d70a4 >' bad amount; 1.23 != 1.230000
The code we saw in the previous section did not cause these errors; that code
is correct. These errors were caused by my original code, which looked like
this:
- (void) testEntryAmount {
[entry setAmountInPennies:123];
STAssertEquals(123, [entry amountInPennies],
@"bad amount; 123 != %ld",
[entry amountInPennies]);
STAssertEquals(1.23, [entry amount],
@"bad amount; 1.23 != %f",
[entry amount]);
}
I simplified the test case by removing all but the first Assert and removing
my custom error message. This is what the code looked like.
Assert
- (void) testEntryAmount {
[entry setAmountInPennies:123];
STAssertEquals(123, [entry amountInPennies],
nil);
// commented-out old versions not shown
}
I clicked "Build" and saw the error message:
-[TestCheckbookEntry testEntryAmount] :
Type mismatch --
The clue I needed was in the phrase "Type mismatch." After a bit of thinking,
I looked at the amountInPennies method. Aha! It returns a
long, not an int. I changed the first argument of
the test to 123L like this:
amountInPennies
long
int
123L
- (void) testEntryAmount {
[entry setAmountInPennies:123];
STAssertEquals(123L, [entry amountInPennies],
nil);
// commented-out old versions not shown
}
I rebuilt the test target, and it worked! I then wrote all the other tests,
which worked perfectly the first time. (If you believe that, I've got some
dot-com stock options for you.)
In order to test much of the code, we need a checkbook object that contains
things to find. We could either create the data manually and feed it to the
checkbook object or read it from an XML file (CheckbooX stores its data as
XML). Let's use the latter method. That way, we can change the test data
without having to recompile the code.
- (void) setUp {
checkbook = [[Checkbook alloc] init];
[checkbook openFile:TEST_CHECKBOOK_FILE];
}
While we're at it, let's store the expected answers in an XML file, too. Then
we can write test methods that don't know the expected answer; they just have
to know the name of the answer in the dictionary and the type of the answer.
Since we want more than one test class to read an answer file, let's abstract
that behavior into a new superclass, TestWithAnswers. The method
TestWithAnswers.readAnswersFrom: and the first few
answerAs* methods look like this:
TestWithAnswers
TestWithAnswers.readAnswersFrom:
answerAs*
-(void)readAnswersFrom:(NSString *)filePath {
NSArray *contents = [NSArray arrayWithContentsOfFile:filePath];
NSEnumerator *e = [contents objectEnumerator];
answers = [[e nextObject] retain];
}
-(NSString *)answerAsString:(NSString *)answerName {
return (NSString *)[answers objectForKey:answerName];
}
-(int)answerAsInt:(NSString *)answerName {
return [[answers objectForKey:answerName] intValue];
}
Now we can write test methods that don't have the answer hard-coded in the
test. For example, here is the test method
TestCheckbook.testBalance:
TestCheckbook.testBalance
- (void) testBalance {
STAssertEquals([self answerAsFloat:
@"balance"],
[checkbook balance],
nil);
STAssertEquals([self answerAsFloat:
@"markedBalance"],
[checkbook markedBalance],
nil);
}
Now when I make a change to CheckbooX, I rebuild the testing target that runs
all of the unit tests. Since writing the unit tests for CheckbooX, I feel more
confident that any changes I make -- whether they're bug fixes or new
features -- will not break the existing code. Though the initial set of
tests is sparse, over time I will be adding more tests to CheckbooX that cover
more of the code. Any new Mac OS X applications I write will be developed with
unit tests from the start.
Testing is good. Just do it.
The Portland Pattern Repository and WikiWikiWeb top-level pages are
deceptively sparse. Browse the main Category page or the Category Testing page.
Search for programming terms and you'll come across an amazingly deep ocean of
discussion. For example, searching for page titles containing "test" returns
529 pages.
JUnit.org is a good jumping-off point
for learning about JUnit and other XUnit frameworks.
Jim Menard
is an independent consultant who has developed many open source
projects, including the Java GUI report writer DataVision, the first pure-Ruby
XML parser NQXML, TwICE (an Information and Content
Exchange (ICE) reference implementation), and, of course, CheckbooX.
Return to the Mac DevCenter
© 2017, O’Reilly Media, Inc.
(707) 827-7019
(800) 889-8969
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners. | http://www.macdevcenter.com/pub/a/mac/2004/04/23/ocunit.html?page=2 | CC-MAIN-2017-26 | refinedweb | 966 | 56.45 |
The Problem
So you want to create a windows form application. It needs to do the following:
- Do some work where its processing multiple items
- Have a progress bar that updates the progress of the application as it runs.
Seems easy.. well here are the complexities:
- You want the main process to run on a background thread, so that the UI thread is available to update and render
- The background thread will need to raise events back to the main application to notify the application of the background thread progress.
- The progress bar will need to be updated to reflect the progress.
- The call to update the UI will crash because it is actually doing a cross-thread call, (the background thread, is trying to update the UI thread and this will crash.
This will walk you through the pattern for implementing this solution.
Background Worker Thread
This as the name suggests is a thread of execution that runs in the background in the application leaving the UI thread to do what it is good at, UI rendering.
If you were to try and have a method that processed 1000 records @ 2 seconds per record, and tried to update the progress bar on processing each record the UI would not render the progress bar as the UI thread is caught up in the process of doing the work.
Doing the work on the background thread leave the UI thread to update the UI whilst the background thread gets on with doing the work.
What is the background thread and how do I create one?
First of all lets create a visual studio solution. I am going to create an empty windows form application called WorkerUtility. I will place the following controls on it.
- A button btnGo – labeled Go
- A progress bar; and
- A label called lblProgress – to show the % complete
The background worker thread can be found in the toolbox under the “Components” section.
Drag the background worker thread onto you form and you will end up with a control called backGroundWorker1.
It should look like this:
Set the following properties on the background worker control
- WorkerReportsProgress true
Double click on the “Go” Button and setup the following Code
private void btnGo_Click(object sender, EventArgs e) { backgroundWorker1.RunWorkerAsync(); }
Performing the Work and Raising Events
I am going to simulate processing a 126 items @ Random number of seconds between 0 and 2 seconds, by looping and pausing the background thread. You could be doing anything in the processing block, for example, read data from the database loop through the rows and perform file system tasks based upon the data?
I will be performing work but each time an item is processed I want to tell the UI thread so that it can update the progress bar. To do this I will need to use events and I am going to create some custom event args.
Create a class called ProgressUpdatedEventArgs like the following:
using System; namespace WorkerUtility { public class ProgressUpdatedEventArgs : EventArgs { public ProgressUpdatedEventArgs(int total, int progress) { this.Total = total; this.Processed = progress; } public int Processed { get; private set; } public int Total { get; private set; } } }
I will encapsulate the logic in a class called Processor.cs. Create a class as follows:
This will house the event handler and raise events back to the UI thread
The main point of Interest in the following code is the creation of the event handler on the page with a delegate method declaration and an event handler. The RaiseEvent method is called on each file that is processed.
using System; namespace WorkerUtility { public static class Processor { public delegate void ProgressUpdatedEvent(ProgressUpdatedEventArgs progressUpdated); public static event ProgressUpdatedEvent ProgressUpdated; /// <summary> /// Main execution method that does the work /// </summary> public static void Execute() { int total = 126 // this creates funny percentages Random randomGenerator = new Random(); for (int i = 0; i < total; i++) { // Do some processing here double delay = (double)randomGenerator.Next(2) + randomGenerator.NextDouble(); int sleep = (int)delay * 1000; System.Threading.Thread.Sleep(sleep); RaiseEvent(total, i + 1); } } private static void RaiseEvent(int total, int current) { if (ProgressUpdated != null) { ProgressUpdatedEventArgs args = new ProgressUpdatedEventArgs(total, current); ProgressUpdated(args); } } } }
Cross-Thread method invoke, handling the callback
Now we need to set up an event handler in the main form so we can update the UI when the event is raised.
On the Background Worker Switch to the “Events” properties and double-click on “DoWork” to create the “DoWork” event handler.
Go to the _DoWork event handler and change as follows:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { Processor.ProgressUpdated += new Processor.ProgressUpdatedEvent(Processor_ProgressUpdated); Processor.Execute(); } void Processor_ProgressUpdated(ProgressUpdatedEventArgs progressUpdated) { }
So this is where the tricky bit comes in. We need to implement the _ProgressUpdated callback.
If we were to go directly to update the UI, we would get a cross thread exception and the program would crash.
Cross-thread operation not valid: Control 'progressBar1' accessed from a thread other than the thread it was created on.
If you check the InvokeRequired method it will return true in this scenario so we need to perform a cross thread call to get from the background worker thread, that the “ProgressUpdated” event is raised on, to the UI thread to make the changes in the UI.
This is done as follows, firstly you need a delegate for the method invoke method callback and an Update Method to handle performing the UI Update.
public delegate void ProgressUpdatedCallaback(ProgressUpdatedEventArgs progress); private void Processor_ProgressUpdated(ProgressUpdatedEventArgs progressUpdated) { if (InvokeRequired) { Invoke(new ProgressUpdatedCallaback(this.UpdateProgress), new object[] { progressUpdated }); } else { UpdateProgress(progressUpdated); } } private void UpdateProgress(ProgressUpdatedEventArgs args) { if (progressBar1.Maximum != args.Total) { // initial setup progressBar1.Minimum = 0; progressBar1.Maximum = args.Total; progressBar1.Style = ProgressBarStyle.Continuous; } progressBar1.Value = args.Processed; if (args.Total > 0) { double progress = args.Processed / (args.Total * 1.0); lblProgress.Text = progress.ToString("P2"); } Application.DoEvents(); }
Here is what it looks like running
Here is the full working code sample in a VS2010 solution.
WorkerUtility
3 thoughts on “Background Worker Thread Code Sample with event handlers and cross thread invoke”
Thank you very much for your post. Your solution was exactly what I was looking for. I actually modified you solution slightly to allow for the updating of multiple progress bars and a rich text box, here is link to the solution:
No problem. I often need to do little utility style applications and I always forget how to setup the event handlers, and the delegate events so this is a basic template for the core of how to implement a background thread example. Glad it helped.
Thank you for the Tutorial, i have implemented this in my project so i am unable to implement the stop button process when my executable code was written in separate class so i have written my code in BGW_DoWork and its works properly. i want to write my executable code in separate class how to could be done. In my project i have two progress bar so implemented by from this link | https://ntsblog.homedev.com.au/index.php/2012/03/30/background-worker-thread-code-sample-event-handlers-cross-thread-invoke/?replytocom=106803 | CC-MAIN-2020-24 | refinedweb | 1,161 | 50.26 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.