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
> -----Original Message----- > From: Martin Sebor [mailto:msebor@gmail.com] On Behalf Of Martin Sebor > Sent: Thursday, June 26, 2008 5:21 PM > To: dev@stdcxx.apache.org > Subject: spacing suggestion for new code > > While reviewing all the new code that's been added I'm finding it > difficult to spot where one namespace-scope definition ends and > another starts because the spacing between them (the number of > newlines) is the same as the spacing between members, namely 1 > blank line. I find code easier to read when namespace scope > definitions of functions and classes that span more than one > line are separated by two blank lines. > > Existing code likely isn't completely consistent in this regard, > and I'm sure examples of both styles could be found, but I'd like > to think the two-line style is prevalent. Either way, in the > interest of readability, I'd like to suggest that we adopt the > two-line spacing style for all new code. Yes? That's my general preference as well. I prefer to use two lines to separate unrelated logical groups. If the groups are related, I'll use 1 line to separate them. Within a logical group, I do not use any blank lines. In the case of namespaces, I'd use 2 blank lines to separate the namespace from its non-namespace members though I would use only 1 blank line to separate the namespace from nested namespaces. namespace A { namespace B { class T; } // namespace B enum { E = 1 }; } // namespace A Brad.
http://mail-archives.apache.org/mod_mbox/incubator-stdcxx-dev/200806.mbox/%3CCFFDD219128FD94FB4F92B99F52D0A4901DB05F9@exchmail01.Blue.Roguewave.Com%3E
CC-MAIN-2016-44
refinedweb
255
60.04
Avoiding Null Anti Patterns Open Source Your Knowledge, Become a Contributor Technology knowledge has to be shared and made accessible for free. Join the movement. The Easiest way to manage null Sometimes, the easiest way to manage null is to not use it. Java coders tend to acquire the habit of initializing data (attributes & variables) to null. This puts them at risk of using a method on the null object, thus causing an overwhelming runtime exception to be thrown! It's generally a better idea to use an empty type to initialize data and yield the same results as a null check. Empty Collections We are frequently tempted to initialize a collection to null to represent the fact that it has not been given any data yet, making it necessary to instantiate it at a later time. Why not instantiate it straight away? This will prevent a potential NullPointerException at runtime and free us of the chore to check if it is null before we try to access it. Moreover, every collection has an isEmpty() method which is as easy to manipulate as anything. Empty String String data types are often initalized to null as well. However, for the exact same reasons, we prefer to use an empty string to replace null. If you want to make it as clear as possible, you can declare a constant in your code such as: public final String EMPTY_STRING = ""; Instead, many coders prefer to use an external library. The Apache Common Lang defines many useful methods for String manipulation, as well as an alias for an empty String. import org.apache.commons.lang3.StringUtils; public String name = StringUtils.EMPTY;
https://tech.io/playgrounds/491/avoiding-null-anti-patterns/alternatives-to-null
CC-MAIN-2018-17
refinedweb
276
61.67
This first tutorial will go over how to make your arduino make simple sounds, and turn your arduino into mini tone generator. Step 1: Supplies 1 small 8 ohm speaker 1 arduino board 1 push button 1 10 k resistor some solid core wire For my purposes, i used the adafruit protoshield to help me lay it out my stuff! Would it be better if we use the piano key frequency formula -> f(n) = 2 ^ (n - 49/12) * 440 Hz, instead of defining all tones? what type of capacitor? how to set up it? thanks.. OK - piece of cake and very very cool ... but one thing TOTALLY escapes me... How do you 'jam out' so 'radically'!?!? The hood, the matching glasses... the rockin mouth poses! Please add instructable on this as well please, otherwise this tutorial is just not complete. :) I had to assign a path in the h include. But's that prob just because I'm a no() { int speakerPin = 8; // iterate over the notes of the melody: for ( int thisNote = 0; thisNote < 8; thisNote++) { // to calculate the note duration, take one second // divided by the note type. //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc. int noteDuration = 700/noteDurations[thisNote]; tone( speakerPin, melody[thisNote], noteDuration ); // to distinguish the notes, set a minimum time between them. // the note's duration + 30% seems to work well: int pauseBetweenNotes = noteDuration * 1.30; delay( pauseBetweenNotes ); // stop the tone playing: noTone( speakerPin ); } } void loop() { // no need to repeat the melody. } And included the .h file with a relative path. #include "./Pitches.h" That was the only way i could get it to work. Thanks. -TheWaddleWaaddle
http://www.instructables.com/id/Arduino-Basics-Making-Sound/
CC-MAIN-2014-52
refinedweb
276
75
After a couple of delays, Java 9 is finally here. Three years after Java 8, it comes with some of the biggest changes to the Java platform, adding more than 150 new features. In this article, we will cover some of the major changes. The module system in Java 9 is one of the most talked about and awaited feature. So, what’s it all about? Java provides an encapsulation mechanism with the help of access modifiers, and any adequately sized Java project will have classes across multiple packages. If the project is large enough, you will have dependencies spanning multiple JAR files. Two problems with this approach are: - Not all the classes declared ‘public’ are part of the APIs that you might want to expose. - What if two JARs have the same class declared under the same package (split packages)? This can lead to class loading issues that you will get to know about only at the runtime. To solve these issues, Java 9 has introduced the concept of modules. A module is a higher-level abstraction over packages. To create a module, you need to add a module-info.java file to your project, and explicitly define the dependencies on other modules using the requires keyword as well as the packages from which you want to expose the public classes using the exports keyword. Do note that other public classes inside any package(s) will not be accessible outside this module, other than the ones inside the exported packages. A sample package definition will look like what follows: module my-module { exports com.example.java9.classes_to_be_exposed_as_apis; requires java.base; } JLink: For creating smaller Java runtimes Java runtime has evolved considerably since its inception, and thousands of classes have been added to it to improve functionality, which has turned it into a huge monolith. Not all the features are used by most of the programs at any given time. For example, until Java 8, you could create a small ‘Hello world’ program that only used classes from the java.lang package, but the runtime would still include all the features (xml parsers, logging APIs, SQL functionality, etc) available in Java. The JDK itself was rewritten using the module system, so there is no single rt.jar file that has all the features of Java; and it has been refactored into small individual modules. This means that you can create custom runtimes that only include the parts of JDK that are used in your module. Once you have a Java module JAR file, you can use the JLink tool in the JDK to generate the runtime: jlink --module-path <modulepath> --add-modules <modules> --limit-modules <modules> --output <path> You can find the dependent modules required by your module using the jdeps tool. Just to give you some perspective, the standard JDK 9 runtime is around 430MB and for a simple ‘Hello World’ application, the runtime generated using the above command is around 24MB, which is great for devices with memory restrictions, for IoT applications and for custom runtimes to run inside containers like Docker. Private methods inside interfaces Java 8 introduced features with which you could have default function implementations inside an interface but all the default implementations behaved like public methods. Well, now you can have private methods inside the interfaces that can be used by the default methods for better code organisation. public interface Car { void setCarColor(String color);// normal interface method default void startCar () { // default method System.out.println(“Car is starting...”); startEngine(); System.out.println(“Car started! “); } private void startEngine() { // Private method not available outside the interface as an API System.out.println(“Engine Started “); } } JShell: The interactive Java REPL Like Python, PHP and several other languages, now Java too features an interactive Read-Eval-Print-Loop. To get started, just type ‘jshell’ in the console and start typing your Java code: C:\Program Files\Java\jdk-9\bin>jshell | Welcome to JShell -- Version 9-ea | For an introduction type: /help intro jshell> int x= 10 x ==> 10 jshell> System.out.println(“value of x is: “+ x); value of x is: 10 Native HTTP/2 and Web sockets Finally, the age old HttpURLConnection has been replaced with the new HttpClient in Java 9, which provides out-of-the-box support for the HTTP/2 protocol, Web sockets and async HTTP requests. HttpClient client = HttpClient.newHttpClient(); HttpRequest req = HttpRequest.newBuilder(URI.create(“”)) .header(“User-Agent”,”Java”) .GET() .build(); HttpResponse<String> response = client.send(req, HttpResponse.BodyHandler.asString()); System.out.println(response.statusCode()); System.out.println(response.body()); Beautiful, isn’t it? No InputStream or Reader is involved — instead, the API offers a BodyHandler which allows us to read the string directly from the response. Enhancements to @Deprecated annotation Deprecated annotation is one of the three original built-in annotations in Java. Over the years, users realised that it is quite ambiguous in nature. It didn’t provide a lot of information previously, like why something was deprecated; could it be used or would it be removed in future versions of the library; if it was to be removed, then at which version would this occur, etc. So, now the deprecated annotation provides additional fields like forRemoval and since for more lucidity. There was another small enhancement whereby, if you were using a deprecated class and suppressed the warning, there would still be a warning left in the place it was used due to the import statement, and there was no way to annotate the import statement. This issue has also been fixed in the current release of Java 9. Multi-release JAR files Multiple, Java-release-specific versions of class/resource files can now coexist in the same JAR file. This is good news for library maintainers, who will not be limited to using the minimum subset of the API provided by the least version of Java they want to support. A multi-release JAR file is one whose MANIFEST.MF file includes the entry Multi-Release: true in its main section. Also, If this JAR is read by JDK 9, it will use classes A and B for Java 9 inside the 9 directory, but if it is read by a pre-Java 9 JDK, it will read classes from the root. Other updates in Java 9 Java 9 packs several other updates. For instance, JavaDocs now supports HTML 5 and the search feature, and new methods have been added to the Stream interface: dropWhile, takeWhile, ofNullable. The iterate method now also allows you to provide a predicate on when to stop iterating. IntStream.iterate(1, i -> i <=10, i -> i + 1).forEach(System.out::println); The collections framework has been updated to now allow a population of collections at the time of creation, as shown below: List<Integer> integers = List.of(1, 2, 3); There are several other new features in Java 9. To get a comprehensive list of all the new additions to Java 9, you can visit the release notes at. Modularity is most anticipated among the new Java 9 features. A modular system includes capabilities similar to an OSGi framework system. Thanks for sharing .
https://www.opensourceforu.com/2017/12/whats-new-in-java-9/
CC-MAIN-2020-45
refinedweb
1,192
52.7
CodePlexProject Hosting for Open Source Software Can someone tell me what to change in this code to remove the sidebar on a page in the Yoko theme. Or is there something else needed to accomplish this. Thank you. This code is in the pages that I want to have no sidebar. using System; using System.Collections; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using BlogEngine.Core; using BlogEngine.Core.Web.Controls; public partial class current_hikes : BlogBasePage { protected void Page_Load(object sender, EventArgs e) { PlaceHolder phSidebar = Master.FindControl("phSidebar") as PlaceHolder; if (phSidebar != null) phSidebar.Visible = false; } } I put this in the master.cs protected void Page_PreRender(object sender, EventArgs e) { if (phSidebar.Visible) Form1.Attributes.Add("class", "body"); else Form1.Attributes.Add("class", "body noSidebar"); } This in master <asp:PlaceHolder <div id="sidebar"> <blog:WidgetZone </div> </asp:PlaceHolder> This in the css form1.noSidebar #content{ width:100%; } I am still struggling with this, I think I am close but have something not right, I would appreciate some assistance, thank you. Can anyone help me with this? I have been successful removing the sidebar but still need help with the css displaying across the entire page. Anybody that can hel me with this? Hi Jerry, For the CSS in the example above targeting the body element with no sidebar, should the CSS not be something like this. .body.noSidebar #content{ width:100%; } Actually your other code displays more of the table and contents the the above code. I just thought it would be easier in the future if I decide to change themes I wouldn't have to make the individual page changes, I have about 6 pages using the code now. The above code doesn't seem to make the tables display wide enougth to show all the data. I have other issues trying to get the ajax calendar contro to work on some forms, do you have any thought on calendar controls, or date pickers they are called. Click on the date field in this form and see what I mean. Thank you for helping me Andy. As you say, the above solution is better if you have a few pages (which you have) and more generic, but the CSS needs tweaking for use in different themes. In the Yoko theme the content div is nested within a div having id main, which also has a width setting, it is that setting which is restricting the max width of content. Taking that into account, the above CSS becomes: .body.noSidebar #main, .body.noSidebar #content { width:100%; float:none; } It's untested, but I think not far off the mark. The date picker issue is also CSS related, it looks like there are highly specific rules being applied to tables which are overriding the date picker table styles. I tested this by going to the page you mentioned using browser tools to adjust the styles of the date picker td's specifically and it displays fine. The culprit here is probably in the stylesheet section headed "Post Tables" where the general table selectors are prefixed with #content, so any table that appears within the content section is liable to inherit these styles, you could possibly start by remove the #content and see what happens. I say see what happens because there may be some other reason why this has been styled so... it's a fair starting point. The above latest code works great Andy, I have given up on the date picker for now, I just switched it out for the free basic date picker, it has a license notice displayed that doesn't look very nice but to keep the forms working I'll use it for now. I'll update all my pages with no sidebar to use it, that way when I switch themes all I'll need to do is edit the css, master, and .cs to keep it working, a few less changes then all the pages without the sidebar. Thank you for all your time and help with this, I do appreciate it very much. Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
https://blogengine.codeplex.com/discussions/397630
CC-MAIN-2017-09
refinedweb
723
72.36
Question: Python is the nicest language I currently know of, but static typing is a big advantage due to auto-completion (although there is limited support for dynamic languages, it is nothing compared to that supported in static). I'm curious if there are any languages which try to add the benefits of Python to a statically typed language. In particular I'm interesting in languages with features like: - Syntax support: such as that for dictionaries, array comprehensions - Functions: Keyword arguments, closures, tuple/multiple return values - Runtime modification/creation of classes - Avoidance of specifying classes everywhere (in Python this is due to duck typing, although type inference would work better in a statically typed language) - Metaprogramming support: This is achieved in Python through reflection, annotations and metaclasses Are there any statically typed languages with a significant number of these features? Solution:1 Boo is a statically typed language for the Common Language Infrastructure (aka. the Microsoft .NET platform). The syntax is highly inspired by Python, and hashes/lists/array are part of the syntax: i = 5 if i > 5: print "i is greater than 5." else: print "i is less than or equal to 5." hash = {'a': 1, 'b': 2, 'monkey': 3, 42: 'the answer'} print hash['a'] print hash[42] for item in hash: print item.Key, '=>', item.Value Solution:2 Cobra is a statically typed language for the CLR (as Boo). From its web page: Cobra is a general purpose programming language with: - a clean, high-level syntax - static and dynamic binding - first class support for unit tests and contracts - compiled performance with scripting conveniences - lambdas and closures - extensions and mixins - ...and more Sample code: """ This Solution:3 Although it is not object-oriented, Haskell offers a significant number of the features that interest you: Syntax support for list comprehensions, plus donotation for a wide variety of sequencing/binding constructs. (Syntax support for dictionaries is limited to lists of pairs, e.g, dict = ofElements [("Sputnik", 1957), ("Apollo", 1969), ("Challenger", 1988)] Functions support full closures and multiple return values using tuple types. Keyword arguments are not supported but a powerful feature of "implicit arguments" can sometimes substitute. No runtime modification of classes, types or objects. Avoidance of specificying classes/types everywhere through type inference. Metaprogramming using Template Haskell. Also, just so you will feel at home, Haskell has significant indentation! I actually think Haskell has quite a different feel from Python overall, but that is primarily because of the extremely powerful static type system. If you are interested in trying a statically typed language, Haskell is one of the most ambitious ones out there right now. Solution:4 It may not match all your needs, but have a look at Boo - The wristfriendly language for the CLI If you do, I highly recommend DSLs in Boo: Domain-Specific Languages in .NET which apart from the DSL aspects, covers Boo syntax in a very nice appendix and a lot of meta-programming. Furthermore the tutorials are a great resource. Solution:5 The Go programming language. I've seen some similar paradigm. Solution:6 Rpython is a subset of Python that is statically typed. Solution:7 The D programming language is a statically typed, natively compiled language that has some significant features inspired by Python. Arrays and associative arrays are built into the language. There are no list comprehensions, but the std.range and std.algorithm libraries fill much of that void. For example, here's a way to sum up all the even numbers from 0 to 100 in D: auto result = reduce!"a + b"( filter!"a % 2 == 0"( iota(0, 100) ) ); There are no keyword arguments so far, but closures are there. Tuples are supported, but not unpacked automatically. In D, you avoid specifying classes (and types in general) everywhere with the auto keyword and with templates. For example, here is generic code to find the product of array of any numeric type: // The return type of product() is inferred. auto product(T)(T[] array) { T ret = 1; foreach(num; array) { // typeof(num) is inferred. ret *= num; } return ret; } D's metaprogramming support consists of compile time introspection (for example, you can iterate over the fields of a class or struct at compile time), runtime type information, and templates that are actually designed for metaprogramming beyond simple generics. For example, here's how to write a generic function that generates a default comparison operation for two structs, which is useful if you need an arbitrary total ordering for something like a binary tree: /**Returns -1 if lhs < rhs, 0 if lhs == rhs, 1 if lhs > rhs.*/ int compareStructs(T)(T lhs, T rhs) { foreach(tupleIndex, value; lhs.tupleof) { if(value < rhs.tupeof[tupleIndex]) { return -1; } else if(value > rhs.tupleof[tupleIndex]) { return 1; } } return 0; } Solution:8 Autocompletion is still possible in a dynamically typed language; nothing prevents the IDE from doing type inference or inspection, even if the language implementation doesn't. Solution:9 If auto-completion is the thing you are looking for, then you might wanna stick with Python and use a great IDE instead. Try PyCharm: Unless you are coding some extremely dynamic stuff (which you can't probably do in a static language anyway), it will keep up with the code and give you completion, refactoring and all the other goodies we are used to in statically typed languages. You can give typehints to the IDE where you really need it by doing: def foo(bar): if 0: bar = Bar() # "if 0" will be removed from the bytecode automatically by python bar. # will now autocomplete Solution:10 Lobster () is a statically typed programming language with Python-esque syntax. It has a few things you're asking for: - Type inference, so your code can look similar to Python without having to specify types everywhere. In fact, it goes further with type inference than languages like Haskell. - Closures: they are syntactically lighter than Python (create your own control structures) and yet more powerful (may be multi-line, you can return from them to enclosing functions). - Multiple return values. It doesn't do so well on these items: - Syntax for dictionaries or array comprehensions. Though its syntax for map/filter is so minimal that it can probably compete with array comprehensions. - Keyworded arguments currently only for constructors. - Runtime modification of classes: nope.. its a pretty static language. - Reflection: also nope, though this would certainly be possible. Solution:11 I think Eric and PyScripter have nice autocompletion on Windows, but maybe not as good as PyTools for Visual Studio (Express). For static typing in Python, i'd use Cython: Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com EmoticonEmoticon
http://www.toontricks.com/2019/02/tutorial-what-statically-typed.html
CC-MAIN-2019-09
refinedweb
1,121
53.31
By Jinesh Varia, AWS & the 8KMiles team Host Your Facebook Applications on AWS In this article, you will learn how to launch your Facebook application on Amazon Web Services cloud infrastructure within minutes. A Facebook application—whether it is online casual game or social application—is a hosted web application that utilizes the Facebook API. You can host your Facebook applications on AWS to access a reliable, scalable, and cost-effective compute infrastructure. The flexibility of AWS allows you to choose the programming models, languages, and operating systems that you are already using or that are best suited for your project. With AWS, you can bring your existing skills and knowledge to the platform; you don't have to learn lots of new skills. When you host your application or game in the cloud, you can start small and then quickly scale up your infrastructure when your application is popular. For the purpose of this tutorial, we will deploy a sample application built in PHP and host it in the AWS cloud. To launch a sample Facebook application in the AWS cloud, all you have to do is following: - 1. Sign up for AWS account (there is no charge for opening an AWS account) - 2. Create a new Facebook app on Facebook - 3. Launch the Facebook sample stack with one click - 4. Configure the Site URL (or Canvas URL) of your app - 5. You are done! Launch Facebook Sample App in the AWS Cloud in Three Simple Steps First, you will have to sign up for an AWS account, if you don't already have one. - 1. Create an app on Facebook You can create an app on Facebook by going to and clicking on the "Create App" button. This will create Facebook app credentials (Facebook App ID and Secret Key) that you will need in the next step. Add Basic Info like App Display Name, App Namespace (can only contain lowercase letters, dashes and underscores), and email address and app domain as "amazonaws.com" (More about this later). - 2. Launch the Facebook sample Stack with one click Once, you have created an app on Facebook, you need to host your application. We are going to host the application in AWS cloud. To do that, click on "Launch Stack" button. This will take you to the AWS Management Console's AWS CloudFormation stack wizard and load the sample template. AWS CloudFormation is a service that will gives you an easy way to create a collection of related AWS resources and provision them in an orderly and predictable fashion using a simple template (JSON). This sample AWS CloudFormation template will launch all the necessary cloud resources you need to launch the sample app on AWS. Since this template will automatically configure the sample PHP (File Sharing) application, you will need to input a few parameters before you can launch the stack: - 1. Facebook App ID, which was generated by Facebook when you created an app in Step 1 - 2. Facebook Secret Key, which was generated by Facebook when you created an app in Step 1 - 3. Facebook App Namespace, which is the same namespace that you used in Step 1 - 4. AWS Access ID, which can be found in AWS Security Credentials page under "Your Account" - 5. AWS Secret Access Key, which can be found in AWS Security Credentials page under "Your Account" The sample template will not only launch and provision all the cloud resources (like an elastic load balancer, an EC2 Micro instance, Auto Scaling Group, Amazon CloudWatch Alarms, uses Amazon Machine Image, configures Security Groups etc.) but also install the latest Facebook PHP SDK (from GitHub) and the AWS SDK for PHP (from PEAR) at boot time as well as download and configure the sample application. This will take a few minutes to launch the stack. The beauty about this cloud architecture is that it will automatically scale and add more Amazon EC2 Instances when your traffic is high and also maintain a minimum number of EC2 fleet size (Min size set to 1) and launch new instances in case of the instance failed. Once the stack is launched (Status shows "Create_Complete") , you now have your application hosted in the AWS cloud. The architecture diagram above shows what will be launched behind the scenes by AWS CloudFormation Sample template that we used. Note: You can use the Facebook Sample template as-is or modify it or use it as a starting point for creating your own templates. You can find more AWS CloudFormation templates here. After the stack is launched, it will output the Site URL of your application which you will need for Step 3. - 3. Configure your Facebook application After you have launched your stack, you need to let Facebook know where the actual app is hosted. Go back to your application settings at and under select how your app integrates with Facebook section, paste the Site URL under Website (if you want to have your own website or game) or Canvas URL under App on Facebook (if you want to integrate your app with Facebook's user experience). That's it. You are done! Within just a few minutes, you have now launched your Facebook web application in AWS cloud. To go to your app, simply point your browser to the Site URL or. When you go access the app for the first time, the app will ask for authorization and permission to access your profile:. Cost of Running the Sample Application on AWS The Sample app (and the sample template) takes advantage of the AWS Free Usage Tier. New AWS customers will be able to run a free Amazon EC2 Micro Instance for a year, while also leveraging a free usage tier for Amazon S3, Amazon Elastic Block Store, Amazon Elastic Load Balancing, and AWS data transfer. Beyond the AWS free usage tier, you only pay for the resources you use; there are no long-term contracts or up-front commitments. You can use the AWS Simple Monthly Calculator to estimate the cost of your application. How to Modify the Sample Application With Amazon EC2, you get complete control of your environment. You can login access as "ec2-user" using Putty/Terminal and the SSH keypair that you used when you launched the stack. Please refer to Amazon EC2 Getting Started Guide for more information. You can modify the sample application (which can be found at /var/www/html/) or replace the sample application with your own existing Facebook app. Credits We would like to thank Navin Kumaran from 8KMiles. 8KMiles is a leading cloud consulting firm and an Amazon Web Services Solution Provider that offers cloud strategy, cloud engineering and cloud migration services to help businesses leverage the power of cloud computing.
http://aws.amazon.com/articles/1044?jiveRedirect=1
CC-MAIN-2015-35
refinedweb
1,129
59.03
Agenda See also: IRC log <trackbot> Date: 05 April 2012 <George> trackbot, start telecon <trackbot> Meeting: Government Linked Data Working Group Teleconference <trackbot> Date: 05 April 2012 <DanG> 691-aaaa is DanG <luisBermudez> aagg is me <scribe> Scribe: olyerickson Materials published; congrats and thanks to everyone esp Sandro <gatemezi> s/Sandrp/Sandro <PhilA2> works Now that FPWD is out, move toward ISA (?) "alignment" scribe: PhilA: core vocabs integrated next couple weeks ... ISA specs NOT currently in published versions of FPWDs mhausenblas: Planning call req'd PhilA2: makes sense ... needs to send mhausenblas something before WWW <PhilA2> works <PhilA2> Guess what <PhilA2> And bhyland: Skip to "Org" agenda item <PhilA2> :-( +1 bhyland to explain... scribe: Weds during sweb coord meeting, paul groth mentioned multiple W3C groups with PROV concerns mhausenblas: What is the status of PROV? bhyland: need to keep up with our liaison with PROV ... current status of PROV, not that far ahead PhilA2: would like to be involved in that discussion <bhyland> Paul Groth mentioned these references for our consideration: <bhyland> [1] people: <bhyland> [2] org: <bhyland> [3] prov-dm: PhilA2: SPARQL 1.1 is about to bring up "prov" considerations George: Org "speaks to" OPMV... <mhausenblas> +1 <gatemezi> +1 <Mike_Pendleton> +1 <BenediktKaempgen> +1 <luisBermudez> +1 George: Sorry to miss "geo work" discussion last week ... any further discussion/comments <bhyland> closing loop on coordinating mhausenblas, phila2, luc and paul groth, see <PhilA2> olyerickson: Regarding the provenance discussion... I'm trying to understand what the issue is? Was Paul concerned that there are lots of parallel efforts on provenance, or people, or what? bhyland: explanation of PROV question <PhilA2> bhyland: AIUI, Paul in particular, they invented "agent" and it has a lot of people attributes. We're up to 4 different ways to capture people-related info just from W3C bhyland: up to 4 ways to describe people ... need to coordinate ... bhyland tasked with bringing together the various parties ... is there common ground, or should there be separate paths <sandro> (Sorry I'm late) bhyland: can/should "people" be simpler <PhilA2> Someone said schema.org ? bhyland: example schema.org w.r.t simplicity 9and role in packaging/marketing) George: many esp govt would like to put a "stake in the ground" <bhyland> To remind people who were present last week (and weren't), Boris gave a great talk on work on map4rdf, see George: poll the group? PhilA2: Trying to notice what is going on, while being concerned about strengthing this group ... BUT we do have optional item <gatemezi> @bhyland --Thanks for the link PhilA2: there is much well-done current work in this area ... thinks, OGC's (??) job ... yet people bring it to use <bhyland> Per PhilA2's reference, see <gatemezi> +1 to PhilA PhilA2: GLD is in a position to consider, yet we have it as an opt. on our charter BartvanLeeuwen: concern over amt of work reqd to get it done ... should at least reference the relevant vocabs ... shouldn't write our own recommendation ... there are "smarter" people to do that ... best practices should be able to point to other references <PhilA2> ref: Open Geospatial Consortium BartvanLeeuwen: but maybe not... George: If there *is* energy, there is interest in the community ... there's lots of innovation going on in this area bhyland: ... BP doc focusing on what SHOULD be done ... BP not about "how" ... rec'd of vocabs is new ground for W3C <PhilA2> I'm the last person to object to FOAF! bhyland: GLD approach to rec'd vocabs is new ... need to be careful to not go beyond out core expertise luisBermudez: Geo vocab standard will be published soon ... important to find way to integrate e.g. geoSPARQL, etc <PhilA2> luisBermudez: geoSPARQL will be publicly available in June (from OGC) luisBermudez: luisBermudez the problem: geoSPARQL not a publicly available standard (will be) <BenediktKaempgen> +q PhilA2: GLD should look at it "a little later" in the year ... FOAF is now under the wing of DC <bhyland> @PhilA2 thanks for clarifying/reminding me re: ISA People & FOAF embrace PhilA2: thought question: Will FOAF be around next year? <sandro> DanG, the reference was to Dan Brickley, co-parent of FOAF. <danbri> while we're on topic, can I draw attention to some other People vocab things from this week? <bhyland> @george, what URL would you like me to add to agenda from HR14 proposal discussion? <danbri> see BenediktKaempgen: Talked to supervisor, tells us that that community has tried to consolidate, question of what GLD process will be for integrating in neogeo (neogeo?) Thanks to sandro for the big push last night <bhyland> +1 thanks to Sandro <danbri> opensocial is a tech for making social networks, and is linked to PortableContacts, a vcard-based addressbook format. opensocial people are wondering how to address new requirements for modelling organizations, scientific info etc. um <danbri> e.g . is there an announcement that some of us are missing? sandro: What does it mean for one vocab to "use" another <danbri> neogeo ~ ? PhilA2: Issue of alignment of e.g. foaf:Person with schema.org equivalent, etc ... See PhilA2 blog post (today) ... motivated PhilA2 to think foaf should be retired... <gatemezi> @LuisBermudez: could you know any triple store that have implemented part of geoSPARQL requirements? sandro: can't recommend The Government to use vocab that can't be used in perpetuity <PhilA2> smotivated PhilA2 to think a day may come when foaf could be retired.../motivated PhilA2 to think a day may come when foaf could be retired.../ <PhilA2> My blog post <bhyland> PhilA2: There may a day in our community that some sacred cows should be retired … bhyland: It's a concept called "social responsibility" ... when you publish "content" you are making a commitment or 'social contract' ... for the foreseeable future ... BP must educate/"warn" adopters ... vocabs should be from authoritative sources that make commitment sandro: doesn't agree ... W3C makes a commitment to e.g. DCAT ... details will change, there is a process and W3C stands behind it <Zakim> sandro, you wanted to disagree with olyerickson <PhilA2> olyerickson: You, Sandro, were right to disagree with my words <PhilA2> olyerickson: An organisation needs to know what it is adopting <bhyland> Sandro: Gov'ts should be able to count on key vocabs, such as DCAT, in perpetuity. <PhilA2> ... e.g. the current version of DCAT, recognising that it may evolve <PhilA2> olyerickson: They need to recognise that by using a vocan they become part of that community <sandro> +1 olyerickson Yes, people adopting a tech become part of the stewardship community, when things work well. That's sustainable. <bhyland> johnerickson: Gov't need to recognize their role as stewards of vocabs [and data sets] that they publish. <PhilA2> ... they can't wine about the fact that current browsers don't working with HTML1 any more we are in fervent agreement (if not using the most articulate language) sandro: brings us back to foaf <mhausenblas> Michael: I have to apologise, need to run now (need to do some fire-fighting, unforeseen incident that came up …) sandro: might have a situation where W3C doesn't control the namespace, dereferencing, etc ... need to ensure namespace is part of the community stewardship ... community needs to have control PhilA2: agrees with sandro <sandro> sandro: We should only use namespaces for which we have en enforcable commitment to respect some legitimate stewardship/community process PhilA2: "DanBri under a bus" problem has created adoption problems for foaf in the past, seems to be resolved now ... key issue is foaf:Person and schema.org allow imaginary people UNKNOWN_SPEAKER: httpRange-14 <danbri> (the dictionaries definition of 'person' allows imaginary people too) (imagine a dictionary where each term had 'except for pretend X's...'?) George: any views/thoughts? <danbri> btw ... if GLD have expectations re what long-term preservation commitments you'd like from schema.org, do please write them down and pass them along sandro: (laughs) ... gave up in 2003 ... proposed 303 but has given up <gatemezi> I was reading also this post of Jenni <PhilA2> olyerickson: I've been watching in the way you watch a NASCAR race expecting a crash. A real concern is implementation efficiency <PhilA2> ... there are existential issues but the practical ones are perhaps more key - redirection, caching and so on <PhilA2> ... there are some proposals around 3xx and 200/207 <PhilA2> ... I really haven't seen a convergence Current state: Open for proposals <PhilA2> George: It's open for proposals on possible conversion <bhyland> olyerickson: "I'm not interested from a fascinated academic perspective, rather a grouchy implementer." ;) bhyland: jenit is soliciting proposals ... trying to do it sensibly ... reaching out to stakeholders ... jenit trying to get something done ... put something in writing, not "pissy emails" not(sandro) : interested in concern over performance scribe: are there designs that deliver performance which doesn't violate semantics of 303 how to engage: write it up, submit George: Interesting how when GLD people get interested and start to engage, their Inboxes get flooded (none offered) Adjorned <gatemezi> Thanks George and olyerickson.. 'Have a great day' <BartvanLeeuwen> thx and bye ! <BenediktKaempgen> Thanks <DanG> Bye This is scribe.perl Revision: 1.136 of Date: 2011/05/12 12:01:43 Check for newer version at Guessing input format: RRSAgent_Text_Format (score 1.00) Succeeded: s/Sandrp/Sandro/ FAILED: s/Sandrp/Sandro/ Succeeded: s/RPOV/PROV/ Succeeded: s/???geo/neogeo/ Succeeded: s/motivated PhilA2 to think foaf should be retired.../motivated PhilA2 to think a day may come when foaf could be retired.../ Found Scribe: olyerickson Inferring ScribeNick: olyerickson WARNING: No "Present: ... " found! Possibly Present: BartvanLeeuwen BenediktKaempgen Biplav DanG George George_Thomas LC MacTed Michael Mike_Pendleton P34 P44 P52 PhilA2 aaaa aabb aacc aadd aaee aagg aahh annew bhyland danbri gatemezi gld johnerickson joined luisBermudez mhausenblas olyerickson ref sandro tinagheen: 05 Apr 2012 Guessing minutes URL: People with action items:[End of scribe.perl diagnostic output]
http://www.w3.org/2012/04/05-gld-minutes.html
CC-MAIN-2015-48
refinedweb
1,640
54.32
spawnle() Spawn a child process, given a list of arguments and an environment Synopsis: #include <process.h> int spawnle( int mode, const char * path, const char * arg0, const char * arg1..., const char * argn, NULL, const char envp is NULL, the child process inherits the environment of the parent process. The new process can access its environment by using the environ global variable (found in <unistd.h>). A parent/child relationship doesn't imply that the child process dies when the parent process dies. Returns: The spawnle(). Last modified: 2014-11-17 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/s/spawnle.html
CC-MAIN-2017-04
refinedweb
107
60.21
Behavior Driven Testing¶ As editlive is a Interface component, a BTD approach is used for testing it. This gives this project the following benefits: - Writing test is really easy. Non-programmers could almost write them. - It tests the client and the backend at the same time, like a real user would - It allow real world testing in multiple browsers (but currently only in Firefox and Chrome are tested) Travis CI is used as build server. Not only you can see the current build status and the complete history, but you can see the build status of branches and pull requests. The test suite is a mix of Lettuce, Selenium and Splinter. Lettuce¶ Lettuce makes writing the test cases and scenarios very easy Features¶ Feature: Manipulate strings In order to have some fun As a programming beginner I want to manipulate strings Scenario: Uppercased strings Given I have the string "lettuce leaves" When I put it in upper case Then I see the string is "LETTUCE LEAVES" Steps¶ from lettuce import * @step('I have the string "(.*)"') def have_the_string(step, string): world.string = string @step('I put it in upper case') def put_it_in_upper(step): world.string = world.string.upper() @step('I see the string is "(.*)"') def see_the_string_is(step, expected): assert world.string == expected, \ "Got %s" % world.string For more information about using Lettuce with Django consult the Lettuce documentation. Splinter¶ From its website: “Splinter is an open source tool for testing web applications using Python. It lets you automate browser actions, such as visiting URLs and interacting with their items.“ from splinter import Browser browser =" browser.quit() For more infos about Splinter. Selenium¶ From its.“ For more infos about Selenium. Running the tests¶ See the Testing and development environment documentation for an example of how to quickly setup a testing and development environment. Test command arguments¶ If you have special arguments to pass to the test runner you will have to use the full command: python manage.py harvest To test a single feature: python manage.py harvest test_app/features/date.feature Excluding applications: python manage.py harvest -A myApp1,myApp2 For a complete argument documentation, please refer to this section of the Lettuce documentation. Manual tests¶ The example_project can also be used to perform manual tests. While in the virtualenv, use the command ./run-server. It accepts arguments as usual. Open the dev server url, an index of the tests should show up. If you click on a test it will bring you to a page with an URL like this:. You can pass arguments to the editlive instance using GET parameters:.
http://django-editlive.readthedocs.io/en/latest/topics/develop/tests.html
CC-MAIN-2017-39
refinedweb
431
58.08
From: williamkempf_at_[hidden] Date: 2001-07-06 17:38:49 --- In boost_at_y..., "David Abrahams" <david.abrahams_at_r...> wrote: > [Nathan, one of these could use some interpretation from you] > > 1.6 Does this bar comments from being placed above the #includes and > > #include guards? > > I guess so, though I think its unintended. If you'd like to supply new > wording allowing initial comments I'm not opposed. I'm not the best documentor, but if no one else has a fix I'll give her a go ;). > > 4.1 Should the guidelines specify the number of spaces used for an > > indentation level? If so, should it be consistent for all > > indentations? > > indentation to indicate namespace scoping can use up a lot of real- estate. > Since there's almost no information at the level of indentation where the > namespace is declared, it isn't worth wasting space on. Also, indentation is > only useful if you stand a reasonable chance of seeing the indented and > unindented stuff at the same time. Namespaces tend not to have that > property. That's why it's 2 for a namespace and 4 everywhere else. Understandable. My only complaint is that editors that do auto- indenting and/or treat the tab key as a sequence of spaces may not work nicely with varying indent sizes. > > 4.4 Why? As long as all lines but the first in a multi-line > > definition is indented another level the blank lines add little > > benefit, and in fact can detract from the rest of the code. > > IMO vertical density makes reading code difficult. If you stick several > multi-line definitions next to one another, things tend to get too dense. Granted. However, you can arrive with a different problem if you expand the vertical density too much, which this rule can lead to. I've never used this rule, but been careful to insure the vertical density remains at a level consistent with easy reading. It just seems like this rule is a little too restrictive just to inforce another rule that should be more explicitly spelled out. In other words, I'd prefer to see a rule about insuring the vertical layout is properly split into "paragraphs" for easy consumption. (Granted, wording of such a "rule" will be difficult.) > > 4.5 See 4.1. > > Consistency of indentation of continuation lines is less important than the > other one. I didn't think it was worth mandating. Well, I'm not sure the number of spaces *should* be mandated. As evidenced here, different people have different preferences for indent size. As long as the size is consistent within a file should we dictate the actual size? Also, this bullet has the same complaint I detailed above concerning editors. > > 4.6 Wording should indicate this applies to multi-line definitions. > > As written it means that ALL function definitions should be multi- > > line. Also, see 4.1. > > I got this guideline from Nathan. I always read it to mean that all function > definitions with arguments should be multi-line. Of course I don't > that practice myself. I like your reading better. Nathan, what do you have > to say about this? So all definitions would follow the form: void foo( bar b) { } I hope this wasn't the intended interpretation. > > 4.7 Again, why? > > Same reasons. > > > 4.8 Why? Also, see 4.1. > > It looks nice ;-) > I used to indent them zero spaces, but worked somewhere that they were > always indented 1 space. I grew to like it. It shows that the class body > isn't over yet. I'm not wedded to this one. I'm opposed to this for the same reason I'm opposed to the other variable sized indentation rules. I'd much prefer to stick to a single indentation size (whether mandated or not) and leave these unindented. > > 5.7 I find this a little restrictive with the reasoning being > > questionable. That said, I can live with it. > > Here's an example of the alternative: > > > if (x < 0) > x = 0; > else > { > for (y = 0; y < x; ++y) > do_something(); > > do_some_other_thing(); > } > > My eye says that the x=0 goes with the 'if' clause and the rest is a > separate entity like a struct declaration or a while loop. This is an > aesthetic consideration; others' taste may not coincide here. Mine don't, but I realize this one is purely aesthetic, that's why I can live with the rule. However, since you agree that it's purely aesthetic, and aesthetics are in the eye of the beholder, should we really dictate (even in "optional" guidelines) this? > > 5.8 See 4.1. > > > > 6.7 This makes the code read less like english. > > Depends whether you think const is an adjective or a noun. I think it's a > noun ;-) *laughs* I guess. I definately don't agree with you, but... > > Also, the comment > > about being consistent with compiler error messages is, frankly, > > misguided. We can't predict how compilers will display this sort of > > Except that compilers have to go out-of-their way to generate "const char" > instead of "char const" when they also have to generate "char* const". If > you pick a simple algorithm to translate an internal type representation > into valid C++, it will always put the const afterwards. Granted. However, since the standard doesn't dictate this Murphy's law says there will be an implementation that behaves differently from what you'd expect. I'd rather not document this at all, but if you're going to make it obvious in the wording that you're just expecting *most* compilers to generate such errors. > That said, I still have a hard time adjusting to writing "char const". OTOH, > if you have to pick a rule, it should be a consistent one. The alternative > is no rule: some people write "char const" and others write "const char". Do > we care? Personally I don't. If we have to pick and it's up to a vote I'll vote for "const char", but I'm used to adapting styles according to guidelines I don't always agree with. :) One should note, however, that the C++ standards document uses the "const char" form in most (all?) examples. One can make an argument for maintaining consisty here. > > 7.3 & 7.5 Don't quite work well together. Combining them will > > better explain that public and protected interfaces should be fully > > commented at the point of declaration. > > Please suggest new wording. Well, again, I'm not great at writing documents. Having the rules seperated and worded as they are leads to some confusion, but I'm not sure how to rework this. Maybe I'll tackle this and the previous one later and send my attempts to you. > > 7.3 & 7.9 Though they technically don't conflict, they lead to > > confusion because of their differing emphasis on accuracy or brevity. > > Yes, they are explicitly recognized as conflicting goals. Do you have a > suggestion? Other than putting text in that states what you just did, no. I understand there's a trade off here and the programmer has to try and achieve as much of both goals as he can. The problem is, both rules currently read as mandates rather than goals, and given the conflict you can only fully meet one mandate. I'd suggest lessening the emphasis or combining the two into a single rule stating that you must strive for terseness while being complete. > > 7.12 It would be helpful to have a document listing the proper C++ > > terminology and improper variants. > > Would you like to write one? *laughs* No, because I'm often caught using the improper variants. That's precisely why I'd like a document listing the proper ones. I expect such a document would be a living document, added to frequently (at least at first). I'm just not qualified to start it, sorry. Guess I was fishing for someone else to volunteer. > > 7.15 Commenting out code should be avoided. Yes, there are times > > when this rule can be broken, but generally it's better to rely on > > the configuration management tool (CVS for us) for recalling code > > that's been removed. Commented out code simply makes reading more > > difficult. > > Changed to: > > Comment out code using `` #if 0...#endif'', or ``//'', not ``/*...*/'' > comment notation. Avoid checking in code that's been commented out. Since it > doesn't get tested, it will likely not make any sense tomorrow even if it > makes some sense today, . If the code never gets checked in we don't need guidelines for how to comment out the code. :) Other than that, I like this wording better. > > 8.1 & 8.2 Though use of public and protected data members may be > > questionable from a design stand point, this is a coding guidelines > > document not a design guidelines document. (Boost should have both, > > but the coding guidelines should be careful to not discuss any design > > guidelines.) > > Even if I agreed that it would be a good idea to separate the documents (I'm > not sure I do), I am definitely unwilling to invest the effort required. If > you would like to generate a consensus for two documents and do the editing, > though... Reasonable response. I'll wait to see if others agree and if someone else is willing to do the effort. > > 8.4 Why make an exception for operator()? > > It's not an exception for operator(), it's for simple function objects. > These are just simple functions in disguise; separating interface from > implementation is more trouble than it's worth in my experience. > > > The reasoning given just > > begs the question since the word "often" is used. > > Where is the word "often" used??? "Function objects are _often_ just wrappers over a simple function or function template." (emphasis added by me). > > What about the other cases? > > I think the wording is clear: there are no "other cases". > > > What about in template classes? > > "Function definitions in the class body are forbidden" I can't always apply this rule with VC++ :(. It often gets confused when the definition of template members are defined outside of the class. Also, though I agree with the reasoning, templates are rarely coded this way, and there's something to be said for consistency as well. I won't argue this rule too much, but had to voice some concern. > > 8.7 Why? The grouping and commenting I can agree with, but leaving > > off the virtual can lead to confusion for readers not fully versed in > > C++. > > The rationale is in the discussion section below: > > "Writing `virtual' on the declaration of a virtual function override is > neither neccessary nor sufficient to document where it comes from and which > code it interacts with. Leaving the keyword off in derived classes reduces > clutter and thwarts the temptation to treat it as sufficient documentation" I think it adds little clutter, and the grouping rule enforces coding that doesn't treat the keyword as enough. Since the keyword does make the code easier to comprehend for some users I just don't think that requiring it to be left out is the right choice here. Again, though, I've voiced my opinion once, I'll live with what you decide after hearing my arguments :). > > 12.2 What does this mean for Boost where the convention is to put > > all code in the boost namespace? > > I think the emergent rule for boost is: separate domains go in their own > sub-namespaces. General-purpose code goes in boost. Probably 12.2 should be > changed to reflect that fact. I realize it's "emerging", but is that really the current desire? I'm asking because I'd like to know if the Boost.Threads stuff should be in boost::thread before I submit (would this cause any conflicts with the thread class name?). Bill Kempf Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2001/07/14374.php
CC-MAIN-2020-16
refinedweb
2,000
65.83
Java vs Golang Programming Language – Hey guys, welcome to my next blog on programming languages. Today, we would be debating about the famous Java and the so much speculated Google’s Go Programming. We all know what Java is. Let me give a recap for the beginners out there. First things first, what is Java? Java is a high-level programming language, but due to its nature which has more in common with C or C++, some people even refer to it as a low-level tool. To make it simple, a Java bytecode includes instructions which asks the program to perform a specific task. But so does Golang or any other programming language, then whats the difference? The thing is the structure of the code, the simplicity or the complicity, the compactness of the code and the speed per bytecodes or how much seconds it takes to perform a specific task; these are the things that make a lot of difference. For example, if you write a “hello world” code in Java; it would take up 3-4 lines of code. The same thing can be done in python in say, around in 1 line. Astonished? You should be. But the thing here also includes efficiency. If I write large programs in Java, it will probably be quicker when it gets executed, but that wont be the same if I use python. Python is much easier to write, but is slow when compared to Java. But, I am not here to talk about python, am I? I am here to talk about Golang and Java. So, this was just an intro for the newbies out there who wants to know why comparing programming languages are important. So, lets have a look what these two languages: Go and Java have under the table. Java vs Golang Programming Language Examples: Before we proceed to actually calculate the differences between these two languages, lets take a look at the piece of code with similar examples. Calculation of all integers from 1 to 10 in Java: package calcint; public class newint { public static void main(String[] args) { int intval; int last_val = 11; for (intval = 0; intval < last_val; intval++) { 4.8 (1,934 ratings) ₹19999 View Course System.out.println(“Loop Value = “ + intval); } } } Now, lets take a look at the same example in Golang: import “fmt” func calcint() { for i := 1; i <= 10; i++ { fmt.Println(i) } Yup, that’s it. No so hard, is it. When I ran these two I actually got the results pretty amazing. I ran Java in the JVM and Go in its basic interpreter, and to my shock Go was actually faster than Java. I though maybe GO is faster than java in small pieces of code, so I dug in a bit deeper. Recommended courses What exactly is Golang? Yup. I actually should have told you this at the very start, but I couldn’t resist myself showing the difference between the two. Go was written by the Google developers and was actually developed to provide fast responses and development, much better support for modern computing techniques, and a much clear human-visible code than other systems languages like C or C++. If you are a C or C++ programmer, then you will probably find GO much better than the likes of it. Go was intended primarily to be a systems language, like C or C++, which are fully capable for supporting front end application’s development. Why was Go actually developed when we have systems languages such as Java and C? Yeah. That is indeed a good question. The answer is something like this. Few years ago, before Go was developed, the developers at Google wanted a language with some efficient libraries to improvise the support for latest computing technologies something similar to C++ or Java. But the thing was, if you write more libraries for languages that already have so much to begin with, and that too without any built-in support for latest computing techs, it simply wont work. As a matter of fact, that seemed like a totally idiotic idea. So, these questions started to become nightmares for them. And then came the idea of building a totally new language from scratch. The developers of Go were always too tired to select from either ease in development or the execution of code and the efficiency of its compilation. So, they thought why can they create something which has everything in particular? Thus, Go was developed to provide superior and quick development, fast compilation along with good efficiency. Besides, if this is not enough, the developers of GO decided to keep a BSD style license to this language, thus making it open source. Now, comes the Inevitable Question.. So, finally now comes the question of the decade. Why develop Go when you have C++ or Java? And what exactly is the difference between the two. So, now lets take a deeper look in the similarities and their differences. Both Java and Go have the functions concept though they are slightly different when compared altogether. In Java, if someone is referring to a function, they are actually referring to the specific body of the code, which include the name, the return type and the parameters rather than just the function itself. Similarly, if a persons refers to a function within the class, its actually referred to the function which is a member or even a method sometimes. The thing is if you have used Java previously, you will probably find GO easier to begin with, but if its vice versa; you will probably find yourself in trouble wondering the whys and why nots in Java or C. Besides, the syntax of GO is very different from the likes of C or Java. If you are used to the method of using data types, list identifiers and paramters in Java, then you probably would have to find GO extremely weird and uncomfortable. Even the interface of GO is fairly different from that of Java. It allows multiple return values from methods and functions and it does not allow implicit type casting. If you try to force coerce these things, you will eventually end up with a compiler error. You need to specifically let Golang know when you want to switch between types. Is Golang object oriented? Now, this my friend, is a tough question to answer. Go doesn’t have many object oriented features like full encapsulation or inheritance or even polymorphism. Infact, GO doesn’t support inheritance to begin with. As a matter of fact, Go implements interfaces and allows for something called as “pseudo-inheritance”. I cannot actually explain how this works without actually showing you a problem. So, I will most likely have to leave this part off for my tutorials rather than over here. But that’s not it. If you have studied Java in detail, then you know that the type hierarchies do cause a lot of headache with overhead compilation and multiple inheritance. But the developers of GO, rather found a shortcut through this gap. The developers actually opted out from adding these features to the GO. Trust me, and that worked. People actually loved this a lot and this saved GO programmers from a lot of hassle. Here, there are no pointer arithmetic unlike object oriented languages. Pointer arithmetics if not used properly, leads to weird code sets and fatal software crashes. Thus even this feature was completely discarded in GO. Memory usage in GO v/s Java Memory cleanup in Go is somewhat similar to that of Java here. It has automatic garbage collection. Thus, the hassle of explicitly freeing up of memory or deletion of certain apps was indeed escaped. The Go developers intended to pry open the efficiency in garbage collection. Besides these, they made GO in such a way that it now utilizes the simple mark and sweep garbage collection method, thus making it more efficient. There is even no function overloading supported in GO. Thus, this saves go from language fragility and doesn’t cause a mess when sweeping up the memory like it does in a ugly way in Java. Conclusion Nuf said, I think these differences are enough to let you know the importance of each language. But as I said previously, GO is not exactly what an object oriented language looks like, but you can still it is possible to program Go in an object oriented way though it doesn’t support full encapsulation or polymorphism. Though GO overlaps Java in a lot of places, it can never replace JAVA. Java is like a king whereas Go is an adviser to the king. Thus the end result is either Java or GO, they both are needed when the situation arises. First Image Source: pixabay.com Recommended Article Here are some articles that will help you to get more detail about the Java vs Golang so just go through the link. - Know The Best about Haskell Programming Languages - Useful Guide On Java vs C# - Amazing Guide On Scratch Programming - You Must Learn About Web Services Interview Questions and Answers - Top features of Java Web Services Interview Questions - Careers in JavaScript - 10 Interesting Things about Java Programming Language - Useful Guide On Programming for beginners (Language, Software) - Important things to know about Haskell Programming Language Software Development Course - All in One Bundle 600+ Online Courses 3000+ Hours Verifiable Certificates Lifetime Access
https://www.educba.com/java-vs-golang/
CC-MAIN-2019-30
refinedweb
1,577
62.58
Coinex Smart Chain (hereinafter referred to as CSC) is one of the best blockchain platforms for creating crypto tokens or building DApps, Coinex Smart Chain (CSC) is represented as a super secure blockchain platform in the crypto space, CSC blockchain supports multiple token standards for token building, such as CRC20, CRC721 NFT, CRC115 and build smart contracts and decentralized applications. CRC20 tokens are commensurate tokens, which means that all units of CRC20 tokens have the same value with each other & CRC20 tokens can be traded on DEX or CEX platforms. Anyone can print CRC20 tokens freely on the coinex smart chain blockchain, you can use trumple , hardhat or Remix IDE. In the previous article we discussed how to make standard fix supply RC20 tokens, but in this article I will provide a tutorial on how to “Create Mintable Token CRC20”. Mintable is a feature on CRC20 tokens that allows to increase supply at any time, usually this is used for StableCOIN (FIAT) tokens or game reward tokens that are set for Unlimited Supply. The Mintable feature allows you to print any amount at any time. Create Mintable Token CRC20 Coinex Smart Chain 1. Prepare Wallet EVM & Coin native Coinex Smart Chain (CET) You can use the wallet metamask browser or android smartphone, but for convenience we recommend you use the wallet metask browser. Buy CET coins on “Coinex Exchange“, CET coins are used to pay gas fees when creating CRC20 token smart contracts, token minting processes and several other transactions. For all this process you only need 10 CET coins or the equivalent of $0.63, this fee is very cheap when compared to ethereum which has to prepare $75-$150 to create a smart contract. 2. Solidity Smart Contract. # Solidity Smart Contract (Standart). pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract CryptoVIRMintableToken is ERC20 { constructor() ERC20("CryptoVIR Mintable Token", "CVRM1") { _mint(msg.sender, 1000 * 10 ** decimals()); } } # Mintable Feature The following are the mintable features that you need to input into your smart contract, so that your CRC20 token has a mintable function import "@openzeppelin/contracts/access/Ownable.sol"; function mint(address to, uint256 amount) public onlyOwner { _mint(to, amount); } # Combined Results of the Smart Contract above This solidity smart contract is what you need to input into remixethereumIDE, // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract CryptoVIRMintableToken is ERC20, Ownable { constructor() ERC20("CryptoVIR Mintable Token", "CVRM1") { _mint(msg.sender, 1000 * 10 ** decimals()); } function mint(address to, uint256 amount) public onlyOwner { _mint(to, amount); } } 3. Deploy Mintable Token CRC20 I use RemixEthereumIDE to deploy smart contracts, make sure your wallet is filled with some CET coins. # Go to the remix.ethereum.org site, connect your wallet, create a new sol file and enter the solidity smart contract code # Use compiler version 0.8.4 , click “Auto Compile” and “Enable Optimization 200” # Wait for the complie process to finish, make sure there are no warnings or errors during compilation, make sure a green check appears on the left # In the ENVIRONMENT section select “Injected Web3” # ACCOUNT : Select the wallet you use to deploy the smart contract # CONTRACT : Choose your smart contract name, for example “CryptoVIRMintableToken” # Click “Deploy” and confirm “Confirm” on your wallet # Wait 3-5 seconds, and check the status of your transaction in the block explorer, once fully confirmed, your token will be printed on the coinex smart chain blockchain # Process deploy completed, The smart contract is completely on the blockchain, and the tokens are minted according to the initial minting amount when first deployed. 4. How to Use CRC20 Minting Feature Minting is a feature to add token supply, you can use RemixEthereumIDE or do the minting process on the Coinex blockchain explorer (CSC). in this article I will show you how to mint in RemixEthereumIDE. # Because the token that we are deploying uses Decimal 18, then when you want to mint, you must add a number (ZERO) with the number 18. My example will mint 3000 tokens, then what we have to input is 3000000000000000000000 # Enter RemixEthereumIDE, scroll to the bottom of “Deployed Contract“, you will see a smart contract that has been deployed, click the smart contract # Click the “Mint” button, In the “to” field, enter the address that will receive the token and enter “amount” the number of tokens you want to mint. Click “transact” + confirm on your wallet # After the minting process is complete, the supply of tokens will increase according to the number of tokens you are minting GOOD LUCK
https://cryptovir.com/how-to-create-mintable-token-crc20-coinex-smart-chain/
CC-MAIN-2022-40
refinedweb
767
56.18
Thursday, September 9, 2010 Unsung Heroes L ocal S ailors Quietly Come and G o F rom War Z ones Photo By Frank Marquart ELECTION 2010 - Primary Profiles, Pages 3-5 The County Times Attention RepublicAn VoteRs! It is time to bring a responsible, common sense business approach back to our government. Be certain we hire someone with the management skills, proven leadership capabilities, and entrepreneurial vision to lead our party this November. Thursday, September 9, 2010 2 What’s Inside On T he Covers ON THE FRONT Julie and Capt. John Lemmon with their children at their home in Wildewood. John recently returned home after an eight-month individual deployment to Africa for the Navy. ON THE BACK Zach Snell ran for the first St. Mary’s Ryken touchdown at their new stadium Friday night. On September 14th Elect Thomas F. McKay as your Commissioner President Candidate newsmakers From left is Will Esham, Craig Casey, Rob Taylor, Pj Aldridge, Buddy Trala, Blaine Champlin and Rico Liberto. His leadership four years ago lead to 7 tax cuts, reduced debt, smaller government, reduced regulations, solutions for small businesses, better schools, better public safety, better protection of our rural character, better protection against encroachment on our Navy Base. When we win in November, we must be prepared to lead. McKay has done it before, he can do it again! His plan to lower taxes, restore confidence in government, promote individual responsibility, and lift the burden of government from the backs of local businesses so jobs can be created is the responsible leadership our county needs! Paid for by Friends of Tommy McKay, Marilyn A. McKay, Treasurer sports Professional lawnmower racer Jason Brown of Clements won his second straight USLMRA SP class national championship this past weekend in Delaware, Ohio Also Inside 3 Candidate Profiles 6 County News 8 Money 9 Editorial 13 Obituaries 16 Education 18 Cover Story 21 Newsmakers 22 Community 23 Community Calendar 26 Entertainment 27 Columns 27 Games 28 Crime 30 Bleachers 32 Football 34 Fishing 3 The County Times Thursday, September 9, 2010 Meet The Candidates The County Times offered all candidates in contested races on the Primary Ballot the opportunity to publish biographical information about themselves. We are providing each candidate with space to provide the information that follows, which includes occupation, volunteer associations, memberships and previous political experience, as well as a 150-word “in your own words” essay on why voters should vote for them. Candidates who are on the primary ballot but do not appear in this issue declined or did not respond to The County Times’ invitation to participate. These candidates included commissioner candidates Randy Guy, Richard Johnson, and Dan Morris. Primary Election Day is Sept. 14. Dorothy Marie Andrews, 55, Republican Kenny Dement, 75, Republican • Candidate for St. Mary’s County Commissioner, District 1 • Occupation – I am a Small Business Owner of Endless Summer Tanning Salon, LLC for over 10 years. • Volunteer associations, memberships, previous political experience – I volunteer by sponsoring my high school clients in their extra-curricular activities. This year, I participated with clients, The Pink Hooters, who raised money for breast cancer. Non-profit organizations should be supported by local businesses and communities not the local government, so I support the Pregnancy Care Center which receives no local monies. I am a member of the St. Mary’s Republican Club and do participate as much as possible in other party events. I am a member in the Lexington Park Business and Community Association and the Elks Lodge No. 2092. • Candidate for St. Mary’s County Commissioner, District 1 • Occupation – Retired, Current County Commissioner, District 1 • Volunteer associations, memberships and previous political experience – 8 years experience as County Commissioner; my political experience in St. Mary’s County began in 1970; member of the Knight of Columbus, Optimist Club and Holy Face Catholic Church. • Why should voters vote for you? I ask for your support to help in preserving the past and planning the future of our St. Mary’s County. I want to continue to represent all of the people of St. Mary’s, no matter what affiliation they may be. I will continue to listen to your concerns, use common sense, and make logical decisions. When I continue as your commissioner, I plan to pursue a variety of issues that affect every citizen – among them are controlling financial waste and implementing a procedure for spending accountability. My priorities are: Education, Fire & Rescue, public safety, law enforcement, watermen/agriculture, Pax River, Webster Field, recreation, tourism, seniors, growth management, zoning and housing. I would like to continue to serve you as a member of the St. Mary’s Board of Commissioners. People know me as an available listener with vision. I am honest, experienced, dedicated, reliable and considerate. Please exercise your right to vote. • Why should voters vote for you? First, a vote for me would place a regular “Joe” in office. Right now, we don’t need anyone who is political. We need someone who knows how to make sacrifices for the success of our community. I do this many ways for my business. One is taking a smaller check instead of cutting employee hours. Next, I know how to be fiscally responsible with money. I have made sound decisions in my business which has kept me successful today. My attitude is “not taxing more” and “shrink local government.” It is crucial that we find extreme measures to cut spending instead of the “spend” attitude we now have in our administration. Last, I believe that listening “to the people” is the key to creating a healthy environment for everyone within our community. Brandon Hayden, 39, Republican Cindy Jones, 45, Republican • Candidate for St. Mary’s County Commissioner, District 2 • Occupation – Regional Manager, Fisher Auto Parts Inc. • Candidate for St. Mary’s County County Commissioner, District 1 • Volunteer associations, memberships and previous political experience – St. Mary’s County Planning Com• Occupation – Business Owner mission 2006-Present, Vice Chairman 2009, Chairman 2010; St. Mary’s County Chamber of Commerce, Board of • Volunteer associations, memberships and previous political experience – Co-Founder Convalescent Out- Directors 1999-2006, President and Chairman of the Board, 2004-2005, Executive Search Committee Chairman, reach Ministry; W. A. R. M.; Three Oaks Center; 2nd District Optimist Club, Tall Timbers; Fleet Reserve Ladies Ambassador’s Committee Chairman, Awards Committee Chairman; St. Mary’s County Economic Development Auxiliary Branch 93, Lexington Park; F. L. O. W. Mentoring, Piney Point Elementary; Council, 2004-2005; Federated Auto Parts Distributors, Inc. Board of Governors, 2003-2005 National Rifle Association; Gun Owners of America; Republican Women of St. Mary’s President 2009; Maryland Federation of Republican Women Nominating Committee • Why should voters vote for you? 2009; St. Mary’s County Coordinator, Bailey for US Congress 2008. I have a 20-year history of successful business ownership and community service • Why should voters vote for you? which gives me the experience to lead our county through these difficult economic times. When it comes to your tax money, I will bring the same attention to detail, and fiscal responI have a background in economics and own a successful small business. I know sibility that I developed in business, to the decisions I take at the Commissioners table. I will how to manage budgets and make prudent spending decisions. I will introduce transuse my experience to make government more efficient and customer friendly. I will personparency at all levels of County government and put an end to backroom deals. I am ally use the technology that makes my job as commissioner more transparent and accessible committed to not raising the property tax and Piggyback Tax rates. I am very involved to all citizens. I seek this job because I believe I have the background and experience to take in the community from mentoring children at Piney Point Elementary to supporting the good decisions, lead our community into the future, and to ensure that St. Mary’s County Three Oaks Center in Lexington Park. remains a great place to live, learn and work. Do You Feel Crabby When You Get Your Insurance Bill in the Mail? Give Us A Call. Weather Watch You’ll Be Glad You Did. Gary Simpson Katie Facchina 7480 Crain Highway La Plata, MD 20646 301-934-8437 April Hancock PO Box 407 Bryans Road, MD 20616 301-743-9000 An Independent Agent Representing: ERIE INSURANCE GROUP Standing: Dan Burris, Jake Kuntz, Seated: Lisa Squires, Susan Ennis, Donna Burris Burris’ Olde Towne Insurance Auto - Home - Business - Life Leonardtown & LaPlata • Bus: (301) 475-3151 The County Times Thursday, September 9, 2010 The risk of being struck by a falling meteorite for a human is one occurrence every 9,300 years St. Mary’s County REPUBLICAN CENTRAL COMMITTEE Vote For No More Than Seven David L. Bowles Patrick Burke Mary Burke-Russell Kevin Cioppa 4 un Fact Kenneth F. Boothe, 65, Republican • Candidate for St. Mary’s County Commissioner President • Occupation – Farmer • Volunteer associations, memberships and previous political experience – Farm Bureau member since 1993 and past President of St. Mary’s County Farm Bureau from January 1995 – September 1997; Served on Tri County Council Southern Maryland Regional Strategy Agricultural Task Force from November 1997 – November 1998. • Why should voters vote for you? I respectfully ask citizens to cast their vote for me because of what my neighbors know me to be and what I stand for. I am a life long county citizen and have degrees from the University of Maryland and University of Baltimore Law School. I seek the opportunity to “stand up” for St. Mary’s County and make my votes and actions count to restore our rural character and strong local government. Our rights and liberties and historic tradition are what makes up our rural character in St. Mary’s County. When these are lost, we have an absence of good government with any integrity. I am committed to reducing taxes and waste in county government and to make it more affordable to live in St. Mary’s County. I have new and different ideas. I need your vote to win. Thomas F. McKay, 53, Republican • Candidate for St. Mary’s County Commissioner President • Occupation – President, McKay’s Food Stores; Publisher, Southern Maryland Publishing, Inc. • Volunteer associations, memberships and previous political experience – Past-President Board of County Commissioners; Past Commissioner, Maryland Critical Areas Commission; Past Member, Maryland Association of Counties Legislative Committee; Past Member, Maryland Association of Counties Education Committee; Past Member, Tri-County Council for Southern Maryland; Past Chairman, Mid-Atlantic Food Dealers Association; Past Board Member, Maryland Retailers Association Food Council; Past Member, Richfood Advisory Board; Former Delegate, Republican National Convention; Member, Republican Club of St. Mary’s; Member, Knights of Columbus, St. Johns Council; Charter Member Hollywood Optimist Club; Past Member St. Mary’s County Elks Lodge. • Why should voters vote for you? Mark A. Cizler Ellynne Davis William Duff Tom Haynie Bryan Jaffe Gary Rumsey David Willenborg Paid for by friends for Mary Burke-Russell Tamara W. Sapp, Treasurer I respectfully ask the citizens of St. Mary’s to again allow me the honor to serve as your Commissioner President. My past leadership was as successful as any four years in our county’s history. We reduced the size of government, we substantially lowered the county debt, we self-imposed spending limits on government, reduced property taxes 3 times, we reduced income taxes twice, we reduced the energy tax by 50%, and we capped property tax for seniors at the age of 70. Additionally, by setting priorities we implemented the largest encroachment protection plan ever outside the Navy Base, we corrected the funding deficiency in education and law enforcement, the results of which we see today. Over the next four years we will lower the tax burden, align spending with county priorities, protect property rights, allow local businesses to grow again, restore trust in government, and blend our past with our future. Henry E Camaioni, 50, Republican • Candidate for Maryland House of Delegates, District 29A • Occupation – Realtor/Property Manager • Volunteer associations, memberships and previous political experience – I have voluntarily spent much of my time and personal finances in an effort to protect the rights of people in St Mary’s County. I provided essential arguments and evidence for the Metcom Task Force meetings. My testimony is clearly reflected in four of the Task force recommendations for the General Assembly, all of which I believe are necessary to protect against unethical conflicts of interest in local government. I have argued against forcing people to pay governmental agencies for services they don’t want and don’t need, and argued against approving a “shady” governmental project that I believe endangers children. • Why should voters vote for you? I grew up, live and work in St Mary’s County. This is my home and I care about the people. As Delegate I would represent the people, their concerns, their issues, and support the projects and policies that best serve the people. I did not make promises to special interest groups or other candidates for their endorsements because I am determined to be a true representative “of the people.” As Delegate I would work to lessen the heavy tax burden that has been placed on local citizens. I will be a highly determined representative “for the people” and believe I have the necessary skills to help create and promote the proper legislation for the benefit of the citizens. I started my first business when I was still in my twenties. I have more than twenty years of business and leadership experience and I would be proud to be your representative. Joe DiMarco, Republican • Candidate for Maryland House of Delegates, District 29A • Occupation – PlantTech at Chalk Point Generating Station • Volunteer associations, memberships, previous political experience – I have no previous political experience, however I have testified in front of the Maryland Senate, Maryland House and US Congress on various issues including Opposing Abortion, Same-Sex Marriage, Embryonic Stem Cell Funding, and Supporting Parental Notification, Traditional Marriage, Jessica’s Law and Pregnancy Care Centers. My wife and I are the Youth Directors at Hughesville Baptist Church where we lead and mentor youth from around our community. I also serve as a Trustee and Deacon at the church. Kenneth F. Boothe Candidate for Commissioner President St. Mary's County I ask Republican voters to cast their vote for me this September 14th. I am committed to vote and to act for the restoration of the real rural character of St. Mary's County and a strong local commissioner form of government able to act for its citizens. I am committed to supporting new and existing businesses because they are the foundation of our local economy. I am committed to education, public safety, other essential services and the taxpayers. I see my leadership and management techniques involving me acting as a trustee for St. Mary's County citizens. Authority: Committee for Kenneth F. Boothe, Commissioner President: Milton F. Boothe, Treasurer • Why should voters vote for you? I am running for office to give the people of my district a voice in our current legislature. I plan to listen to the ideas and concerns of the people and take them to Annapolis. If elected I hope to be an intricate part of reducing the State Budget and cutting wasteful spending. I believe in making Maryland a “Business Friendly State” which it is not with the added sales tax and corporate taxes this legislature has passed. I am proposing that we bring our taxes more in line if not below our neighboring states taxes. Short of this will cause more businesses to relocate to our neighboring states taking revenue and jobs with them. I am asking that the voters put their trust in me and allow me to represent them in Annapolis and make the government work for them not the other way around. 5 Thursday, September 9, 2010 The County Times Matt Morgan, 37, Republican • Candidate for Maryland House of Delegates, District 29A • Occupation – For the past 9 years I’ve worked as the Lead Technology; Specialist at the College of Southern Maryland and I also work as a Realtor for O’Brien Realty. • Volunteer associations, memberships, previous political experience – I am a lifelong resident of Southern Maryland. I have two children who attend public school. My family attends St. Francis de Sales Catholic Church and our kids participate in lots of community sports. I enjoy coaching football, flying and auto racing. • Why should voters vote for you? I am an average guy with good business experience, strong financial skills and most importantly common sense. I feel I can do a better job at representing Southern Maryland’s point of view than our current representative. There is a disconnect between our professional politicians and the average guy. Because unlike them and like you and, I know what it is like to go work every day. I know what it is like to struggle to make a mortgage payment, to pay for day-care, and to make sacrifices for your children. Because we are like minded, you can rest assured when there is a bill put forth that we have to live under, I’ll be making the same decision you would make. Working To Make St.Mary’s County A BETTER PLACE TO LIVE & WORK Jannette P. Norris, 63, Democrat • Candidate for St. Mary’s County Treasurer • Occupation: St. Mary’s County Treasurer • Why should voters vote for you? I have worked in the Treasurers office for 31 years. The past 16 as Treasurer. I believe in the best service for the best cost. I have managed to handle the growth in the county as well as implemented many new changes and additions to the tax rolls without having to increase staff and with minimal operating costs. I have the experience, dedication and skills to continue serving St. Mary’s County as Treasurer. I love this county and the people in it. I would appreciate your support on September 14th. Daniel H. Raley, 60, Democrat • Candidate for St. Mary’s County Treasurer • Occupation – Retired grocery store owner, currently County Commissioner • Volunteer associations, memberships, previous political experience – Member American Legion Post 255, Lexington Park Lions Club, St. Michael’s Knights of Columbus, St. Marys County Farm Bureau, St. Georges One Hundred, 12 yrs as County Commissioner of District Four • Why should voters vote for you? I would like to gradually and economically bring about changes to the daily operation of the Treasurer’s Office. I would like to offer the citizens more options and more transparency in their dealings with the Treasurer. The payment of taxes and fees should be made as easy and convenient as possible. I would enhance the flow of revenue data to the county. I would convert software from a stand alone program that is administered by someone in Virginia to the county’s current system that could be handled by existing county staff, thereby enhancing efficiency and lowering recurring costs. Everyday practices in this office need to be updated to the standards of the 21st century. t c e l E ReDELEGATE JOHN F. WOOD, JR. YOUR VOICE IN ANNAPOLIS By Authority John F. Wood, Candidate Julia Lee Forbes, Treasurer The County Times Thursday, September 9, 2010 6 ews This Year Hoyer May Have His Biggest Challenge in Years Steny Hoyer Collins Bailey Charles Lollar By David Saleh Rauf Capital News Service Republicans in Maryland’s 5th Congressional District have noticed something new this year: House Majority Leader Steny Hoyer appears to be grinding the campaign trail. Hoyer, a Maryland Democrat and 15-term incumbent, is meeting with teachers and small business leaders and is ramping up appearances across the district, after years of what Republicans call less-than-aggressive campaigning. “He’s done more campaigning in the last three months in the district than he’s done in the last 10 years in my unofficial observation,” said Collins Bailey, a Republican who lost to Hoyer in 2008. “He’s actually campaigning locally now.” It’s all a product of what local GOP leaders say could be the most competitive 5th District race in decades. Hoyer shrugged off assertions that this campaign is any different from the past. “I always run an aggressive campaign, whether I have an opponent or not. And I’m always in the district,” he said. Hoyer has easily beaten every Republican since taking office in 1981 and political experts are not yet calling the overwhelmingly Democratic district -- which includes chunks of Prince George’s and Anne Arundel and all of Calvert, Charles and St. Mary’s counties -- a battleground. But this year’s election could be different, experts say. For one, dissatisfaction with government is making this campaign difficult for incumbents. And the quality of the challengers could also complicate the election for Hoyer, said Michael Cain, director of the Center for the Study of Democracy at St. Mary’s College of Maryland. “I actually think Steny Hoyer is concerned,” Cain said. “I don’t think he will take this race for granted. I expect he will be out there more, trying to get out his message.” Four Republicans are vying in the Sept. 14 primary, according to the Maryland State Board of Elections. Bailey, a self-proclaimed constitutionalist who won 24 percent of the vote in 2008, has name recognition in the district after that campaign. A more serious challenge, observers say, could come from political newcomer Charles Lollar, a former Marine who was once touted as a potential gubernatorial candidate. Cain said Republicans are high on Lollar because he appears to be the strongest candidate in the field. But, he cautioned, “No one nationally is calling this seat in play.” “The question is if this is going to be a tight, competitive race,” he said. “I don’t know yet. There’s a lot of this game to be played.” Still, local GOP leaders are painting Hoyer as out of touch with the district and blasted him and the Democratic administration for healthcare reform legislation, a stalled economy and high unemployment rates. But riding a wave of anti-incumbent fervor into the general election will not be enough for Republicans to win a blue state like Maryland, said Cain. To win, they will have to go beyond the “Tea Party vote and get more of the electorate,” he said. That includes capturing votes in Prince George’s County, which has the most voters in the district. Republicans have traditionally done poorly in the county: In 2008, Bailey won 12.9 percent of the vote there. GOP candidates have not campaigned there in the past, said Mykel Harris, chairman of the Prince George’s County Republican Central Committee. “Charles is at least going to ask for the vote,” said Harris, who is also Lollar’s campaign manager. “Many Republicans see the African-American vote as hostile and to a large extent that’s true. But at the end of the day there are people who want to be asked for their vote.” Final Decision Pending on St. Mary’s River Oyster Sanctuary By Guy Leonard Staff Writer “My family and my business depend on me.” You have obligations... and Heart Failure doesn’t have to prevent you from meeting them. “Living Well with Heart Failure” is a HealthLink program designed to help you manage this chronic condition. The focus of this program is on understanding heart failure, the treatment of heart failure and what you can do to live your life, your way. Offering outpatient and educational seminars which teach self management, nutrition, proper use of prescribed medications and basic lifestyle changes, “Living Well with Heart Failure”, combined with your physician's advice, can greatly enhance the effectiveness of your treatment. Join Us! Saturday, Sept. 18 and Saturday, Dec. 4 8 - 11:30 am Multipurpose Room of St. Mary's Hospital Light breakfast offered. FREE. Please call to register and for information about participation incentives! Local watermen met with others from around the state last week to put together their recommendations to the state for boundaries for a controversial oyster sanctuary plan and want to ensure that productive waters here are still open for harvesting. Robert T. Brown, president of the St. Mary’s County Watermen’s Association, said that local watermen’s groups put together their own plans for their respective counties in time to meet the state’s Sept. 14 deadline for a final decision on the sanctuary boundaries. And the St. Mary’s River, Brown said, is one of the most important for local watermen to stay in business, though Gov. Martin O’Malley’s plan calls for taking some of the most productive bottom and prohibiting oystering there. “We want to move the [boundary] line north, upstream, to Martin’s Point and Short Point,” Brown said of the waterman’s proposal. “We would have all the ground south of that. “That would still give them plenty of oyster seed ground.” Brown said that the watermen’s offer would ensure that there would be plenty of young oysters in the northern waters of the river to ensure that oysters could continue to repopulate. The southerly waters would ensure that watermen would have enough older, marketsized oysters to stay in business. Watermen became incensed last year over O’Malley’s plan to restrict 24 percent of productive oyster bottom statewide in favor of oyster sanctuaries in an effort to protect and replenish the species. Watermen claimed that taking productive bottom would be an increasing financial hardship on them and sanctuaries would eventually fail for lack of being worked to remove silt which would kill young oysters. Brown also said watermen offered up the entirety of Breton Bay, a portion of St. Clements Bay and the Wicomico River from Bushwood Wharf to Bluff Point for state sanctuary land. Meanwhile activists locally planted more oyster seed, or “spat on shell”, on Aug. 28 to help replenish stock. Volunteers working with the St. Mary’s River Watershed Association, which supports the original state-sponsored oyster sanctuary plan, laid down 500,000 spat within the boundaries proposed by the state. “This is in support of our goal to put 12 million oysters in the river in five years,” said Bob Lewis, executive director of the watershed association. “They are going to go in the proposed sanctuary.” The group has already planted 275,000 since June, Lewis said, and plans another 500,000 in September. Lewis said that while watermen have pressed the state to use unproductive bottom for their sanctuaries project, Lewis said that the cost would be prohibitive. “That would require a huge investment to replenish that bottom,” Lewis said. “I can’t argue with the watermen on where the productive bars are. “We want to do everything we can to increase the fisheries down there.” guyleonard@countytimes.net 7 Thursday, September 9, 2010 The County Times GARY RUMSEY ews Mazerine Wingate, a resident of St. Mary’s County, will be celebrating his 100th birthday Sept. 20. Wingate has been an employee at the Lexington Park Post Office for 40 years and still works there part time, every day from 8 a.m.-12 p.m. In addition to this, he is a deacon at First Missionary Baptist Church, works in his garden and is still driving. His family will be celebrating his birthday at the J.T. Daugherty Conference Center in Lexington Park Sept. 28. Anybody who wishes to attend it are welcome to do so, but they will be required to pay for their own meal. For those interested in attending, contact Adrienne Ellis a 301-894-7421. Photo by Frank Marquart Fritz Outraged With Town Hall Handouts By Sean Rice Staff Writer St. Mary’s County State’s Attorney Richard Fritz is outraged that supporters of the Town Hall Alliance were handing out material near the county’s early voting center that could be interpreted that Fritz and others are endorsed by, or working with, the Town Hall Alliance. The Town Hall Alliance is a slate of candidates organized by County Commissioner Larry Jarboe. Supporters of the slate were handing out sample ballots on Sept. 3 near the Potomac Building in Leonardtown that showed checkmarks next to Town Hall Alliance Candidates – and also next to candidates who are not part of the Alliance, including Fritz, commissioner candidate Todd Morgan, Congressional candidate Charles Lollar and Maryland Senate candidate Steve Waugh. “I was shocked when I noted that a checkmark was beside my name and another candidate who are not members of the Town Hall Alliance,’ Fritz said in a press release. “I was never asked and I never granted permission to have my name added to this bogus ballot … I hope it will be made clear that I do not belong to The Town hall Alliance; and that I feel it is completely fraudulent to hand out a ballot suggesting that I am supporting such a slate of candidates,” Fritz said. “This fraudulent ballot was completely unfair to all other candidates who have expended great effort to get their message across to the voting public.” Morgan, when contacted by The County Times, said he is not associated with the Town Hall slate or any other group of candidates other than the Republican Party. for Republican Central Committee • Are you tired of candidates who break promises? • Are you tired of sweet-heart deals made in smoke filled rooms for well connected bigshots? • Are you looking for new blood with fresh ideas? • Do you wish “conservative” meant something again? It all starts with the Republican Central Committee. Nothing will change in county politics until the “power elite” who run the Committee today are sent home. Elect Gary Rumsey and take a giant leap toward a Republican Party that is once again open, honest, conservative, and truly cares about the average hardworking taxpayer...like you. Paid for by citizens for Gary Rumsey Daniel H. Raley For County Treasurer The Treasurer’s office has been under the same leadership for 16 yrs. The current Treasurer has consistently refused to enact any of these advances. Shouldn’t you be able to call and if the line is busy, just leave a message and get a call back? This is just common courtesy. There is no message taking service available. The county pays for 3 extra phone liens that are separate from the county system and are only available when the office is open. Online payment services, voicemail, email, acceptance of credit, debit and check cards are a fact of life and need to be incorporated into the Treasurer’s office. The current Treasurer has purchased a third party software to run her office that cannot be maintained by our county IT staff and regular changes have to be paid for on an hourly basis. The taxpayer should be able to view their tax bill online at least 60 days prior to payment. Who hasn’t changed their business methods in the last 16 yrs? Today we must stay up to do. It’s uncomfortable to change but it’s a necessity. We need integrated software to readily identify revenue trends to assist in the county’s budget process. “Nobody likes paying taxes but the process should be as easy and with as many options as possible.” “Vote reasonable, gradual, much needed improvement on Sept. 14” “Experience does not always = efficiency” by auth: Daniel H. Raley candidate, Ann Raley Treas. The County Times Thursday, September 9, 2010 8 for the love of Money Maryland Bank Merging Into Old Line Bank Old Line Bancshares, Inc., the parent company of Old Line Bank, and Maryland Bankcorp, Inc., the parent company of Maryland Bank & Trust Company, N.A., announced on Sept. 1 the execution of a merger agreement that provides for the acquisition of Maryland Bankcorp, Inc. by Old Line Bancshares, Inc. for approximately $20 million, or approximately $30.93 per share, in cash and stock. According to a press release, Old Line Bank will be the “surviving bank” after Maryland Bank’s parent company merges with Old Line Bank. The acquisition will increase Old Line Bancshares, Inc.’s total assets by more than $349 million for total assets immediately after closing of approximately $750 million. The acquisition will add ten full service branches to Old Line Bank’s existing ten-branch network. “MB&T over the years has built a core deposit base that is truly enviable in today’s banking environment,” James W. Cornelsen, President and Chief Executive Officer of Old Line Bancshares, Inc., said. As of June 30, 2010, MB&T, with deposits of $297 million, had the highest percentage of non-interest bearing deposits of any Maryland-based commercial bank at 31% of total deposits. “By joining together with our Southern Maryland neighbor, we envision being able to achieve significant cost savings of more than 35% over the next two years, and, take us a big step closer to reaching our goal of being Maryland’s next $1 billion asset bank,” Cornelsen said in a press release. Maryland Bank was founded in Lexington Park in 1959 by Jack Daugherty. Daugherty’s son, G. Thomas Daugherty, President of Maryland Bankcorp, said: “Over just the last few years, we have seen several of Maryland’s largest independent banks vanish, purchased by out of state banks. This partnership is a step toward beginning to fill that void.” As part of the agreement, Old Line Bancshares, will add G. Thomas Daugherty and Thomas B. Watts, CEO of Maryland Bank and Trust to its board of directors and to the board of directors of Old Line Bank. Daugherty and Cornelsen have told the media that it is unknown yet if there will be any layoffs for Maryland Bank and Trust employees. The merger agreement is subject to approval by both companies’ stockholders and banking regulatory authorities. 9 Thursday, September 9, 2010 The County Times Endorsements Disclosure Before Endorsements; It’s Responsible Journalism Southern Maryland Publishing, which publishes The County Times as well as several other local newspapers in Southern Maryland, announces its endorsements for those candidates who are running in contested primaries this September 14th, which we believe are the best persons to represent their respective party in the upcoming November 2nd general election. The endorsements are based upon several criteria including the past training and experience of that individual as it relates to the position which he or she seeks, and the public policy or managerial philosophy of the individuals, especially as it compares to the prevailing public policy philosophy among the general public in our community. Additionally, we look closely at each candidates individual loyalty to the general population of St. Mary’s County as opposed to special interests. Based on the knowledge we have attained by our reporters following the candidates regularly, combined with our continued coverage of what is taking place in our community from Charlotte Hall to Ridge, we offer the following opinions to our readers who seek an opinion from an informed media which believes our community wants leaders who are fiscally conservative, believe in individual responsibilities, individual property rights, a free market economy, and place high values on education and public safety. While disclosing our philosophical prejudice we must also disclose that one of the candidates we are endorsing, Thomas F. McKay for Commissioner President is the publisher for Southern Maryland Publishing. We always disclose who we are, and it will often ref lect on our editorial pages. However, we take great pride in the fact that we never hide who we are from our readers, thus we raise the bar for our reporters to assure our disclosed prejudice never finds it way beyond our opinion pages. We thank our readers for their constant comments about our paper’s integrity and high standards. We can assure our readers that our endorsements are weighed very carefully by what we believe is in the best interest of our community at large and not by any special interest or political group or political boss. The Best Candidates To Lead Their Party In 2010 Republicans: U.S. Congress 5th District: Charles Lollar There is no doubt the general public is upset with Washington and well they should be. No common sense American believes the spending policies over the past four years are good for our Nation. The economy is in shambles, the American dollar is at its lowest value in our memory, and small business is going out of business. Two Republican candidates deserve the opportunity to carry the debate to November for the Republicans, Collins Bailey and Charles Lollar. Both have articulated a clear change in direction for our nation, both are fine gentlemen with a good background for the job, yet only one can move on. The best person to move on to November is Lollar. He has a clear vision to balance the budget, reduce the regulatory environment, and limit career politicians time in office. Lollar represents the best hope for Republicans to unseat Steny Hoyer this November. House of Delegates 29A: Joe DiMarco There is no clear choice in this primary, however DiMarco has shown that he is somewhat more informed on the issues and represents a hard right alternative for those Republicans who are looking for that kind of candidate. Almost all the district is made up of St. Mary’s with a small portion in Charles County. Matt Morgan live in Charles County and it would seem disproportionate to give this seat away to Charles County. Additionally, Morgan is associated with the strong arm campaign that kingpin Ken Rossignol is using in his attempt to take over the Republican party in St. Mary’s County. President of the County Commissioners: Thomas F. McKay None of our readers should be surprised by this endorsement, McKay is the publisher of this newspaper. But when you look closely at his experience, his training, and his success both as a business man and as a former Commissioner President, the facts overwhelmingly support this choice. McKay has articulated a vision for the future that will control spending and taxes, make our county a better place for small business to grow jobs, and assure quality education and public safety. Most people had wished he never left county government before and the Republican party would do well to bring him back as their candidate this November. Kenneth Booth is a fine gentlemen and has run a good campaign, his limited focus on farming issues, while important to our community, would not be enough to carry him through the November election. Randy Guy switched parties to run and has spent the campaign slinging mud and distorting facts as directed by kingpin Rossignol and his “Chicago political style” machine. For any of the Rossignol characters to win a contested primary would open the door for misgivings in the Republican party in St. Mary’s. The local party has worked hard for many years to become one of the best in Maryland, it would be a shame to see it fall so fast. County Commissioner District 1: Kenny Dement or Cindy Jones The County Times believes that either of these two candidates represents a good choice for the Republicans this fall. Dement is the incumbent and has shown repeatedly his ability to win in the General Election. Many argue he has not shown leadership on tax and spending issues, however he voted all seven times with McKay four years ago to lower taxes as well as reduce spending. Throughout his 8 years as commissioner Dement’s greatest asset has been his individualized attention to citizen’s problems. When there’s a clogged road drain or a pothole in the neighborhood, Dement would not rest until the problem was fixed. Cindy Jones has worked hard and displays good qualities that would represent the Republican party well this November. She is seeking office for the first time and has a background in business and economics. Jones has articulated her vision quite well and would offer a fresh, competent new face at the commissioner table. Either Dement or Jones would represent the Republicans well this November. Dorothy Andrews is a fine lady who has run an underdog campaign as her first entry into politics. She has progressed well and represents a good future for the Republican party down the road. Richard Johnson has displayed the Rossignol mudslinging, fact distortion playbook like a loyal follower. He has yet to articulate a single public policy idea that he would bring to the table. County Commissioner District 2: Brandon Hayden As an independent business man and member of the St. Mary’s County planning commission, Hayden has demonstrated management qualities that would serve the Republicans well this November in a race that will P.O. Box 250 • Hollywood, Maryland 20636 News, Advertising, Circulation, Classifieds: 301-373-4125 be hard fought by the Democrats. Hayden has run a conservative campaign in order to preserve resources for the November battle. Republicans can count on his integrity this fall. Dan Morris, who also changed parties to run as part of the Rossignol “Chicago political style” takeover of government, probably could have been a good commissioner candidate for either party, but we are really not sure. Before allowing himself to get tied up with this group he seemed like a much different person. We are not sure what his political views are, only what the kingpin has told them all to say. Some people just don’t do well with power and politics, it changes them dramatically, and Morris is one. Democrats: U.S. Congress 5th District: Steny Hoyer Hoyer’s long tenure in the U.S. Congress has made him an inf luential legislator for Southern Maryland. The Democrats cannot possibly choose anyone else to carry the banner this November, Hoyer has earned that right. His leadership role is important, and you have to admire his ability to get there, yet it may be the thing that ultimately costs Hoyer his career. He will no doubt win the nomination, but his appearance on the ballot this November may do more harm than good to the other Democrats. County Treasurer: Janette Norris Jan Norris has struggled some with the fact that someone within her own party would challenge her for a job she has held so long. She should be delighted he did. It has given her an opportunity to demonstrate her accountability to the public -and she has done so quite well. The fact that she started the job 16 years ago with just 4 employees and today she still gets the job done with just 4 employees is a testament to her competency. Dan Raley put himself out there and allowed the voters the opportunity to have a choice, and he should be commended for that. His 12 years of service as county commissioner is coming to an end, we thank him for that service but we see no need for a four year tour of duty in the treasurer’s office. James Manning McKay - Founder Eric McKay -Associate Publisher..................................ericmckay@countytimes.net Tobie Pulliam - Office Manager..............................tobiepulliam@countytimes.net Sean Rice - Editor....................................................................seanrice@countytimes.net Angie Stalcup - Graphic Artist.......................................angiestalcup@countytimes.net Sarah Miller- Reporter - Education, Entertainment...sarahmiller @countytimes.net Chris Stevens - Reporter - Sports......................................chrisstevens@countytimes.net Guy Leonard - Reporter - Government, Crime...............guyleonard@countytimes.net Sales Representatives......................................................................sales@countytimes.net To The Editor The County Times Thursday, September 9, 2010 10 Maryland Needs Table Games, Raley Is The Right Choice for Not Slots Treasurer I recently took a day trip to Dover for now offer table game style gambling. Many I am writing in response to several letters campaign that used the slogan “If it ain’t broke, printed by your paper and others regarding the upcoming election for County Treasurer. While some have unfortunately been mean-spirited, the one overarching theme by the letters submitted from Jan Norris’s supporters has been that the voters should allow Jan Norris to remain Treasurer because, as Mr. Robert Jarboe stated in his recent letter, the voters should “let Jan Norris have four more years and retire as she has earned it.” This election is not about what Jan Norris or Dan Raley have “earned” due to their prior years of public service. Both have served our County; Ms. Norris as Treasurer for the past 16 years and Dan Raley as our County Commissioner for the past 12 years. This election is instead about choice. The choice is clear. If you believe it is time for the Treasurer’s office to be updated so that citizens can pay their bills online, view your account information online, be able to leave a voicemail, and communicate with the office via email in a timely manner, then you should vote for Dan Raley. If you believe the Treasurer’s Office should stay the way is has been the past 16 years, then you should probably vote for Jan Norris. My father, Abell Longmore, once ran a don’t fix it.” While this is a catchy phrase, in my humble opinion, it does not apply to this year’s Treasurer’s race. After 16 years of the same management style and approach, I believe the office needs fresh leadership that will prevent it from falling further behind so it can begin to provide the types of services to our citizens that many other counties and governments already provide to theirs. Our citizens can seize the opportunity to instill this new leadership by electing Daniel H. Raley as our next Treasurer. Dan Raley is my father-in-law, and I am proud to be both his friend and a member of his family. But most of all, I am grateful for the hard work he has done as our Commissioner for the past 12 years because it has ensured that St. Mary’s County will continue to be a beautiful, safe and prosperous place for Katie and I to raise our three children. I urge you to vote for Dan Raley for County Treasurer on September 14, but most importantly I urge all Democrats to come to the polls to assert their rights to choose who will be the best Treasurer, not who some people think may have “earned it” by having been in the office previously. Christopher Longmore Great Mills MD some gambling relaxation. Dover has just implemented table games to their Dover Downs Casino and I love to play cards. The reason I am writing this is because in 2008, Maryland voters voted to change Maryland’s Constitution adding 15,000 video lottery terminals to Maryland’s way of generating funds in specified locations. Already behind with Delaware, West Virginia, and Pennsylvania already having casino style gambling, Maryland’s lawmakers with their political cowardice put the decision on the citizens of Maryland. Almost 2 years later, we still have no funds being generated but we still have fights of where the terminals will be placed. I’m not exactly sure why location is a question as this legislation was all about helping the dying horse racing industry. If that were the case, you would think that the terminals would be placed at the existing horse tracks, not some Mall that I’ve been seeing ads on TV. How can slot machines in a mall help a horse racing industry? Keeping people away from the tracks and in the malls would likely not help the horse racing industry at all but in fact hurt them. Not only will Maryland be behind with the machine type gambling, Maryland will be competing with other jurisdictions that people, like myself, would rather play the table games over the machines, where the odds are less predetermined and supposedly better. With these other jurisdictions having the table games, I and I’m sure others, will choose to drive a little further in hopes of keeping their money longer and hopefully adding to it. I would much rather keep my money in my own state however I want to enjoy the time whether I win or lose and not just feed some machine. So if the state should find the video lottery terminals alone aren’t bellying up what was anticipated because of these other jurisdictions having table games, will there have to be another constitutional amendment? Will the citizens have to vote on the addition of table games because of the political cowardice of the General Assembly? The Constitution is not a place for this type of legislative activity and should have never been there to start with. The Constitution is a document that describes the structure of the Government, the rights, responsibilities, and duties of the citizens and Governmental Institutions. Revenue generation is the duty of the General Assembly, not the citizens. Jimmy Hayden Leonardtown, MD Thank You For Candidate Forum Why Are We Still Putting Coverage I would like to extend my personal thanks filing deadline of July 6, 2010. All other candiPoisons Into Our Food At This as well as thanks on behalf of the League of dates were invited to meet and greet the public Women Voters of St. Mary’s County to the re- that evening prior to the question and answer Day And Age Of Good Health porters and staff of the County Times for the periods. LWV is a nonpartisan organization, excellent coverage of the Primary Forum held and we are always disappointed when some on Aug. 23. I am sure that notices announcing candidates choose to not accept our invitation Practices? the forum were a major factor in the standing to participate in forums or respond to questions room only audience in attendance. In election years, providing opportunities for the public to meet candidates and learn their positions is one of the primary goals of LWV. Forums and the online Voters Guide (www. smc.lwvmd.org ) take months of planning on the part of LWV members, all of whom volunteer their time. They also require input from the candidates. Invitations to speak at the Primary Forum were sent to all candidates in contested office races shortly after the candidate for the Voters Guide. LWVSMC will sponsor forums in October prior to the General Election; invitations to candidates will be sent as soon as primary election results are complete. We look forward to full participation by the candidates and more full houses of interested citizens. Virginia Stein, Publicity Chair League of Women Voters of St. Mary’s County Democrats Should Choose Norris September 14th is Primary Election Day in Maryland. If you can’t make it to the Polls on that date, there’s early voting at the Board of Elections Office in Leonardtown from September 3rd through September 9th, including Labor Day. Democrats have contested races for Governor, U.S. Senate, and Congress. The only contested local race for Democrats is for County Treasurer. JANNETTE (JAN) NORRIS, has 31 years of dedicated service in the St. Mary’s County Treasurer’s Office – the last 16 years as the Treasurer. As a practicing attorney for over 30 years, I have had many dealings with the Treasurer’s Office, and have seen Jan always provide efficient and courteous customer service. She still makes time to personally answer customer’s phone calls, and often goes the extra mile to help County citizens with their problems. She handles over 109 million of taxpayers’ dollars honestly and efficiently, so as to keep down the costs of running the office. The Treasurer’s Office is the only County department that I know of that has not increased their number of employees in 16 years. I would urge all Democrats to vote on September 14th for the most qualified, experienced, and knowledgeable person for the job of Treasurer - JANNETTE NORRIS. John S. Weiner Leonardtown, MD My concern is over the addition of arsenic in chicken feed. Yes, arsenic--which is also known as rat poison. This arsenic breaks down into a poison that spreads into our atmosphere, our land, and our water, as well as our chicken meat. Most of the chicken we eat everyday has been tested to show detectable levels of arsenic which cause horrible health problems, like cancers and neurological disorders in children. In addition, the poison is running off into the Chesapeake Bay from chicken waste, threatening our water and our fish. This issue really concerns me because my only income is Supplemental Security Income (SSI). My food allowance is only $109/ month, I am disabled, and have no way of earning more income. Therefore, I absolutely cannot afford to get sick. But because chicken is a main source of protein for the disabled, I fear my health is in jeopardy. Our health should be the reason, if no other, why arsenic needs to be banned from our food chain. The more toxins we pour into our food, sooner or later, the cost of medical care will be passed on to you--the taxpayer. Arsenic is a completely unnecessary practice that has been going on way too long. My ask to the people of St. Mary’s County is to support a state bill to ban arsenic from chicken feed! Thomas Dyson Lexington Park, MD 11 The County Times Thursday, September 9, 2010 CALIFORNIA MERCHANTS Come by & Visit Your Local Businesses & Shops! C A Brand new D with free internet, free hot breakfast B EvEry room Fridge/Microwave Flat Screen TV Meeting Rooms Walk to Restaurants Shopping • Night Life Per Diem Rates Available Fitness Center Business Center Laundry Facility wake up on the bright side® E (301) 862-2191 (301) 862-1846 A Bl vd Macarthur C Buck H ewi tt R d 235 22769 Three Notch Road • California, MD 20619 A 235 Three No tch Rd Lafern & Shirley Florist (301) 862-9109 E A D San Souci Plaza 22576 Mac Arthur Boulevard California, Maryland 20619 301-737-0500 A Family Practice Mon-Fri: 8 AM- 5 PM 301-737-4241 D B 237 BRETON MEDICAL CENTER SUPER CARE Breton Medical Center 308 San Souci Plaza, California, MD Ch anc ellors Run Rd 301-862-4100 Super Care: Mon-Fri: 8 AM- 8 PM Sat & Sun: 9 AM– 5 PM The County Times Thursday, September 9, 2010 12 13 Thursday, September 9, 2010 James Baker, 58 James Andrew Baker, 58, known to family and friends as “Andy Brown”, peacefully departed this life on September 2, 2010. James was born on December 7, 1951 in Budd’s Creek, MD, to Alice Pauline and the late Robert Q. Baker Sr. He accepted Christ in his life, was baptized, and became a member of St. Matthew’s Free Gospel Church of Christ, Leonardtown, MD on March 19, 2006. He was educated in the St. Mary’s County public school system where he graduated from Chopticon High School, Morganza, MD. Following graduation, James enlisted into the United States Army. Following his military service, James worked for the St. Mary’s County Government for 2 years. He then followed in his father’s footsteps, and began to work at the Indian Head Naval Ordinance Station in Indian Head, MD, where he worked for 34 years until he retired. James enjoyed being around his family and lending a helping hand when needed. He always had a witty remark for any situation (i.e., I’ll throw salt in your eyes or I’ll scratch your eyes out), this is an inside joke for the family. He was an usher and a member of the St. Matthew’s Men’s Choir. He enjoyed watching all sports and the cooking channel. James also was a DJ for many occasions such as, cookouts, weddings and different fundraisers. He enjoyed being with his companion, Felicia and the girls, this made him very happy. He leaves to cherish his loving memories, his beloved companion, Felicia Cutchember and three daughters: Patrice, Shawnese, Sherice ; two granddaughters Kaelani and Talia; mother, Alice Pauline; sisters: Theresa Maddox, Paulette, Agnes, Marie and Pamela, brothers: James (Dicky) Brown, Robert Jr, Lewis, and Charles; one brother-in-law, John Maddox; two sister-in-laws: Denise and Linda; host of nieces, nephews, aunts, uncles, cousins, other family and friends; three goddaughters: Ciera Young, Shaquan Bush, Shambre’ Young. Family will receive friends for James Life Celebration on Thursday, September 9, 2010 from 9:30 a.m. until time of Service at 11 a.m. in the Brinsfield-Echols Funeral Home, P.A., Charlotte Hall, MD with Bishop Daniel Jones officiating. Interment will follow in Charles Memorial Gardens, Leonardtown, MD Mary Dean, 86 The County Times. Arrangements by the Brinsfield Funeral Home, P.A., Leonardtown, MD. Andrew Goyco, 23 Andrew Joseph Goyco, 23 of Leonardtown, MD passed away from accidental causes on August 31, 2010 in Leonardtown, MD. Born January 14, 1987 in Philadelphia, PA, he is a graduate of Father Andrew White Elementary School and St. Mary’s Ryken High School, both in Leonardtown, MD. Andrew was awarded a Bachelor’s of Science Degree in Biology in 2010 from Temple University, Philadelphia, PA. Andrew enjoyed running, weight lifting, video games and cooking in his spare time and was a member of St. Aloysius Church in Leonardtown, MD. Andrew was a great brother and son and kept his family and all who knew him entertained with his quick wit. He is survived by his parents Ivan and Joan Goyco, his brother Alex and his sisters Caroline and Julia all of Leonardtown, MD. He is also survived by his maternal grandfather, Joseph Marano and his paternal grandmother Sylvia Goyco as well as aunts, uncles and cousins from Philadelphia, PA, Long Island, NY and Tampa, FL. Family received friends on Tuesday, September 7, 2010 in the Brinsfield Funeral Home, 22955 Hollywood Road, Leonardtown, MD 20650. Prayers were recited. A Mass of Christian Burial was celebrated on Wednesday, September 8, 2010 at St. Aloysius Catholic Church, 22800 Washington Street, Leonardtown, MD 20650. Interment followed in St. Denis’s Cemetery in Haverford, PA. In lieu of flowers, memorial contributions may be made to St. Aloysius Catholic Church, P.O. Box 310, Leonardtown, MD 20650 or Father Andrew White School, P.O. Box 1756, Leonardtown, MD 20650. Condolences to the family may be made at. Arrangements by the Brinsfield Funeral Home, P.A., Leonardtown, MD. Ernie Modlin, 89 Ernie Lee Modlin, 89, of California, MD died on August 29, 2010 at the Charlotte Hall Veterans Home in Charlotte Hall, Maryland. . Born January 7, 1921 in Jamesville, North Carolina, he was the son of the late Joseph Gray Modlin and Mittie E. Ange Modlin. He was married on March 6, 1966 and for 44 years was the loving husband of Juanita Lorraine Thompson Modlin. He is also survived by his sister, Annie May Williams. He was preceded in death by his siblings, Jesse, Elmer, Eddie W., Grady, Pauline, and Joseph A. Modlin. After graduating from Jamesville High School, and before enlisting in the U.S. Army, Ernie worked at the Naval Ship Yard in Norfolk, VA. While proudly serving in the Army as a Combat Engineer, Ernie was in five major battles, and campaigns, which included Normand, Northern France, Ardennes, Rhineland, and Central Europe and he served from October 19, 1942 to December 11, 1945. His decorations and citations: American Theater Campaign Metal, EAMET Campaign Metal, Good Conduct Medal and 5 bronze service stars. After being Honorably Discharged, Ernie coowned and operated a barbershop for 33 years in Lexington Park, Maryland before retiring in 1985. He was a life member of the V.F.W., The American Legion, The Elks, and the D.A.V. The family received friends on Thursday, September 2, 2010 in the Mattingley-Gardiner Funeral Home, Leonardtown, MD where a memorial service was held. Interment followed at the Modlin Family Cemetery, in Jamesville, NC. Contributions in memory of Ernie Lee Modlin can be made to the Lexington Park Caring for the Past Planning for the Future Brinsfield Funeral Homes & Crematory “A Life Celebration™ The County Times Thursday, September 9, 2010 14 Continued Rescue Squad, P.O. Box 339 Lexington Park, MD 20653 or Hospice of St. Mary’s, P.O. Box 625, Leonardtown, MD 20650. To send a condolence to the family please visit our website at. Arrangements provided by the Mattingley-Gardiner Funeral Home, P.A. Richard Russell, Sr., 85 Richard Ignatius “Dick” Russell, Sr., 85 of Leonardtown, MD died on August 31, 2010 at his residence of 63 years. Born November 18, 1924 in Morganza, MD, he was the son of the late William Lee and Kathleen Ann Abell Russell. He was born the fifth child out of eight. He attended both St. Joseph’s and Margaret Brent Schools. Dick graduated from Margaret Brent High School in 1943. He met the love of his life, the late Agnes Cecilia Russell in the late spring of 1944 and they were married at St. Aloysius Catholic Church in Leonardtown, MD on November 22, 1945. Their best man was Irving Russell and their maid of honor was Virginia Hurry. Agnes preceded Dick in death on July 14, 1985. He held a memorial Mass dedicated to her at St. Francis Xavier Catholic Church every year since her death as well as for his son David who was killed in Combat in March of 1969. Dick is survived by his children; Dickie (Karen), Bobby (Carole), Donald (Debbie), Linda Farrell (Jim), Agnes Monteith, Charles (Christine), Francis (Gisela) and Carolyn Weiler (Donnie) and Grandchildren; Georgia, Pam, David, Cynthia, Sandra, Nicole, Stephen, Kristie, Ryan, Paula, Ricky, Lewis, Sarah Jean, Brian, Keri, Tommy, Brandie, Crystal, Patrick, Kara, Karla, Charlotte, Sarah Jane and Michael as well as his 25 Great-Grandchildren. He is also survived by his siblings Dorothy Shavatt of Waldorf, MD, Mary Rosalyn “Rose” Hurry of Morganza, MD and James “Jim” Lambert Russell of Hughesville, MD. He is preceded in death by his children; David Allen Russell and Baby Benjamin Russell, his granddaughter Kelly Farrell, and siblings; William “Austin” Russell, Walter “Fidalis” Russell, Anne “Helene” Hoffman and Louis “Lee” Russell. He was known and loved by all as a family man, a faithful Catholic, a devoted community servant, and a dear friend. He has been an active member of the St. Francis Xavier Parish since he moved to his last residence in St. Clements Shores in 1947. He joined the Knights of Columbus in the same year. He has been in the Lions Club since 1973 serving as King Lion on three separate occasions. He remained active in all three until his death. He became the first baseball Manager at St. Clements Shores in 1956, first Rocking Chair Softball Manager of the local team in 1963 retiring from the team in 1970 and is a member of the Rocking Chair Hall of fame. He served as President of the Babe Ruth League while managing one of the other ‘A Friend of Many, Re-Elect Kenny!’ KENNY DEMENT Commissioner St. Mary’s County Honesty Vision Dedication Available Experience Reliability Considerate Listens Friends for Kenny Dement, Commissioner • By Authority: William L. Lyman, Treasurer divisions in the 1960’s. He also managed the Compton Raiders Young Men’s Softball team one year in the 70’s. He was the first President of the Chopticon Athletic Boosters in 1966. He was also the first President of the St. Clements Shore Comments Club. Dick received many awards and has been recognized for his community work on several occasions. One of the most significant was Maryland’s Most Beautiful People Volunteer award he received in October of 2004. He was nominated by the St. Mary’s County Commissioners and received his award in Annapolis, MD. Dick was born and raised on his family farm in Morganza, MD. He continued to farm in the Morganza area until he went to work as a Civil Servant from 1946 until 1979 at the Patuxent Naval Air Station, retiring as the Budget Officer. He continued to work as a government defense contractor for several years as a Financial Consultant and also worked part time for several years in real estate with B&B Realty. He always helped out on the Russell farms whether it was with tobacco, grain, f lowers or just driving the tractor. He was still going to the farm and helping in any way he could until his illness with pulmonary fibrosis no longer allowed. He still consulted after that with his nephews on a regular basis right up to the time of his death. Dick loved to travel and was able to see the world. He loved his family and loved to go up on the farm, the “Home Place” where he was born. Dick enjoyed spending time and working with his family, his fellow parishioners, his fellow club members, his hunting and fishing buddies. He loved to hunt and fish whenever he could. He never forgot a birthday and that included his brothers, sisters, parents, children, grandchildren and even most of the great-grandchildren as well as most of his nieces and nephews. He was an avid sports fan especially the Orioles and the Redskins and later the Ravens and the Nationals. When he found the time and if he wasn’t coaching or working as a community servant, he enjoyed watching family members play ball, especially his Grandson David. Dick died peacefully in his home after two years battle with pulmonary fibrosis. The family received friends on Thursday, September 2, 2010 in the St. Francis Xavier Catholic Church, Compton, MD where prayers were said and the Knights of Columbus will say the Rosary. A Mass of Christian Burial was celebrated on Friday, September 3, 2010 in St. Francis Xavier Catholic Church, Compton, MD with Fr. John Mattingly officiating. Interment followed in the church cemetery. Pallbearers were his surviving eight children. Honorary pallbearers were the members of the Leonardtown Lions Club. Contributions in memory of Dick can be made to the St. Francis Xavier Catholic Church, 21370 Newtowne Neck Road, Compton, MD 20627 and/or the Leonardtown Lions Club, P.O. Box 363, Leonardtown, 20650. Condolences may be left to the family at h.com. Arrangements provided by the Mattingley-Gardiner Funeral Home, P.A. Edward Wagner, 84 Edward Charles Wagner, 84 of Mechanicsville, MD died on August 31, 2010 at the Hospice House of St. Mary’s, Callaway, MD. Born August 2, 1926 in Baltimore, MD, he was the son of the late Edward Ambrose and Ethel E. Pocklington Wagner. He was the loving husband of Edna M. Wagner whom he married on March 6, 1949 in St. John’s Lutheran Church, Brooklyn, MD. He is also survived by his four children; Dan Wagner (Rhonda) of New Castle, PA, Diana Johnson of Mechanicsville, MD, Janet Wagner of Brunswick, MD and Nancy Curry of Hudson, FL. He is also survived by his six Grandchildren Lori Quade, Charlena Rutherford, Daniel Curry, Melissa Curry, Dana Wagner and Lisa Wagner; five Great-Grandchildren David Rutherford, Rhodie Quade, Chrissy Rutherford, Amanda Rutherford, and Mason Quade. Edward was preceded in death by his Granddaughter Kimberly Johnson. Edward joined the United States Army in December of 1944 and was stationed in Fort Meade, MD. He separated from the United States Army in February of 1946. He worked for Amoco Oil (BP) as a Refinery Supervisor for 37 years and retired in 1977. Edward was a member and past Commander of the American Legion Post 276, Severn, MD, Haurundale Little League, Glen Burnie, MD and the Rebels Athletic Club, Glen Burnie, MD. The family received friends on Friday, September 3, 2010 in the MattingleyGardiner Funeral Home, Leonardtown, MD. A Funeral Service was held on Saturday, September 4, 2010 in the MattingleyGardiner Funeral Home, Leonardtown, MD with Fr. John Ball officiating. Interment followed at Charles Memorial Gardens, Leonardtown, MD. Pallbearers were Kevin Askew, Gary Davis, Rhodie Quade, David Rutherford, Philip R. Quade III, and Steven Dean. Contributions in memory of Edward may be made to the Hospice House of St. Mary’s, P.O. Box 625, Leonardtown, MD 20650. Condolences may be left to the family at h.com. Arrangements provided by the MattingleyGardiner Funeral Home, P.A. Jack Witten, 92 Jack Francis Witten, 92 of Great Mills, MD passed away on September 3, 2010 at St. Mary’s Hospital. Arrangements are pending at this time. For information please contact the Brinsfield Funeral Home, P.A. at 301-475-5588. To place a memorial please call 301-373-4125 15 Thursday, September 9, 2010 The County Times Hollywood Graphics And Screen Printing ng i r e f Of W O N • Business T-Shirts • Custom T-Shirts • Banners • Stickers • Graphics/Logos • Vehicle Lettering • ATV & MX Decals 301-769-1177 hgx@hollywoodgrafx.com m o c . x f a r g d woo y l l o h . www ASK OUR FRIENDLY PHARMACIST FOR ALL OF THE DETAILS! Wildewood Shopping Center California, MD 20619 The Shops at Breton Bay Leonardtown, MD 20650 301-866-5702 301-997-1828 Route 246 & Great Mills Rd. Route 5 & Mohawk Drive Lexington Park, MD 20653 Charlotte Hall, MD 20622 Route 245 Hollywood, MD 20636 301-862-7702 301-884-5636 301-475-2531 In The Know Education The County Times The term "white chocolate" is a misnomer. Under Fedaral Standards of Identity, real chocolate must contain chocolate liquor. "White" chocolate contains no chocolate liquor. G. Mills NJROTC Hosting 9/11 Event By Sarah Miller Staff Writer The Great Mills Naval Junior Reserve Officer Training Corps (NJROTC) will be hosting 11 Laps to Remember on Saturday, Sept. 11 form 2-4 p.m. at the Great Mills High School track. The goal of the walk is “to honor and support the first responders,” said Captain J.P. Kelly, senior naval science instructor at Great Mills High School. All proceeds from the event will be donated to the Bay District Fire and Rescue Squads. Businesses that make a donation of $100 or more will be allowed to put a banner on the track fence during the event. Those who haven’t yet signed up for the walk can do so the morning of the walk itself between 1 and 2 p.m.. The fee for registering is $5 per person or $20 for a family of four or more. The NJROTC is “designed to be a citizenship and leadership program” and the Great Mills NJROTC is the biggest in the tri-county area with 150 students enrolled, according to Kelly. This is the first year the Great Mills NJROTC has hosted the 11 Laps to Remember event, but Kelly foresees it becoming an annual event. Last year, the event was run by Tamarah Dishman, a teacher at Spring Ridge Middle School. But this year, “we [the Great Mills NJROTC] assumed the program,” Kelly said. The original idea was a brainchild of Kathy Norton, the current principal at Park Hall Elementary School. Dishman was pleased to see the NJROTC take control of the 11 Laps to Remember and said there is “no organization more appropriate” to be in charge of the event. “We’ve been in this together,” said Jacob Stansfield, a senior at Great Mills High School and the Cadet Commanding Officer. Thursday, September 9, 2010 According to Kelly, there are plans to continue the 11 Laps to Remember next year in conjunction with the Leonardtown and Chopticon branches of the ROTC, the Army and the Air Force respectively. The Great Mills NJROTC drill team and color guard will also be present at the event. The drill team and color guard travel all over Maryland and were even invited to participate in the national Memorial Day parade in Washington, DC last year, Kelly said. There will also be miniature representations of the twin towers on the track with the names attached of all the people who died on Sept. 11, 2001. For more information about the walk or making a donation, contact Kelly at 301-863-2001 ext 144. sarahmiller@countytimes.net 16 un Fact Fall Cherrydale Fundraisers Kicking Off By Sarah Miller Staff Writer The Cherrydale Fall Fundraiser was recently kicked off at Leonardtown Elementary School. Many of the schools in the county use the Cherrydale fundraiser, according to Kelly Hall, director of elementary schools with St Mary’s County Public Schools. “Cherrydale is a very easy company to work with,” Hall said. Through the Cherrydale fundraisers, students sell things such as wrapping paper and gourmet foods to raise money for things such as after-school programs. “The funds raised by the students are to be spent on the students,” said Carolyn Nelson, a retired member of fiscal services for St. Mary’s County Public Schools. Some of the money is used to update equipment, but all of it is kept within the school. “We really try to work with the schools and tell them not to do too many [Fundraisers],” Hall said. The schools are encouraged to keep the economics of the surrounding community in mind and only do a couple of big fundraisers per year. It is up to each school as to when the fundraisers are, but they mostly have their fundraisers in the fall, Hall said. The Parent Teacher Association (PTA) and the Parent Teacher Organization (PTO) also have a meeting with the principals of the elementary schools every year to set a calendar to the PTA/PTO fundraisers don’t coincide with the school fundraisers and they have a reasonable amount of time between fundraisers. sarahmiller@countytimes.net Photo by Sarah Miller Seniors Jacob Stansfield, Cadet Commanding Officer and Tiffany Moreira, Cadet Executive Officer staple lists to replicas of the twin towers. The best of Flexsteel is now on sale during our biannual event! We’re passing factory authorized pricing on to you! t e p r a C Abbey by s ’ e l y Do Abbey Carpet 20041 Pt. Lookout Rd. Great Mills, MD 20634 301-994-3650 Abbey Carpet 86 Solomons Island Rd. Prince Frederick, MD 20678 410-414-5171 Cakewalk Chair & Ottoman in leather Available in 16 special order colors! Factory authorized pricing for a limited time only. September 1 thru 20. 17 The County Times Thursday, September 9, 2010 Southern Maryland Association of REALTORS® Public Awareness Campaign Mission Statement The mission of the Southern Maryland Association of REALTORS® is to maintain a financially viable association offering support, services and training for its members; to provide community outreach; to foster a proactive relationship with local and state legislative leaders and to be the leading advocate of the real estate industry, private property rights and the issues that most affect the members’ ability to serve the public with competency, integrity, and professionalism. PAX RIVER REALTY SMAR does not provide opinion or endorsement of individual REALTOR® members and brokerages. We do however thank the SMAR members surrounding this ad for their financial support of this Public Awareness message Irene Parrish B. Realty Irene Parrish Broker 22188 Three Notch Rd. Suite A Lexington Park, MD 20653 Toll Free: 866-726-0008 Office: 301-862-0008 Fax: 301-862-0009 301-863-7002 office 301-481-7244 Lexington Park, MD 20653 cell ParrishI@IBP-Pro_offices.com For All Your Real Estate Needs. Addie McBride Cell: 301-481-6767 Home: 301-737-1669 addiemcbride@verizon.net Helping Good People Find Good Homes. , Inc. Franzen Realtors 22316 Three Notch Rd. Lexington Park, MD 20653 Office: 1-800-848-6092 • Office: 301-862-2222 Fax Office: 301-862-1060 Kim Hills Licensed Broker in MD & VA AssociateBroker RE/MAX 100 28105 Three Notch Road, Mechanicsville, MD 20659 Toll Free: (888)355-0010 800) 314-8235 Office (Toll Free) (301) 672-4040 (Cell Phone) Email: kimhills@mris.com A REALTOR CAN SELL YOUR HOME FASTER AND FOR MORE THAN YOU COULD YOURSELF. ® ERIE INSURANCE GROUP LEAVING YOU MORE TIME TO ENJOY YOUR LIFE. Your Neighborhood Expert! If you’re one of the 5.7 million people who list their home for sale this year, the National Association of REALTORS wants you ® to know that when it comes to selling a home, you’re better off using a REALTOR®. Someone who can get the job done in half Office: (301)392-0010 Office: (410)535-5585 Office Phone: (301)932-7800 FIRST CHOICE REALTY 8340 Old Leonardtown Rd • Hughesville, MD 20637 the time, and can sell it for more than if you sold it on your own. That’s because REALTORS® are experts—they have extensive Rita Minion • Chris Minion Your Southern Maryland Real Estate Connection Patuxent Plaza - Solomons experience staging the home, showing it and attracting qualified buyers to view it. Work with a REALTOR®, a member of the National Association of REALTORS®, they can explain options in your area that best fit your situation. To learn more, visit. Based on NAR Market Forecast. Home office: 410-326-9198 mobile: 410-610-2591 office: 410-326-3133 ext. 214 fax: 410-394-0251 ritaminion@mris.com Would you like this spot? Give us A CAll 301-373-4125 EVERY MARKET’S DIFFERENT, CALL A REALTOR ® TODAY. Southern Maryland Association of REALTORS® ©2010 National Association of REALTORS®. James Moran Branch Manager Hughesville, MD 301-870-2323 ERIE ERIE INSURANCE INSURANCE GROUP GROUP BURRIS’ OLDE TOWNE INSURANCE DANIEL W. BURRIS, CIC, PROPRIETOR Office/Cell: 301-752-6876 BURRIS’ BURRIS’OLDE OLDETOWNE TOWNEINSURANCE INSURANCE DANIEL DANIELW. W.BURRIS, BURRIS,CIC, CIC,PROPRIETOR PROPRIETOR Auto Auto• •Home Home• •Business Business• •Life Life Connie Fitzgerald 301-672-1634 or 800-493-4545 23076 Three Notch Rd, Suite 100 Three Notch Rd, California MD 20619 Each Office Independently Owned and Operated Your St. Mary’s County Real Estate Expert Hollie D. Kessler REALTOR®, ABR®, CDPE®, GREEN RE/MAX 100 23076 Three Notch Road California, Md 20619 Providing Comprehensive Real Estate Services to Home Buyers and Sellers Ron Wimmer Century 21 New Millennium ron.wimmer@c21nm.com Work: 301-737-3636 Mobile: 240-434-1471 Fax: 301-862-2179 Office: 301.863.5355 Cell: 240.925.2718 Fax: 410.505.9368 22720 22720WASHINGTON WASHINGTONSTREET STREET• •P.O. P.O.BOX BOX707 707 St. Mary’s 1st GREEN Designee LEONARDTOWN, LEONARDTOWN,MD MD20650 20650 (301) (301)475-3151 475-3151• Toll • TollFree: Free:(800) (800)872-8010 872-8010• Fax: • Fax:(301) (301)475-9029 475-9029 danburris@danburris.com• •danburris.com danburris.com 24404 Three Notch Road, Suite 102, Hollywood, MD 20636 danburris@danburris.com holliekessler@remax.net The County Times Thursday, September 9, 2010 18 19 The County Times Thursday, September 9, 2010 Cover Cover Local Sailors Quietly Come and Go From War Zones On The On The By Sean Rice Staff Writer spouses and families they left behind. The end result was a support system that became a model for the Navy and spread across the country. Glen Ives, with the help of Master Chief Jeff Snowden, set up support systems for the business end of IA deployments, and started holding quarterly IA Homecoming celebrations, which still continue. The next IA Homecoming is tonight on base, and Lemmon will be one of those recognized. Concurrently, Barbara Ives volunteered to spearhead the creation of the IA Support Group, which hosted events for IA spouses and families. “At one time we had near 400 families in the group, the largest IA spouse support group in the nation,” Barbara Ives said. The program is still in operation under the Fleet and Family Support Center. “We really grew that into something that was really special. We did everything we could to make it a very worthwhile,” Geln Ives told The County Times. “That probably turned out to be one of the most successful stories we had … one of the best things we did while we were there.” Pax River personnel now have an Individual Deployment Support Specialist (IDSS) to help them through what may be a tough time for some families. “Families have a lot of questions, and we are there to form a relationship with them much like a friend would to make sure the needs of the family are met,” said Alexandria Hoffman, IDSS, at Pax River. U.S. Navy Capt. John Lemmon, of California, returned home two weeks ago after spending eight months in Djibouti, Africa, on an Individual Augmentee (IA) assignment supporting the global war on terror. There were no cheering crowds, no banners or f lags waiving (except for the ones held by his wife and children), because Lemmon came back into Dulles Airport the same way he left in January – alone. IA assignments are special assignments in which military personnel are deployed individually to a needed area on the globe, which is a major departure from the image that comes to mind when a aircraft carrier full of sailors or a squadron of pilots gets deployed or returns to base. “A lot of people, unless you’re military, you don’t understand what an IA is,” said Julie Lemmon, John’s wife. “In the past, usually when you’re Navy you deploy with a group, and these IAs, they are going by themselves.” In January, John finished up his command tour as commanding officer of the VX-20 squadron at Patuxent River Naval Air Station. VX-20 is one of the f light test squadrons on base. His new assignment at Pax River is with NAVAIR program office PMA-231, where he will be a co-lead for the E-2D, a carrier-based airborne early warning aircraft. When John got the call to go on an IA mission, its was his first IA assignment in his 22-year career with the Navy. Prior to this assignment, John hadn’t been deployed in nearly 10 years, back when his children – aged 15, 13 12 and 10 – were much younger. “This was one of those things that came up.” John said. “I was the commander of a task group out there, and we were doing operations to support the global war on terror, and other contingency operations.” The deployment wasn’t too surprising, Julie said, because it has been so long since John last went overseas. “It’s so different because in the past when he’s come back from deployment it’s a big deal.” Julie said. “We’ve lived in Norfolk and San Diego, and the whole Julie and John Lemmon please contact the county times at win 301-373-4125 1 $ four $25 winners 8 chances to win. and get 00 on Any Meal off EXPIRES 09/24/10 21591 Great Mills Road Lexington Park, MD 20653 $100 in cash prizes by using these coupons! grooming or boarding and no limit on stay use all 8 coupons coupon 301-866-0850 name: address: phone 20815 Callaway Village Way Callaway, Md 20620 301-994-9439 #: Customer Must Present Original Coupon. Purchase Required. No Cash Back coupon 301.475.2142 43450 St. Andrews Rd. Leonardtown 301.274.4440 8275 Leonardtown Rd. Hugesville 301.855.8308 9214 Boyd’sTurn Rd. Owings name: address: MARTIn’S AuTo TEcH Automotive And Transmission Repair • 301-373-2266 10 $ #: coupon coupon 00 oFF GRooMInG & BoARDInG phone “Because I have such a good support system here with my neighborhood and other military wives, I feel very blessed,” Julie said. The Lemmons are fortunate to have that extended network to help them out, which has been built up over the last 16 years, when the family have moved and then returned to St. Mary’s County three separate times. Julie said she made sure all her children’s teachers know the situation, their coaches and neighbors. “It’s amazing once you tell them your situation,” Julie said. “Our parish priest, Father Ray at St. Johns, made a speJohn and Julie Lemmon at Dulles Airport on Aug. 22 when John returned from his cial point to tell the kids ‘I’m here for you if you need me.’” But not all Navy spouses are as blessed with a homeIA deployment to Africa. grown support network. “For some of these younger Navy wives who just moved town knows that there’s a battle group coming back, here and their husbands are being sent somewhere, they have no one, and that thousands and thousands of men and women they have no support system,” Julie said. are returning from deployment. In this case, it’s just “When most folks come to Pax River, they think they are on shore one guy coming into Dulles Airport and it’s very dif- duty,” said Capt. Barbara Ives (USN Ret.), wife of former Pax River ferent from the homecoming we’re used to.” Commanding Officer Capt. Glen Ives. “And once you’re off sea duty Julie and the kids put up signs on Wildewood your thinking ‘OK I’m on shore duty, time to regroup with my family, Parkway saying “Welcome home Dad.” it’s time to reconnect with my children … and then to go IA it destroys “Unless you know me or you know the situation, that plan, it really does cause a lot of strife.” no one knows that these guys have even come and Until about 2005, when IA assignments started to pick up expogone,” Julie said. nentially: “We had never really figured out, or needed to figure out The Lemmons have no family locally, but they do how to support them individually.” Glen Ives said. have an extended network of friends, neighbors and Glen and Barbara at the time made it one of their top priorities to other military families to lean on like family. “It has set up a support system for personnel heading out as an IA and for the to be when you’re not around family.” no limit on stay EXPIRES 09/24/10 Special Lube,oil,Filter/ Rotate & Balance Tires -complete Safety Inspection/ Top off All Fluids (excludes diesels/ synthetic oils) $44 99 expires 09/24/10 23867 Mervell Dean Rd. • Hollywood, MD name: address: phone #: coupon 29 $ 40845 Merchants Lane • Leonardtown, MD 20650-3771 • (301) 475-8838 25 99 oil change, Filter, Tire Rotation framing order % entire or home decor Up to 5 quarts of oil. Does not include diesel or synthetic oil. Expires 09/24/2010 off EXPIRES 09/30/10. Not valid on any previous purchases. SUMMER HOURS: Mon-Fri 10-5 • Saturday: 10-2 name: phone #: address: John Lemmon name: address: phone #: Remember to fill out your information on the coupon so you can be entered for a chance to win $25! The County Times Thursday, September 9, 2010 20 2010 Taste of St. Mary’s Sunday, September 19th • 12:00 ~ 5:00 PM Family Event • Free Admission • Free Entertainment Cakes for Weddings and Special Occasions 301-481-9901 anita@anitasweddingcakes.com 22330-A Chancellors Run Rd • Great Mills, MD 20634 Anita Kriner, Owner Country French Dining in a Casual Atmosphere Sample entrĂŠe items, desserts and appetizers from local restaurants and caterers serving St. Mary’s County and Southern MD Food tickets are $1 each. Washington Street on the square in Leonardtown, MD On the square in historic Leonardtown Classy entertainment, Prix-Fixe Menu & more Reservations Recommended 301-997-0500 ERIE INSURANCE GROUP WHERE SOMETHING GOOD HAPPENS EVERY DAY! BURRIS’ OLDE TOWNE INSURANCE DANIEL W. BURRIS, CIC, PROPRIETOR MONDAY - FRIDAY 9:30 TO 7 SATURDAY 9:30 TO 5 301-475-1630 22720 WASHINGTON STREET • P.O. BOX 707 LEONARDTOWN, MD 20650 41675 Park Avenue, Leonardtown (301) 475-3151 • Toll Free: (800) 872-8010 • Fax: (301) 475-9029 danburris@danburris.com • danburris.com Personalized Therapy of St. Mary’s & Calvert Partnered for All of Your Catering and Event Needs! Quality Street and the JTD Event Center will provide full service catering services for you and your place of business. • Drop-off breakfast, lunch & platters • Full event services at JT Daugherty center • Weddings and Formal celebrations • Career fairs, large meetings and conferences Please Contact Cherie Banner at: cherie@jtdevents.com 301-863-9345 21 Thursday, September 9, 2010 The County Times ewsmakers Locals Host 2nd Annual Bar Crawl to Help Friend Fight Cancer Durkin’s Realty, P.C. 301-737-1133 • 1-800-638-4701• 301-994-1632 21945 Three Notch Rd. #104 • Lexington Park, MD 20653 Visit our Branch office: 20259 Point Lookout Rd. • Great Mills, MD 20634 Outstanding Commercial Investment Lovely Rambler in Private Location By Andrea Shiell Staff Writer Locals from both sides of the Thomas Johnson Bridge will be adding a cause to their September 11 plans as they host the 2nd Annual Solomons Island Bar Crawl, sponsored by the Hurricane Alley Alumni Association, from 5:30 to 9:30 p.m., this year raising money for their friend PJ Aldridge, who has been battling Stage IV lung cancer. Jodi Aldridge, 38, who is married to PJ’s cousin Lewie, said she had known PJ for several years before he was diagnosed in February, 2010, and the news came as a shock to the family, who had helped host a bar crawl on Solomons Island for a similar cause this time last year. “My husband owned a bar called Hurricane Alley on Solomons Island … and after they closed, in the last year or so, people had been saying ‘we should all get together and have a Hurricane Alley reunion, it would be so much fun’ … and at the same time, last year would have been his 25th high school reunion, and nobody had planned a reunion.” That’s when the Aldridge’s plan for a bar crawl came into being, said Jodi, going on to explain that last year’s crawl had covered not only a reunion function with proceeds going to charity, but served also as a last boost to local businesses before their normal season ended. “We both have been here a really long time, and we also know too that because of the economy that people are really struggling, especially businesses … so we made it the last weekend the Tiki Bar was open, the reason being that it’s right before the off-season, so we figured it would be a really great way to help some of the local businesses.” Jodi said their group sold about $100 tshirts for last year’s bar crawl, which included both walking non-drinkers and crawling drinkers side by side, and PJ had marched up and down Solomons Island without showing any signs of illness. The crawl raised $575 for the American Cancer Society, but in what Lewie Aldridge described as an “ironic twist” of fate, PJ was diagnosed just months later. Vera Taylor, a long-time friend of PJ’s, Home has been completely remodeled and is ready to move in. New roof, deck, appliances, flooring, lighting, shows like a new home. Nice .65 Acre lot in quiet country setting. SM7417107. $195,000. Call Donna Knott. Located at corner of Point Lookout & Flat Iron Road, great income producing property, 2,700 sq ft building, with three units, separate heating/ cooling, all well maintained. Under lease as retail and office space, tenants pay utilities. 22 parking spaces, lighted sign. .40 Acre lot zoned CMX. SM7398441. $499,000. Call William Durkin. said that once PJ had been diagnosed, it didn’t take long for him to start thinking about cancer research and how he might help raise awareness, and Vera offered to help him research what organizations were best to donate to. “I was appalled at how little money goes to lung cancer research,” she said. “It’s the number one cancer diagnosed in the United States, and around the world, but it gets the least amount of funding.” The PJ Aldridge Foundation will be putting as much as they can into the September 11th fundraiser, and they are also sponsoring National PJ Week, October 3-10, during which donations will go to PJ’s favorite research organizations (including the National Lung Cancer Partnership and the University of Maryland), all feeding into the goal of raising $1 million. “The goal really is to raise a million dollars, and when you’re dealing with that kind of money you need to be an actual foundation and not just somebody out there collecting cash,” said Jodi, explaining that a portion of the proceeds from this year’s event will also go to local chapters of the American Cancer Society. The Foundation has been sprucing up its webpage () and collecting material to help friends and family follow PJ’s progress. “PJ is loved by many in St. Mary’s County as well as Ocean City, so we’re putting up the website so people can see how he’s doing,” said Vera. Call Durkin’s Today for Available Rentals & Building Lots “STEP UP TO SERVICE” On September 18th, 2010 at Father Andrew White School in Leonardtown, Maryland at 9:00 AM, the Society of St. Vincent de Paul will hold its Annual Nationwide Friends of the Poor® Walk (rain or shine) We will celebrate service to the poor, and encourage kindhearted Americans all across the country to become Friends of the Poor, too. Pledges made on behalf of registered walkers in a given community will benefit those most in need in that same community. Come join us for live music, complimentary post walk brunch and face painting as well as door prizes. The Health Connections staff will be available to do blood pressure checks. mo For re information pl Please register at. Same day registration starts at 7:30 am. eas ec a ct ont Patty ng Bela The 2nd Annual Solomons Island Bar Crawl will start at the Next Door Lounge and then move on to Stony’s Kingfishers, Catamarans, Solomon’s Pier and Calypso Bay Raw Bar, ending at the Tiki Bar by night’s end. Registration starts at 5 p.m. at the Next Door Lounge, with the walk beginning at 5:30. The cost for registration and a t-shirt is $25, and participants will be expected to pay for their own drinks. For more information on the PJ Aldridge FounPhotos by Jamie Koslow dation, contact Lewie Aldridge From left is Will Esham, Craig Casey, Rob Taylor, Pj Aldridge, III at lewiea@verison.net, or Buddy Trala, Blaine Champlin and Rico Liberto. call 301-481-5289. 68+ Acres – Villa Road Beautiful property just past St. Mary’s College with over 1000 feet of frontage on Rt 5 & Villa Road. 12 approved perc sites, very scenic location. Priced to Sell $680,000. er a or v t 301-904-7990 isit oor.com kforthep l a w . www walk a mile in my shoes Community The County Times Thursday, September 9, 2010 RiverFest is Sept 25 Celebrate the St. Mary’s River with kayaking, song, entertainment, and educational exhibits at RiverFest 2010 on Saturday, Sept. 25 at Historic St. Mary’s City. Festivities will take place from 10 a.m. until 5 p.m. and all activities are free. Discover what you can do in your own backyard to keep our waterways and shoreline healthy. Local vendors will be on hand to discuss solar energy, sustainability, rain barrels and rain gardens. Take home a copy of the 40-page home conservation guide available free at RiverFest. Join Senator Bernie Fowler for the annual River Wade-In, an informal check of water quality, at 2 p.m. See how deep you can go before you lose sight of your feet. Have a close encounter with some of the winged, finned, and furry characters you might meet in your neighborhood at birds of prey and touch tanks exhibits. Mutts Gone Nuts, a madcap variety show featuring amazing rescued dogs, will perform at 1 and 3. Stroll through outdoor mini-galleries, where regional wildlife artists will display their work, or paint a pumpkin and create your own work of art. Become a work of art by having your face painted or watch a balloon artist twist and turn a latex and air sculpture. Relax at water’s edge and enjoy regional talent including David and Joe Norris b Bo by to Pho Bob Jones, Maryland Depart of Natural Resources naturalist and interpreter formerly Lew is at Point Lookout State Park. Bernie Fowler leads the annual “wade in” HSMC Photo performing original tunes inspired by our land, waters, and history, Southern Maryland Traditional Music and Dance, and duet Indian Summer. At 4 p.m., Hot Jazz of D.C. will wrap-up the day with manouche gypsy jazz and swing. The living history exhibits, including the tall ship Maryland Dove, and the St. John’s Site Museum at Historic St. Mary’s City will be open. Vendors will offer food and beverage for sale throughout the day. This event is sponsored by the St. Mary’s River Watershed Association and Historic St. Mary’s City, with support from The Boeing Company, St. Mary’s County Arts Council, Maryland State Arts Council, and more than 30 local businesses. For more information about RiverFest visit or or call 301-862-3517 or 800-SMC-1634. 100 Women Walking to Good Health By Sarah Miller Staff Writer Tuesday saw the beginning of 100 Women Walking Their Way to Good Health, a program at Chancellor’s Run Regional Park initiated by Agnes Price, an administrative assistant with the Department of the Navy. “My goal is to have over 100 healthy women walking the county,” Price said. According to her, walking can have several health benefits, including the reduction of the risk of medical conditions such as high blood pressure and heart disease, a reduced risk of depression and the ability to sleep better. People who exercise on a regular basis also feel better in general, Price said. Price said she came up with the idea for 100 Women a year ago, but she put it aside until recently. “We as women have a tendency to take care of our husbands, children, grandchildren, and whomever, but we do not take care of ourselves,” she said. Ella Sommerville, a participant at Tuesday’s walk, said she supported Price’s venture. “I think it’s very nice. I think it’s something we should be able to do health wise,” she said. She also said it was good from a fellowship point of view because of all the different people the women who get the chance to meet. As of right now, there are over 100 women signed up to walk the Chancellor’s Run Park every evening beginning Tuesday. “I am amazed at how many women responded to this request,” Price said. There are even 12 girls between the ages of 6 and 12 signed up to walk. “I want to grab them at an early age, and teach them that they should start taking care of their body and health at an early age. What they do now, can affect them for the rest of their lives,” Price said. “This is not a one-time event,” Price said. She hopes women meet every day at the track to walk together and be each other’s encouragement and support. Participant Rhonda Curtis plans on coming out four days a week to walk. “My goal is to get healthy,” she said. A total of 73 women came to the walk Tuesday night. “Everybody just had a great time,” Price said. She looks forward to walking with other women every night and aid she’s gotten several e-mails from other women expressing the same sentiment. sarahmiller@countytimes.net 22 L ibrary Items • Open House scheduled for Lexington Park’s new, improved children’s area The public is invited to the Grand Transformation Open House to showcase the new, improved children’s area of the Lexington Park Library on Sept. 21 from 9 a.m. to 8 p.m. Remarks by Library Board President Alan Dillingham, Senator Roy P. Dyson and Delegate John H. Bohanan will be given at 9:30 a.m. Two of the highlights of the new area include the addition of Active Learning Centers and the creation of a special area for children in third through sixth grades. • Teens and adults can participate in statewide community read Warren St. John’s book, “Outcasts United,” this year’s selection for the One Maryland One Book statewide community reading project, is being read across the state. Book discussions are scheduled at each branch with the first one being held at Lexington Park on Sept. 15 at 6 p.m. Leonardtown and Charlotte Hall’s will be in Oct. Teens across the state are encouraged to read “Home of the Brave” by Katherine Applegate which features similar themes to “Outcasts United”. A teen chat to discuss this book will be held at Charlotte Hall on Sept. 13 at 5 p.m. and at Lexington Park on Oct. 18. • Workshop planned for home schooled families Students who are home schooled and their parents are invited to attend a workshop to learn more about the resources and services the library offers. The workshops will be held at Leonardtown and Lexington Park on Sept. 17 at 2 p.m. and at Charlotte Hall on Sept. 20 at 10 a.m. Registration is requested. • Robotics team demonstrates robots The SSI Robotics Team will demonstrate their robots including a World-Championship winning bot that shoots wiffle balls at a special program at the Leonardtown Library on Sept. 18. Those attending will have the opportunity to drive the robots and learn about robotics competitions. This free program will begin at 2 p.m. • Genealogical Society to conduct basic classes St. Mary’s County Genealogical Society will conduct the first of three basic genealogy classes on Sept. 22 at 6:30 p.m. at the Leonardtown Library. The class will cover getting started researching family history. Registration is required. 23 Thursday, September 9, 2010 Thursday, September 9 • Mega Yard Sale Living Word Community Church (39371 Harpers Corner Road, Mechanicsville)-8 a.m. If you have items you want to donate the people at Living World Community Church can arrange to have it picked up. They will accept any electronics, clothing, sporting equipment, electronics or items of a similar nature so long as they are still usable. The Girls impact will be selling baked goods and the Royal Rangers and Honorbound Men will be selling lunch foods. For more information contact Pastor Ed at 301-884-0167 • Blood Drive Immaculate Conception Church Hall (28297 Old Village Rd., Mechanicsville)-3:30 p.m. Life Scout John Hildebrand of Mechanicsville Boy Scout Troop 1782 and the American Red Cross will sponsor a blood drive at Immaculate Conception Church. Walk-ins are welcome appointments are encouraged to keep the wait time low. To schedule an appointment or for more information, call 301884-4248 or email hildetpj@verizon.net. • Volunteer Awareness Fair Southern Maryland Higher Education Center (44219 Airport Road, California)-6 p.m. The Volunteer Awareness Fair will be hosted by The Young Professionals Initiative of St. Mary’s County and is an opportunity to meet with various organizations from throughout St. Mary’s County that are looking for volunteers. Organizations participating in the event include FLOW Mentoring, Christmas in April, Big Brothers Big Sisters of Southern Maryland, Hospice of St. Mary’s, Southern Maryland Animal Welfare League (SMAWL), Leonardtown Volunteer Rescue Squad, The Friends of Myrtle Point Park, St. Mary’s County, MD League of Women Voters, Potomac River Association, and more. For more information, contact Amanda Ellington at programs@ypi-smc.org or 443-838-6429. • Anti-Bullying Presentation Leonardtown High School (23995 Point Lookout Road, Leonardtown)-6 p.m. Jodie Blanco, author of the book “Please Stop Laughing at Me” and anti-bullying expert, will be giving a presentation at Leonardtown High School Thursday evening. For more information, contact Mr. Michael Wyant, SMCPS director of safety and security, at 301-475-4256, ext.188. Friday, September 10 • 3rd Annual Leonardtown Wharf RegattaHappy Hour and Skipper’s Meeting Fitzie’s Irish Pub (21540 Joe Hazel Road, The County Times Leonardtown)-6 p.m. There will be a happy hour and skippers meeting at Fitzie’s Irish Pub with a cash bar. The captain’s briefing will begin at 7 p.m. The $25 for entries after Sept. 6. All proceeds from this race go to the St Mary’s Ryken and Leonardtown High School Sailing Teams. For more information, contact the Barnacle Cup Sailors Robert “Buzz” Ballard at buzz. ballard@gmail.com, call 240-298-1211 or visit. The event is open to all racers and the general public. • 11 Laps to Remember Chopticon High School Track/Football Field (25390 Colton Point Road, Morganza)-3:30 The Air Force JROTC at Chopticon High School will be hosting an 11 Laps to Remember event Friday evening in honor of the events of September 11. People will walk or run the track at the names of those who dies will be read off. The AFJROTC Color Guard will also be there and the National Anthem will be sung by Chopticon’s Choral Group, “Infinity.” Saturday, September 11 • Free Grocery Give Away Calvert County Baptist Church (2190 Solomons Island Road South, Prince Frederick)-10 a.m. One hundred bags of groceries will be given away tot he first hundred people to come between 10 a.m. and 1 p.m. First come, first served. For more information, call 410-535-6155. • 3rd Annual Leonardtown Wharf RegattaRaces Leonardtown Warf (Washington St, Leonardtown)-12 p.m. Races begin at noon. • 2010 Hogs and Heroes Fundraiser Old Glory Harley Davidson (11800 Laurel Bowie Road, Laurel) Poker Run Registration-9:30 a.m. Bike/Car Show Registration-11:30 p.m. This fundraiser is to collect money for the children of police officers, firefighters, first responders and active duty military members who were killed in the line of duty. There will be special appearances by The Blues Keepers Band, Citizens Band Radio and The Other II. Sunday, September 12 • All–You-Can-Eat Breakfast Rescue Squad Building (Route 235, Hollywood)-7:30 a.m. The menu will include: sausage gravy and biscuits, sausage links, bacon, scrambled eggs, fried potatoes, escalloped apples, assorted juices, coffee, tea and hot chocolate. The breakfast is free for children under the age of 5, $4 for children between the ages of 5-12 and $8 for adults. • Dinner Cruise Calvert Marine Museum (14200 Solomons Island Road, Solomons)-5 p.m. Annual dinner cruise on the Wm. B Tennison. Cost is $30 per adult and pre-registration is required. For more information, call 410-316-2042 ext. 41. Monday, September 13 • Blood Drive Second District VFD and Rescue Squad (Valley Lee)-12 p.m. The American Red Cross will be holding a blood drive at the Second District VFD and Rescue Squad from noon5 p.m. Walk-ins are welcome, or people can schedule an appointment or get more information by calling 301-994-1038. • Monday Morning Movies & More Calvert Library (850 Costley Way, Prince Frederick)-10 a.m. For more information, call 410-535-0291 or 301-855-1862. • Patuxent River Quilter’s Guild meeting Good Samaritan Lutheran Church (20850 Langley Road, Lexington Park)-6:30 p.m. There will be a guest speaker, Genie Posnet, at the monthly meeting. Posnet will be giving her lecture entitled “Dressing the Bones” and there will be a $5 guest fee for non-members. • No Linit Texas Hold ‘Em “Bounty” Tournament St. Mary’s County Elk’s Lodge (45779 Fire Department Lane, Lexington Park)-7 p.m. Part of the Leaderboard Challange FallWinter season. Anybody is welcome to join. Buy in is $25 or $3,000 in chips. Blinds start ar $25/$50 and are progressive. People wih the most points will recieve a free roll to the $150.00 Leaderboard Challenge Tournament in February. You can earn points for each tournamant you paticipate in. Side games, food and beverages are avaliable. For more information, call the lodge at 301-863-7800 or Linda Hill at 240-925-5697. Tuesday, September 14 • Election Day Stuffed Ham Sandwiches Sale (13820 Point Lookout Road, Ridge)-7:30 a.m. The Ridge Volunteer Fire Department Auxiliary will be holding their Stuffed Ham Sandwich Sale on Primary Election Day. The sandwiches will be $4 and other food items and baked goods will be for sale. Pre-orders must be collected by noon or they will be sold. • St. Mary’s Hospital Auxiliary Golf Tournament Breton Bay Golf and Country Club (21935 Society Hill Road, Leonardtown)-11 a.m. Tee-off is a noon. A person can sponsor a team or put their own foursome together for this tournament. Proceeds form the event will go to find critical equipment for the Emergency Department Trauma Center at St. Mary’s Hospital. To sponsor a team or register your own, call Kay Owns, event chair, at 301-373-3626. • Group Personal Training Breakthrough Fitness (6247 Crain Hwy., Upper Marlboro)-5 p.m. Get personal training in a small group. Groups have a minimum of three and a maximum of six people and space is limited. New clients are welcome, but drop ins are not encouraged. Arrangements have to be made in advance to prepare a personalized initial workout. People who make a comittment to a group are expected to workout with that group at the designated time. For more information, call 240-463-6868. • Yoga Class Breakthrough Fitness (6247 Crain Hwy., Upper Marlboro)-6:30 p.m. Classes meet weekly through Nov. 2. The price is $120 per person. The classes consist of traditional hatha yoga with centering and relaxation meditation at the beginning and end of each 60-minute session. To register on-line, go to. Wednesday, September 15 • Adult Computer Class: Introduction to Windows Lexington Park Library (21677 FDR Blvd., Lexington Park)-2.p.m. Charlotte Hall Library (37600 New Market Road, Charlotte Hall)-5:30 p.m. Adults can learn the basics of Microsoft Windows free. Registration is requied. For more information, call 301-863-8188 (Lexington Park) or 301-884-2211 (Charlotte Hall). • Why Snooze When You Can Crooze Arby’s (40824 Merchants Lane, Leonardtown)5 p.m. Come on out with your custom car, truck or motorcycle to cruise night. • Learn to Line Dance Hotel Charles (15110 Burnt Store Road, Hughesville)-7 p.m. The Boot Scooters of Southern Maryland will be giving Line Dancing lessons free of charge at Hotel Charles. The regular weekly practice for team members will be after the lessons. For more information, go to www. bootscootersofsomd.blogspot.com. “Murder at the Yacht Club” NE LI OSS E IC T CR L POO NO NE LI OSS E IC T CR L PO NO DO D An interactive murder mystery dinner, Live and silent auctions SATURDAY, SEPTEMBER 18 Lenny’s Restaurant • California, MD 6 pm to 9 pm A fundraiser presented by the Friends of the St. Clement’s Island and Piney Point Museums TICKETS: $60 Museum Members $65 Non – Members ADVANCE SALE ONLY TIX & INFO: 301-769-2222 The County Times Miss St. Mary’s County Places at State Fair 24 Adopt A Pet! Miss St. Mary’s County Farm Bureau 2010, Emmilee Guy, was chosen first runner up in the Miss Maryland Agriculture competition. The contest was held at the opening night festivities of the 130th State Fair in Timmonium, a press release states. The competition represented all 23 county farm bureaus. Southern Maryland’s Tri-County region fared well in the contest with Miss Charles County, Rebecca Creighton, placing fourth runner up, Emmilee Guy placing first runner up and Calvert County’s Lauren Jackson being selected as Miss Maryland Agriculture 2010. Emmilee Guy is a graduate of Leonardtown High School and is currently a student at the College of Southern Maryland. She plans to be an elementary school educator. In addition to her studies, she is active in the Young Farmers Organization and helps to manage her family’s farm. Emmilee is the daughter of Sherri and Roy Guy of Clements. Thursday, September 9, 2010 “Hi, my name is Jake and I’m a wonderful eight year old male Rottweiler/Basset Hound mix. I love other dogs and get along great with kids. I’d make a terrific family dog or companion dog. I’m up to date on vaccinations, neutered, house trained and identification micro chipped. For more information, please call SECOND HOPE RESCUE at 240-925-0628 or email lora@secondhoperescue.org. Please Adopt, Don’t Shop!” CHURCH SERVICES DIRECTORY ANGLICAN THE ANGLICAN MISSION OF SOUTHERN MARYLAND Sundays - 9:30 AM 41695 Fenwick Street Unit 3 Leonardtown, MD 20650 301/475-9337 BAHA’I FAITH BAHA’I FAITH “Consort with the followers of all religions in a spirit of friendliness and fellowship” Discussions every 3rd Friday, 7:30 pm 301-884-8764 • 1-800-22-UNITE or BAPTIST CHURCH GRACE CATHOLIC CHAPEL HUGHESVILLE BAPTIST CHURCH Grace Chapel A member of the Southern Baptist Convention 8505 Leonardtown Road, Hughesville, MD 20637 301-884-8645 or 301-274-3627 Pastor Keith Corrick Associate Pastor Kevin Cullins • Sunday Morning Worship • Sunday School (all ages) • Sunday Evening Worship & Bible Study • Wednesday Discipleship Classes (Adults, youth & Children) Going the Distance An Independent Baptist Church and Academy 10:30am 9:15 am 6:00 pm 7:00 pm Victory (Meeting at Mechanicsville Elementary School) Pastor Carl Snyder Worship Service: 10:00 am Phone: 301-884-3504 • Website: John 8:32 Member of fellowship of Grace Brethren Churches PRESBYTERIAN 10:00 am 11:00 am 7:00 pm 7:00 pm …Making a Difference Golden Beach Rd. Charlotte Hall, MD 20622 • 301-884-8503 Robert W. Kyner, Pastor CATHOLIC CHURCH Calvary Baptist Church St. Cecelia Church Independent, Fundamental & KJV Bible-believing Home of 88.1 FM, All Christian Radio (mailing address & church office: 46365 Pegg Ln., Lexington Park, MD 20653) 47950 Mattapany Rd, PO Box 429 St. Mary’s City, MD 20686 301-862-4600 301 862-4435 Meeting at: Home Towne Center Conference Room Sunday School: 10 A.M. (2nd bldg. north of Naval Air Museum) Sunday Services: 11 A.M. & 6 P.M. 22196 Three Notch Rd. (Rt. 235) Lexington Park, MD Wednesday Bible Study & Prayer: 7 P.M. United Episcopal North Sandgates Rd. (1/4 Mile in, on the left) Mechanicsville Traditional 1928 Prayerbook Services 10:00 am Sunday Father Joseph H. Dobson, Jr., Rector Father John Ayres, Assistant 301-373-3862 or StJohnsUEC@md.metrocast.net BAPTIST CHURCH Sunday School Worship Service Sunday Evening Wed. Prayer & Bible Study Virgil Mass: Sunday: Weekday (M-F): Confessions: St. John’s UNITED METHODIST Patuxent Presbyterian Church California, Maryland 301-863-2033 Rev Michael R. Jones, Senior Pastor 1 miles South of Thomas Johnson Bridge on Rt. 4 BAPTIST CHURCH EPISCOPAL 4:30 pm Saturday 8:00 am 7:30 am 3-4 pm Saturday Sunday Morning Worship Services: 8:30 am & 11:00 am Sunday School 9:45 am With Nursery care Website: E-mail: ChurchOffice@paxpress.org Offering worship and serving opportunities at… First Friendship campus – Ridge 9:00 am Traditional worshipc St George Island campus – Piney Point 9:45 am Children and Adult Sunday School 11:00 am Traditional worship St. Paul’s campus – Leonardtown 8:05 am Traditional worshipna 9:15 am Contemporary worshipnca(ASL Interpreted) 10:45 am Contemporary worshipnca 6:00 pm The Refinery (interactive worship)nc n – nursery provided c- children’s Sunday school also available a- adult Sunday school also available 301.475.7200 Running the 2nd & 4th Week of Each Month • To Advertise in the Church Services Directy, Call The County Times at 301-373-4125 25 Thursday, September 9, 2010 The County Times SAINT CHARLES. IT’S TIME TO START FRESH, AND SAVE BIG. TOWNHOMES FROM THE $230’S, SINGLE-FAMILY HOMES FROM THE $260’S. Beautiful homes, beautifully priced. And a brand new beginning for you and your family, in a place whose time has come. That place? Saint Charles, Maryland. A beautifully designed community located in the heart of Charles County just 11 miles south of the Beltway and 22 miles from downtown DC. Swimming, tennis, golf, first-rate public and private schools, the Saint Charles Towne Center and year round activities are all a part of your new community. See it for yourself. See Saint Charles. There are 12 apartment communities to rent and townhome and single-family homes by 3 of the finest national home builders–Lennar, Ryan Homes and Richmond American–all beautifully designed and all beautifully close to DC. A PLACE WHOSE TIME HAS COME. Model homes now open. The County Times Rotary’s Performing Arts Series Adds Variety This Year By Sarah Miller Staff Writer Photo from Twain in his act “Mark Twain! On Mark Tw several times in the past and is. Singer and humorist David Pengelly will be finishing up the series on Jan. 8. Proceeds from the Performing Arts Series will go to fund “Service with a Smile,”475-6999 or go online to. Photo from David Pengelly sarahmiller@countytimes.net We post nightlife events happening in Calvert, Charles and St. Mary’s counties. To submit an event for our calendar, email andreashiell@countytimes.net. Deadline for submissions is Monday by 5 p.m. Thursday, September 9 •Happy Hour Gilligan’s Pier (11535 Popes Creek Road, Newburg)-3 p.m. •Dave Norris DB McMillan’s (23415 Three Notch Road, California)-5 p.m. •Karaoke/Dance Party Bowie Applebee’s (4100 N W Crain Highway, Bowie)9 p.m. •Karaoke with DJ Damon’s Waldorf (45 St. Patrick’s Drive, Waldorf)7:30 p.m. •Teen Advisory Group (TAG) Meeting Charlotte Hall Library (37600 New Market Road, Charlotte Hall)-5 p.m. Leonardtown Library (23250 Hollywood Road, Leonardtown)-5:30 p.m. Friday, September 10 •Maryland Seafood Festival Sandy Point State Park (1100 East College Parkway, Annapolis)-11 a.m. •Happy Hour Gilligan’s Pier (11535 Popes Creek Road, Newburg)-3 p.m. •Dave Norris DB McMillan’s (23415 Three Notch Road, California)-5 p.m. •Fair Warning Donovan’s Pub (22767 Three Notch Road, California)-5 p.m. •Bent Nickel Toots Bar (23971 Mervell Dean Road, Hollywood)-7 p.m. •DJs Donna and Ohmer Hotel Charles (15110 Burnt Store Road Hughesville)7:30 pm. •Church Hollywood Volunteer Fire Department (24801 Three Notch Road, Hollywood)-8 p.m. •Karaoke with Lori and Band in a Box Quade’s Store (36786 Bushwood Wharf Road, Bushwood)-8 p.m. •Karaoke “On Demand” With DJ/KJ Steadyrockin Cadillac Jack’s (21367 Great Mills Road, Lexington Park)-9 p.m. •Karaoke with D Waldorf Applebee’s (3610 Crain Hwy, Waldorf)-9 p.m. •No Green Jelly Beenz Gilligan’s Pier (11535 Popes Creek Road, Newburg)-9 p.m. What’s The County Times is always looking for more local talent to feature! To submit art or band information for our entertainment section, e-mail andreashiell@countytimes.net. Thursday, September 9, 2010 •Endway Hulas Bungalow (23900 N Patuxent Beach Road, California) 8 p.m. •3 Day Ride Big Dog’s Paradise (28765 Three Notch Road, Mechanicsville)-9:30 Saturday, September 11 •Hate the Toy Apehangers (9100 Crain Hwy., Bel Alton)-9 p.m. •Fall Follies Leonardtown Square)12 p.m. •Open Skate Night Leonard Hall Recreation Center (23145 Leonard Hall Drive, Leonardtown)-5:30 p.m. •Disc Jockey/MC Chef’s American Bistro (22576 Macarthur Blvd., San Souci Plaza Suite 314, California) •Fair Warning DB McMillan’s (23415 Three Notch Road, California)-6 p.m. •The Not So Modern Jazz Quartet The West Lawn Inn (9200 Chesapeake Ave., North Beach)-8 p.m. •Saturday Night Dance featuring The Wanderers Mechanicsville Volunteer Fire Department (28165 Hills Club Road, Mechanicsville)-8 p.m. •Car 54 Scott’s II (7050 Port Tobacco Rd., Welcome)-9 p.m. •Karaoke “On Demand” With DJ/KJ Steadyrockin Cadillac Jack’s (21367 Great Mills Road, Lexington Park)-9 p.m. •Big Boy Little Band- Live Blues Performance Delta Blues Juke Joint and Diner (2796 Old Washington Road Waldorf)-9 p.m. •Karaoke California Applebee’s (45480 Miramar, California)-9 p.m. •Karaoke with DJ Mango Lexington Lounge (21736 Great Mills Road Lexington Park)-9 p.m. •End of Summer Blowout Party Gilligan’s Pier (11535 Popes Creek Road, Newburg) featuringSam Grow Trio-2-6 p.m. Full Steam-8 p.m.-midnight Sunday, September 12 •37th Annual Catonsville Arts and Crafts Festival (Frederick Road, Catonsville))-Noon •Nuttin’ Fancy Sea Breeze Restaurant & Bar (27130 South Sandgates Road, Mechanicsville)-3 p.m. •The California Ramblers Back Roads Inn (22094 Newtowne Neck Road, Leonardtown)-3 p.m. 26 Creek Road, Newburg)-3 p.m. •Fair Warning DB McMillan’s (23415 Three Notch Road, California)-5 p.m. •Teen Advisory Group (TAG) Meeting Lexington Park Library (21677 FDR Blvd., Lexington Park)-5 p.m. •Texas Hold ‘Em Cadillac Jack’s (21367 Great Mills Road, Lexingtn Park)-7 p.m. •”Cruisday/Tuesday Karaoke” with Reggie Kelly’s “Rock ‘n’Soul” karaoke show The Holiday House (6427 Harford Road, Baltimore)8 p.m. Wednesday, September 15 •Happy Hour Gilligan’s Pier (11535 Popes Creek Road, Newburg)-3 p.m. •Anne Arundel County Fair (1450 Generals Highway, Crownsville)-4 p.m. •Captain John DB McMillan’s (23415 Three Notch Road, California)-5 p.m. •Karaoke/Spoken Word Poetry Chef’s American Bistro (22576 Macarthur Blvd., San Souci Plaza Suite 314, California)-5 p.m. •Karaoke/Ladies Night Chef’s American Bistro (22576 Macarthur Blvd., San Souci Plaza Suite 314, California)-5 p.m. Monday, September 13 •Live Music Gilligan’s Pier (11535 Popes Creek Road, Newburg)-6 p.m. •Happy Hour Gilligan’s Pier (11535 Popes Creek Road, Newburg)-3 p.m. •Take Me Back To Bambinos Reunion Ruddy Duck Brewery (13200 Dowell Road, Dowell)-5 p.m. •One Maryland One Book Chat- “Home of the Brave” by Katherine Applegate Charlotte Hall Library (37600 New Market Road, Charlotte Hall)-5 p.m. •Mason Sebastion DB McMillan’s (23415 Three Notch Road, California)-5 p.m. •Book Dicussion- “Crazy for the Storm: A Memoir of Survival” by Norman Ollestad Lexington Park Library (21677 FDR Blvd., Lexington Park)-6 p.m. Tuesday, September 14 •Bingo Hollywood Volunteer Fire Department (24801 Three Notch Road, Hollywood) Early Bird-6:30 p.m. Regular-7 p.m. •Book Discussion- “Outcasts United” by Warren St. John Lexington Park Library (21677 FDR Blvd., Lexington Park)-6 p.m. •Wolf’s Hot Rods & Old Gas Open Blues Jam! Beach Cove Restaurant (8416 Bayside Road Chesapeake Beach)-8 p.m. •Open Mic Night with Myles Morse Church Street Pub (489 East Church Street, Frederick)-8:30 p.m. •Karaoke with DJ Stacy Memories Nightclub & Bar (2360 Old Washington Road, Waldorf)-9:30 p.m. * CALL TO CONFIRM •Happy Hour Gilligan’s Pier (11535 Popes n O g n i o G For family and community events, see our calendar in the community section on page 23. In Entertainment 27 The County Times Thursday, September 9, 2010 By Linda Reno Contributing Writer We don’t know anything about her origins or exactly when she came to Maryland, but her name was Blanche and she was living here about 1640. She married first, John Harrison who was deceased by 1642. As was the norm, she quickly remarried. Her second husband was Roger Oliver. They weren’t married very long before Roger was killed. 7/10/1643: John Nuttall being demanded of the meanes how Roger Oliver came by his death, saith that he saw no assault made by any one upon the person of the said Roger; nor doth know by what meanes he came by his death; but about 6 houres or thereabouts as he imagineth after he was slaine, this depont saw the said Roger lying in the hold of the vessell, with onely one wound in his throat, & a gap vpon his chin, wch he supposeth was made wth the knife that wounded him in the throat, & saw a dutch knife lying close by him, bloudy, & broken close by the hand, & more he knoweth not. John Hollis likewise demanded, The Wanderings of an Aimless d Min A Harperʼs Ferry Day By Shelby Oppermann Contributing Writer This is a Harper’s Ferry Day. Cool, breezy, with sparkling sunshine. It is still early September and we have had a few days which have given us an early taste for Fall. I have even seen a few crickets on the hearth. They are finding their way inside the house whenever we open the door. After a record number of hot days this summer, I have heard many people say that they are so ready for fall to begin. Well, I know it’s close because many stores have already put their Halloween items on display. Fall was the time when my Father and I would take our long drive to Harper’s Ferry, West Virginia. I loved that drive almost as much as our three really long drives to Texas to visit my oldest brother, Bobby. The trip to Harper’s Ferry wasn’t really that far from Clinton, but the change in scenery was so drastic. Our leaves might be just starting to change at home, while you could see the gradual change to brighter oranges and reds as you travelled up I-270 and I-70. Part of the way I would keep my arm out of the window to feel the wind pressure on my hand. The other part of the drive I took with my head on my Father’s leg getting lulled to sleep listening to WGAY or some classical music station. Sometimes I would watch the telephone lines with their graceful arches and pretend I was gliding along them on skis. How nice when everything was as simple as that. My Father would hum or sing along in his deep baritone, sounding to me like a mixture of Johnny Cash and Bing Crosby, and drive with one hand holding his Chesterfield cigarette. The smell of cigarette smoke on those drives was comforting to me, probably the only time I ever felt that way about cigarettes. Daddy would pack a cooler with our favorites, just like our Golden Beach trips: propane gas grill, American cheese on white bread (yes, white bread), pork and beans, Vienna sausages, maybe a few hot dogs, sardines for him, and applesauce and sardine A Journey Through Time saith that being vpon the deck, & called by Thomas Boys to helpe Roger Oliver, he leaped downe into the hold, & saw an Indian & the said Roger strugling together, whervpon this dept knocked the Indian on tion. He did not admit the killing or the promise… but the head wth the barrell of a gonne, & presthe court awarded her a cow in damages.” ently after he saw the said Roger fall downe by The record is not clear, but at some point it was ala wound which the Indian had given him as he leged that Blanche had committed perjury in pressing supposeth; & being distracted for some time wth her claims. She pled not guilty but the jury determined perills of his life in the hold with other Indians as otherwise. It was ordered that she“stand nayled in the soone as he looked vpon the said Roger he saw pillory and loose both her eares (her ears were nailed him dead, & more he knoweth not of the meanes to the pillory and cut off afterwards). how he came by his death. Blanche had only two children. Her son, William Between 1646 and 1648, Blanche became emOliver, died as a youngster. Blanche’s daughter, Mary broiled in controversy. She claimed that Governor Harrison married Nicholas White and both of them Calvert had killed her ox at St. Thomas’s Fort and had promised her another one in its place. By June A pillory from early times died in 1659, but they left an infant daughter named Eleanor White who was left in the care of Major Wil1648 Blanche was married to Humphrey Howell when she sued Nathaniel Pope (ancestor of George Washington) liam Boarman. Eleanor White later married Francis Knott (born “ for a cow which Pope, or some of his accomplices in time of the about 1648 in England who was brought to Maryland by his steprebellion killed at the fort and for which he promised her satisfac- father, Robert Cole). sandwiches for me. I know it sounds weird, but it was the only way I could eat them. My Father was very close with his money. I don’t remember ever eating in a restaurant with him, even on our trips to Texas. He’d wait until we got to Texas and knew my Air Force pilot brother would take care of everything. Daddy might have been a little… cheap. But you haven’t lived until you are stopped at scenic rest areas with a cheese sandwich in your hand. At that moment it was the best gourmet meal in the world. At Harper’s Ferry we would set up our picnic area right on the shore of the Shenandoah River. My Father would stay down at the site and read, and I would wander over every nook and cranny of the town. Up the stone steps, past the churches; one still in use at the time and one destroyed in the Civil War, The Harper House, to Jefferson Rock, and then up to the graveyard on the top. Back down in the town, I would go through all the shops, my favorite being the one with apple candy bars. What a wonderful compact town for kids. I only went in the John Brown museum a few times. Those life size wax figures were too lifelike and scary for me, especially the hanging room. The entire town was fascinating to me. Oh, how wonderful it would be to have one more trip there with my Dad, but it’s been thirty years since his passing. My husband and I did spend one of our November anniversaries there a few years ago, and the town is still magic to me even now and with all it’s changes. The fresh breezes coming off the Potomac and Shenandoah Rivers, the quaintness, and of course the beautiful leaves. We don’t leave St. Mary’s County often, but once in awhile I do love to see the mountains, and feel at one with my Father. To each new day’s adventure Shelby Please send comments or ideas to: shelbys.wanderings@yahoo.com. Chronicle Last Week’s Puzzles Solutions CLUES ACROSS 1. Fishhook point 5. Golfer Norman 9. S. China seaport 14. Colorless compound 15. Helicopter 16. Like an old woman 17. Complex quantities 18. Swedish rock group 19. Matador injury 20. It’s capital is Wellington 23. Worldly rather than spiritual 24. No (Scottish) 25. Having flavor 28. Those easily cheated 32. ____ Ladd, actor 33. Take hold of (Brit.) 35. He played Gordon Hathaway 36. Nostrils 38. Make a mistake 39. Strike with fear 41. Consumed 42. Place in line 44. W. Rumanian city 45. Supply with air 47. Extreme happiness 48. Indian arrowroot 49. Smoking implement 51. Bond author 55. Emotionally distressed 58. Cape near Lisbon 59. Aba ____ Honeymoon 62. Add piquancy 63. Highly excited 64. Longest division of geological time 65. Niches 66. Hold a position 67. Indian musical genre CLUES DOWN 1. Seed vessel with hooks 2. They __ 3. Bridle strap 4. Baseball scoring path 5. Mohammedan warrior 6. Medieval fiddle 7. Italian Island 8. Scoring area 9. Business leaders 10. Electrodes 11. Le ___que Restaurant 12. Brew 13. Largest English dictionary, (abbr.) 21. Small mass of material 22. Genus of ducks 25. Yemen capital 26. Winglike maple seeds 27. Small sharp fruit knife 28. Asteroid 3228 ___ 29. Lake in No. Finland 30. Jaguarondis 31. Plant sources 33. Six (Spanish) 34. Bulky grayish-brown eagle 37. Satisfies to excess 40. Annual timetable 43. Slant away from vertical 46. From each one 47. Characters in one inch of tape 49. A tributary of the Rio Grande 50. A representation of a person 52. Make secure by lashing 53. Trademark 54. Mother of Cronus 55. ___ Today: newspaper 56. Worthless ideas 57. Type genus of the Suidae 60. Cranberry field 61. Am. Nurses Assoc. (abbr.) The TheCounty CountyTimes Times New Meth Training Helps With Bust Robert Oscar Newland cover operations and executed Search and Seizure Warrants over the course of ve days. This training was offered at no cost to St. Mary’s County. The process for “cooking” methamphetamine has evolved over time and now is conducted in what is called a “one pot” or “shake and bake” process,” St. Mary’s Sheriff Lt. Daniel Alioto said in a press release. This means an entire lab is contained within a plastic bottle and makes the process even more dangerous as it is easily transported and carelessly discarded. The information learned was shared with the State’s Attorney’s Ofce. During the month of July of 2010, Vice Narcotics Detectives received information that Suspect Robert Oscar Newland, 24 of California, was allegedly manufacturing methamphetamine. Undercover purchases of methamphetamine were made from Newland, police report. The cases were reviewed with State’s Attorney Richard D. Fritz and presented to the Grand Jury. Three arrest warrants were issued and a Search warrant was obtained. On Sept. 2, the St. Mary’s County Sheriff’s Ofce Emergency Services Team assisted Vice Narcotics Detectives in executing the Search Warrant on the California home. Numerous items of evidence were seized from inside the home and discarded in the rear yard and wooded area behind the home. Marijuana and cocaine was recovered as well and charges are pending against a second suspect. The U.S. Drug Enforcement Agency was contacted and provided a federally certied clean up crew to respond from the State of Pennsylvania to handle the hazardous material clean up. The DEA funded the clean up as well as the collection gear needed. Newland was charged with three counts of “Distribution of Methamphetamine” and numerous additional charges are pending a review with State’s Attorney Richard D. Fritz. The successful investigation, identication, and arrests in this case were made possible by the training and eld experience provided by Sheriff Bivens, the Monroe County Narcotics Unit and the Tennessee Methamphetamine Task Force, Alioto stated. Philip H. Dorsey III Attorney at Law -Serious Personal Injury CasesLEONARDTOWN: 301-475-5000 TOLL FREE: 1-800-660-3493 EMAIL: phild@dorseylaw.net 28 10 Drug Arrest at Trafc Stop Police Briefs In June 2010, Sheriff Bill Bivens of Monroe County Tennessee hosted training on methamphetamine investigations for St. Mary’s Vice Narcotics Detectives. Detectives worked side by side with detectives in the Monroe County Narcotics Unit and the Tennessee Methamphetamine Task Force detecting, identifying and conducting clean ups. Vice Narcotics detectives conducted under- Thursday,September September9,9, 2010 Thursday, 2010 On Friday, Sept. 3, at 5:48pm, TFC C. M. Evans initiated a trafc stop in the area of Route 235, north of Route 712 on a white Ford Crown Victoria for a trafc violation. Upon making contact with the driver, Trisha Kathleen Jones, 34, of Lexington Park and a male passenger, TFC Evans observed an unknown pill located on the oorboard of the passenger seat. The pill was a scheduled narcotic, and a prescription was produced authorizing Jones to be in possession of it. However, an additional search revealed a CDS – Not Marijuana in Jones’ property, police report. Jones was arrested and transported to the St. Mary’s County Detention. Jones was charged with Possession of CDS Paraphernalia and Possession of Hydromorphone and will be held pending a bond review with the District Court Commissioner. Man Jailed for Sleeping in Post Ofce On Saturday, Sept. 4, at 3:19am, Trooper R. L. Jackson responded to the United States Post Ofce on South Coral Drive in Lexington Park for a reported subject sleeping in the lobby. Upon arrival, the trooper made contact with Oliver Henry Woods, Jr., 49, of Waldorf who was sleep in the lobby of the Post Ofce. Police say Woods had been notied by Trooper Jackson on two previous occasions that he was not permitted to sleep in the establishment and continuing to do so would be considered trespassing. Woods was subsequently arrested for Trespassing on Government Property and transported to the St. Mary’s County Detention Center. He was held pending a bond review with the District Court Commissioner. Grand Jury Issues Felony Indictment Police report that Charles Vaselee Freeman Jr., 26 of Lexington Park, was identied as a distributor of marijuana and prescription medication. Members of the St. Mary’s County Bureau of Criminal Investigations Vice Narcotics division conducted undercover purchases of marijuana and Percocet. A recent Grand Jury for St. Mary’s County handed down two arrests warrants charging Freeman with felony distribution of both controlled substances. He was arrested and originally held without bond. Two Sheriff’s Cars in Serious Crash By Sean Rice Staff Writer At 7:45 p.m. Sept. 6, St. Mary’s County Sheriff’s units were responding to a personal injury motor vehicle crash in the area of Three Notch Road and St. Jerome’s Road in Dameron, when two police cars crashed. A press release states that a preliminary investigation states a 2009 Ford Crown Victoria operated by Deputy Scott Ruest was traveling northbound on Three Notch Road behind a 2007 Ford Crown Victoria operated by Dfc. Michael George. As units arrived on the scene Ruest’s vehicle collided with George’s vehicle, which subsequently struck a 2003 Honda Odyssey, was unoccupied and parked in the parking lot of the Dameron Post Ofce. The Odyssey was reportedly involved in the crash to which the ofcers were responding. Dfc. George was own by Maryland State Police Helicopter Trooper 7 to Baltimore Shock Trauma. Deputy Ruest was transport via ambulance to St. Mary’s Hospital. Both Deputies were treated and released from the hospitals. The motor vehicle collision investigation, as well as an agency internal investigation is on going, the release states. Sheriff’s ofce ofcials have not revealed any other details of the incident, pending the outcome of the investigation. “We are very fortunate the Deputies injuries were not as serious as originally believed. Our thoughts and prayers are with the deputies. We wish them both a speedy recovery,” Sheriff Tim Cameron said in a statement. seanrice@countytimes.net Woman Allegedly Scratches Cop On Sept. 4. St. Mary’s Sheriff’s, police say. As Dfc. Watters was walking to his vehicle, a victim exited the residence and stated Cooper struck him in the head with a telephone, police report. Dfc. Watters told Cooper she was under arrest for second-degree assault. As Dfc. Watters attempted to escort Cooper from the residence she tried to pull away from him, police report. Dfc. Watters placed Cooper on the ground and attempted to handcuff her. Cooper continued to resist and she dug her ngernails into Dfc. Watters hand causing a scrape to his hand, police say. Cooper was handcuffed and charged with two counts of second degree assault and resisting arrest. Breia Marie Cooper 29 The County Times Thursday, September 9, 2010 Business Call to Place Your Ad: 301-373-4125 DIRECTORY Deadlines for Classifieds are Tuesday at 12 pm.. Classifieds Real Estate WATERFRONT HOME IN NICE COMMUNITY ON BEAUTIFUL LEVEL LOT WITH PIER. 2 bedrooms, 2 baths, formal living room, kitchen/island/bar, dining area, florida/sun room with climate controlled, 2+ car garage, with handicapped ramp. Generator back, blacktop, overhead garage doors with openers, security system installed, cable tv ready, 14’ X 40’ garage with 3 access doors, small storage shed, deck with vinyl railings, professionally landscaped. $975,000.00 call (301) 884-5061 or email tegcustomhomes@aol.com. Real Estate Rentals Phone 301-884-5900 1-800 524-2381 Phone 301-934-4680 Fax 301-884-0398 CROSS & WOOD ASSOCIATES, INC. Serving The Great Southern Maryland Counties since 1994 Employer/Employee Primary Resource Consultants Group & Individual Health, Dental, Vision, AFLAC, Life, Long Term Care, Short & Long Term Disability, Employer & Employee Benefits Planning 12685 Amberleigh Lane La Plata, MD 20646 28231 Three Notch Rd, #101 Mechanicsville, MD 20659 Law Offices of P.A. Hotchkiss & Associates Since 1987 WHERE YOUR LEGAL MATTER-MATTERS Heating & Air Conditioning Auto Accidents – Criminal – Domestic Wills – Power of Attorney DWI/Traffic – Workers’ Compensation “THE HEAT PUMP PEOPLE” 30457 Potomac Way Charlotte Hall, MD 20622 Phone: 301-884-5011 301-870-7111 1-800-279-7545 Serving the Southern Maryland Area Accepting All Major Credit Cards Est. 1982 snheatingac.com Lic #12999 Large 1200sqft 2 Bedroom, 1 Bathroom home on 1/2 acre in Leonardtown. Large closets in both bedrooms and hallway. Linnen closet in Bathroom. Oil Heat, Air Conditioning, Electric appliances, Central Vacuum System. Large Laundry/Utility room. Carport with closet. 10x12 storage shed on premises. Recently painted, and new carpet and vinyl throughout within the last year. New well installed in 2007. New furnace in 2008. 10 miles to Pax River and 2 miles to downtown Leonardtown. Walking distance to Leonardtown High and Middle schools, Tech Center, and Convenience store/ gas station. Transit system stop right across the street. $1100/mo rent, $1250 Security Deposit. No smoking inside premises. Pets allowed on a case by case basis and will require additional pet deposit. Call (301)863-5764. 2 large bedroom, 2 Bath newly built apartment with open floor plan. Apartment is located in a quiet and private setting and located on the second floor of two story duplex. The apartment has a lot of windows and an abundance of storage space. No outside maintenance needed. Prefer single or couple and No pets. No Section 8 or Housing Programs. Call 301-472-4310. Price: $1,100 Help Wanted Dental Assistant needed monday, tuesday, wednesday for Dentrix software. Prefer certified in Dentrix, XRay certification a must. Calvert County Dental Office. Great Staff & Patients. Call 410-535-1990. Estate Sales 301-737-0777 301-866-0777 Pub & Grill 23415 Three Notch Road California Maryland 188 Days Till St. Patrick’s Day Entertainment All Day Prime Rib • Seafood • Sunday Brunch Banquet & Meeting Facilities 23418 Three Notch Road • California, MD 20619 Advertising That Works! Ca ll 30 ! d A 1-373 r -4125 to Place You Estate Item Sale-September 11, 2010, 7AM-12PM, 23360 Rolling Court, Town Creek, -tools, hardware, electronics, appliances, many unique items & lots of stuff. Important. Sp rts The County Times A View From The BLEACHERS sports. This expectation, of course, is unrealistic and we know it. First, adults are more reserved creatures than kids. Us big people are so situationally aware and selfevident we almost never get lost in a moment. More importantly, though, the business of professional sports is a serious one with real consequences: see the fine line between employed and unemployed. Pro coaches Tennis Social Doubles Social Doubles for Adults is held twice weekly and consists of informal doubles matches, put together by the site coordinator, based on that day’s attendance. All who show up will get to play. • 5 P.M. Thursdays at Great Mills High School, June 6th through September. Contact Bob Stratton at 443-926-2070 or rstratton55@hotmail.com. The league fee is $30 for the Great Mills site. Fees include court costs and balls. No registration is required. 30 Brown Wins Second Straight SP Lawnmower Championship By Chris Stevens Staff Writer just like the Wicked Witch did in Munchkinland. Just because something you loved becomes a job laden with responsibility doesn’t mean you have to lose. With a second straight United States Lawnmower Racing Association SP class championship on the line, Clements native Jason Brown knew a fast start would be necessary to hold on to the crown. “I had to try and get a good clean start – I’m not usually a good starter,” Brown said after he jumped out to first place and won both SP races this past weekend in the Sta-Bil finals in Delaware, Ohio to earn the title by 50 points over Richard Webb of Michigan. Photo By Frank Marquart Brown’s strategy Jason Brown won his second straight USMLRA SP was easy to think of and as it turned out, class title Labor Day Weekend. easy to execute. “Once you get out in front, it’s just driving hard, staying away from light traffic and just pulling away,” he said. Brown was confident in his ability to win, but the media coverage on the season’s final regular season race forced him to prepare for the race early. “It was never-wracking. You don’t have too much time to pay attention to the race,” he said. “Every time you start working on something, you’ve got another camera in your face. You’ve got to prepared ahead of time.” Brown also had to deal with being the target of every SP participant this season. “This was better than last year because you have that target on your back – everyone’s looking at you as soon as you unload,” he says. “People have been paying a lot more attention this year than they did last year.” Brown also finished in the top 10 of the higher-horsepower BP class, but was disappointed in his results in BP. “To be honest, I’m not happy with it. It was a bad year in that class. I blew two engines, lost a transmission and even in the last race, I lost my brakes, but we finished up good,” he said. Brown credited his sponsors (L.S.I, Sta-bilt, S&J Heating, Accokeek Development and William Dishman contractors to name a few), along with Bryantown’s Wally Bender, who won the AP national title, for helping them along the way, and a celebration is planned. “It was about midnight when we left the track, so we just went to a restaurant up there,” Brown said. “But we probably will have a party with my sponsors in the next month or so.” Send comments to rguyjoon@yahoo.com chrisstevens@countytimes.net The Faces Of Comedy And Tragedy By Ronald N. Guy Jr. Contributing Writer Thursday, September 9, 2010 SMCTA, Rec and Parks Partner on Tennis Court Lighting at Dorsey Park The St. Mary’s County Tennis Association has jumpstarted a new doubles league to help defray the cost of using the tennis court lights at the Dorsey Park. Led by organizer Laura Carrington of Leonardtown, the league plays Wednesday nights at Dorsey Park and consists of many of the area’s best tennis players. The majority of the league’s proceeds, which are generated from registration fees paid by each player, will be donated to Recreation & Parks later this year. “It’s great to have people like Laura who volunteer their time so enthusiastically to run local tennis programs,” says Jason Wynn, Vice President of the SMCTA and one of the league’s participants. The newly installed lights at Dorsey Park are programmed to run eight months out of the year, and can be operated by players between dusk and 11:00 p.m. with the push of a button. Based on the first few months of operation, the Department of Recreation and Parks estimates the yearly cost to operate the lights to be approximately $600. “Recreation and Parks has a long history of working with the SMCTA to provide enhanced tennis facilities and programs in St. Mary’s County. We hope to continue this partnership to promote the game of tennis for many years to come,” said Phillip Rollins, Director, St. Mary’s County Recreation and Parks. The Department has worked with the SMCTA over the past several years in leveraging funding to enhance twelve (12) tennis courts at various County parks. To date, the County has received $22,500 from the USTA Maryland Fix-A-Court Program, $49,315 from Maryland’s Program Open Space, and $402,100 in County funding for these efforts. “While not all players who use the tennis courts at Dorsey Park are members of the SMCTA, it makes sense for us to help out, given the fact that County baseball and softball programs are charged a fee for using the lights on the ball fields,” said Wynn. “I certainly prefer the push-button system at Dorsey over the kind that you have to stuff quarters in every half-hour.” The Dorsey Park Doubles league will run through November, weather permitting. Regular participants are asked to pay $30 to cover the whole season, while substitutes who fill in occasionally must pay $5 per match. The league will conclude with a hot-dog roast for the players. 31 Thursday, September 9, 2010 The County Times Calvert Memorial Hospital Center for Breast Care 5K Challenge Run/Walk & Health Expo Thurs., Sept. 9 p.m. Girls’ Soccer St. John’s at St. Mary’s Ryken, 4 p.m. Field Hockey Leonardtown at Calvert, 4 p.m. St. John’s at St. Mary’s Ryken, 4 p.m. Girls’ Tennis Paul VI at St. Mary’s Ryken, 3:30 p.m. Fri., Sept. 10 Boys’ Soccer St. Mary’s Ryken at St. John’s, 4 p.m. Cross Country St. Mary’s Ryken at Magruder Invitational, 9 a.m. Field Hockey Patuxent at Chopticon, 4 p.m. Football Great Mills at Calvert, 7 p.m. Patuxent at Leonardtown, 7 p.m. Archbishop Carroll at St. Mary’s Ryken, 7 p.m. Girls’ Soccer North Point at Great Mills, 6 p.m. Volleyball Lackey at Great Mills, 7 p.m. Sat., Sept. 11 Boys’ Soccer Chopticon Tournament, 9 a.m. Football Chopticon at Gwynn Park, 1 p.m. Volleyball Leonardtown Tournament, 9 a.m. Mon., Sept. 13 Boys’ Soccer Thomas Stone at Great Mills, 6 p.m. Leonardtown at Calvert, 6 p.m. St. Mary’s Ryken at Paul VI, 6:45 Wed., Sept. 1 Girls’ Soccer Great Mills at Thomas Stone, 6 p.m. Calvert at Leonardtown, 6 p.m. Join the fun on Oct. 2nd at the Solomons Medical Center and raise funds for a great cause – the Center for Breast Care at CMH Volleyball Great Mills at Thomas Stone, 7 p.m. About the Run/Walk Tues., Sept. 14 Boys’ Soccer Chopticon at North Point, 6 p.m. St. Mary’s Ryken at Archbishop Carroll, 4 p.m. t On-site registration starts at 7 a.m. t Warm up with World Gym trainer at 8 a.m. t Race starts at 8:30 a.m. Volleyball St. Mary’s Ryken at Holy Cross, 5:30 p.m. RACE FEES: Wed., Sept. 15 Cost is $35 for adults & $25 for children 6-17 Ask about package deals! Cross Country Chopticon/La Plata at Leonardtown, 4:30 p.m. Great Mills/McDonough/ Thomas Stone at Lackey, 4:30 p.m. Field Hockey St. Mary’s Ryken at Good Counsel, 3:45 p.m. Golf Northern/North Point/McDonough vs. Chopticon at Wicomico Shores, 4 p.m. Great Mills/Huntingtown vs. Leonardtown at Breton Bay, 4 p.m. Girls’ Tennis Good Counsel at St. Mary’s Ryken, 3:30 p.m. Volleyball Westlake at Chopticon, 7 p.m. To pre-register, call 410-535-8233 Great Giveaways! - Prizes for top finishers in each age group - Post-race rejuvenation tent will offer FREE refreshments & seated massages - Door prizes & free giveaways for all participants - Free race T-shirts for all who pre-register plus first 100 who sign up on-site Golf Chopticon 179 Calvert 184 Great Mills 196 Football Westlake 12, Chopticon 10 Great Mills 47, Thomas Stone 14 Leonardtown 38, Westlake 21 Paul VI 42, St. Mary’s Ryken 14 McDonough 155 Leonardtown 175 Patuxent 182 Volleyball Leonardtown 3, Chopticon 0 Fri., Sept. 3 Sat., Sept. 4 Field Hockey Leonardtown 3, La Plata 0 Field Hockey Great Mills 2, McDonough 0 Bring your family! Come for the run/walk, the health fair or both! Health Expo free for everyone! - 8 a.m. – noon / Open to all ages - Informative displays - “Passport to Good Health” for children 10 and under - FREE screenings for blood pressure, cholesterol, glucose, skin cancer, osteoporosis, vascular and more Some tests require pre-registration To sign up, call 410-535-8233 Sp rts The County Times Thursday, September 9, 2010 32 Football Ryken Falls Behind in Football Home Opener, Can’t Catch Up Paul VI 42, St. Mary’s Ryken 14 By Chris Stevens Staff Writer 1 14 0 Paul VI (1-0) SMR (1-1) 2 22 0 3 6 6 4 0 8 Total 42 14 LEONARDTOWN – It was a tale of two halves for the St. Paul VI – Collins 1 run (kick failed) Mary’s Ryken football team in their home opener Friday night. Paul VI – Collins 1 run (Collins run) Visiting Paul VI took advantage of the Knights mistakes Paul VI – Tuell 5 run (O’Donnell kick) in the first half, cruising to a 42-14 win, but the Knights clearly Paul VI – Alex Jesmer 36 pass from Salmon (O’Donnell kick) played better in the second half, an encouraging sign for thirdPaul VI – Tuell 3 run (Charlie Jesmer run) year head coach Bob Harmon. SMR – Snell 11 run (pass failed) “The things that happened to us in that first half, we did Paul VI – Hughes 70 punt return (kick failed) to ourselves,” Harmon said of five turnovers, all of which the SMR – Houston 1 run (Snell pass to Simms) Panthers turned into touchdowns. “You can’t have five fumbles, you can’t have a blocked punt, you can’t have a punt returned for a score. But we’re going to get better.” The Panthers (1-0) used a multitude of running backs to wear down the Knights defense. Five running backs had at least five carries, with George Collins and Zach Tuell scoring two touchdowns each. The Knights also got a 36-yard touchdown pass from quarterback David Salmon to receiver Alex Jesmer, as well as a 70yard punt return for a touchdown to end the third quarter by Phil Hughes. “We wanted to give our offense a short field,” Paul VI head coach Nick Metro said. “I had my guys prepared like it was an Army-Navy game because we thought they were going to be fired up.” Photo By Frank Marquart Johnny Houston ran for 46 yards and a touchdown in the Knights’ 42-14 loss to Paul VI Friday night. Photo By Frank Marquart The St. Mary’s Ryken football team hits the field for the first time at their new campus stadium. The Knights trailed 36-0 at the half, but outscored the Panthers 14-6 in the second half, with sophomore quarterback Zach Snell scoring the first touchdown for the home team in the new stadium’s history. “We won that second half,” Snell said plainly. “I feel confident towards the future because we played really well in the second half.” As for scoring the first home touchdown in the new stadium’s history? “I was overwhelmed and proud of my offensive line for blocking for me like that,” Snell said of his uncontested 11-yard run up the middle with 6:58 left in the third quarter. “The cornerbacks bit on the fakes and I saw my chance.” Ryken added another touchdown from junior running back Johnny Houston in the fourth quarter, and he too was excited about the potential success of this year’s team. “We’ve got really good coaches and we were very aggressive in that second half,” said Houston, who led the Knights’ ground game with nine carries for 46 yards. “This is something I’ll always remember.” Tough loss notwithstanding, Harmon is still pleased with the way things are going, especially now that his football team has a field they can call home. “I looked around when we came out and said ‘Wow, we’re not at Lancaster Park anymore,’” he said. chrisstevens@countytimes.net Hornets Rout Stone in Season Opener By Chris Stevens Staff Writer The Great Mills football team used their superior speed and quickness, jumping out to a 34-0 halftime lead and cruised to a 47-14 win over Thomas Stone Friday night. “That’s what it was – the old adage ‘speed kills,’” Hornets head coach Bill Griffith said. “Our guys played really hard and [Stone] just couldn’t handle our team speed.” Junior running back Aaron Wilkerson led the charge with four touchdowns in three different ways – he caught two passes from quarterback Jordan Hurtt for scores, adding a 45-yard run and a six-yard interception return for a score. Hurtt threw for three touchdowns (the other going to Anthony Smith) and Wink Queen also added a rushing touchdown for Great Mills, who defeated Thomas Stone 6-0 to end a 20game losing streak a year ago. The Hornets are in much the same position they were last season – facing Calvert after defeating Thomas Stone to begin their season. The Hornets lost to the Cavaliers 21-14 with a roughing the kicker penalty costing them in the final seconds. Great Mills will travel to Prince Frederick Friday night at 7 p.m. with an eye on revenge for last season’s loss. “We can’t make the same mistakes we made against them last year,” Griffith said. “We just have to play mistakefree football and do the same things that we did well this past week.” Griffith was pleased with the effort that the Hornets put forward because it sends a message to Southern Maryland Athletic Conference teams who think that last year’s 5-5 record was a one-year wonder. “This was good for us because people are probably thinking ‘Well, they’ll go back to being the same old Great Mills,’” he said. “We’re not. This is a new Great Mills team and we plan on going even further than we did last year.” chrisstevens@countytimes.net 33 The County Times Thursday, September 9, 2010 Raiders Rally for Win in Nines’ Coach Debut By Chris Stevens Staff Writer Mike Nines really didn’t think too much about his first win as a high school football coach until a little while after Leonardtown’s 38-21 win over visiting Calvert Friday night. “It didn’t hit me until I called my parents and told them,” Nines said with a chuckle. “I was more happy for the players, especially the seniors because they’ve been through some tough times.” The new and improved Leonardtown ground game, led Patuxent transfer Marcus Stout, rolled up 378 rushing yards and scored 25 unanswered points in the second half to start their season on the right foot. Nines was pleased with the effort after Calvert jumped out to a 21-13 at the break, noting that the senior leadership was key. “They know what we expect of them, so we came out in the second half, made some corrections,” Nines said. “We’ve been preaching confidence to the kids and they’ve responded.” Stout led the way with 179 yards on 18 carries, while Alfonso Cyrus and Stephen Stewart added 118 and 66 rushing yards respectively. The Raiders also got a 42-yard interception return from senior linebacker Mike Molina in the win. The prolific running game is the desired effect of the Wing-T offense, and Nines gave total credit to his offensive linemen, who have to be successful in order for the Wing-T to work properly. “This puts our players in the right spots,” he says. “We’ve got linemen who are fast and block well. They worked their tails off [Friday] night.” Leonardtown will now turn its attention to their second home game of the season, a match-up with Southern Maryland Athletic Conference contender Patuxent. The Panthers are coming off of a 13-0 win over Lackey, and Nines feels the keys to a win over Patuxent include using their offensestopping their two main offensive weapons, quarterback Ed Massengil and running back Dakota Edwards. “We want to exploit their linebackers with our speed and try to confuse them a little bit,” he said. “Also, if we can key on their quarterback and running back, we should be successful,” chrisstevens@countytimes.net Westlake Overtakes Chopticon in Final Seconds By Chris Stevens Staff Writer Quarterback Chris Istvan and receiver Steven Koudossou hooked up for two touchdowns, the final one coming with 13 seconds left in the fourth quarter, as Westlake rallied to defeat Chopticon 12-10 Friday night in the season opener for both teams at Wolverine Stadium. “I thought we played hard and played well as a team,” Braves head coach Tony Lisanti said. “Westlake is a very good team and this is something we can build on.” Sterling Miles scored on an 11-yard touchdown run and junior place-kicker Christopher Palmer kicked a 37-yard field goal to give the Braves (0-1) a 10-0 lead through three quarters. The Wolverines (1-0) refused to quit and pulled out the win on Istvan’s five-yard toss to Kodossou for the win. Lisanti was pleased with the improved defensive effort – Westlake scored 40 on the Braves in the 2009 season opener. “A lot of it has to do with us knowing our roles and that allows us to play fast and play very well,” he said. “Westlake didn’t gouge us for anything.” The coach is still concerned with the running game, as the Braves finished with minus 10 yards rushing. “You can’t run for as little yardage as we did and expect to be victorius,” Lisanti explained. “The run game was a disappointment.” The Braves will continue their tough first-half schedule Saturday afternoon when they travel to Brandywine and face Prince George’s 2A power Gwynn Park. Game time is 2 p.m. The Yellowjackets opened their season in thrilling fashion with a 17-14 overtime victory over Forestville Military Academy at Largo High School last Saturday afternoon. Lisanti remembers them well from their 33-0 victory at Braves Stadium last season. “They’ve got big fast receivers that can run, so it’s going to be a quite a challenge to shut their offense down.” chrisstevens@countytimes.net Westlake 12, Chopticon 10 Chopticon (0-1) Westlake (1-0) 1 0 0 2 7 0 3 3 0 Chopticon – Miles 11 run (Palmer kick) Chopticon – Palmer 37 field goal Westlake – Koudossou 12 pass from Istvan (kick failed) Westlake – Koudossou 5 pass from Istvan (kick failed) 4 0 12 Total 10 12 Sp rts Wolfpack Wins 9 and Under Soccer Title Southern Maryland’s newest and youngest Select Travel Soccer Club, the St. Mary’s United, U9 “Wolfpack”, earned their first victory as a team last month in The August Cup, held in Gaithersburg, MD. The August Cup is represented by some of the strongest travel teams in the MarylandVirginia area. St. Mary’s United’s U9 team faced teams from Western Prince William County (VSA), Montgomery Soccer Club (MSA) from Rockville, and Loudoun in the first round. The Wolfpack defeated each team by scores of 4-0, 7-1 and 7-0 before rallying from two goals down to defeat Seneca FA 6-5 in the championship game. Adult Volleyball League Meetings Adult Volleyball League meetings Men’s meeting Thursday September 9th All meetings at Leonard Hall Recreation Center 7 p.m. Individuals and teams welcome to attend. For more information call Kenny Sothoron at 301-475-4200 ext 1830. Online Registration is Now Open for Southern Maryland Sabres Rec Hockey Sabres Recreational Hockey 2010-2011 begins in October The Southern Maryland Hockey Club recreational program is designed to provide hockey players an opportunity to learn and develop skills in a team setting. The recreational program is also designed to assure equal opportunity to participate for all skill levels. Players of all skill levels are welcome. No tryouts required. These teams participate in the Capital Corridor Hockey League (CCHL). The league is part of the Southeastern District of USA Hockey (). Our home arena is Capital Clubhouse in Waldorf, MD (). Mite/Atom Cross Ice $ 500 Squirts, Pee Wee, and Bantam - $ 750 Midget - $600 Any questions please contact Jaime Cantlon. recdirector@somdsabres.org. Sp rts The County Times I took some of my own advice last week and fished ahead of the storm. I was not disappointed! I got to Cedar Point at 7:00 AM and was immediately in the middle of acres of breaking bluefish, stripers and Spanish mackerel. The fish 34 The Ordinary The Stealth Approach to Breaking Fish By Keith McGuire Contributing Writer Thursday, September 9, 2010 were feeding on small silversides, or bay anchovies. The top water action didn’t stop for two hours before I left them to find a flounder – a fairly futile venture on every trip out of Solomons this year. But, that’s a story for another time. Mine was the only boat in the area for a time. When I saw the birds and boiling surface water, I noted the direction that the feeding fish seemed to be headed and circled slowly and widely to stop in the path of their progress and shut off the outboard. The fish stayed on top, feeding and splashing to their heart’s content as my fishing partner and I cast jigs, spoons and top water plugs into the fray; hooking up and landing fish as fast as we could. The next boat to arrive on the scene was a local light tackle guide who approached the schools Angler Ang Ang ng ngler gler ller le er of breaking fish in a similar fashion. The fish seemed not to notice as we enjoyed the frenzied activity. Several recreational boats arrived next. Some intended to play the breaking fish with light tackle casting rigs and approached with stealth to keep the fish on top. But, there was one (isn’t there always?) who approached the schools of fish like a dirt-track speedway driver on a Friday night. We saw him passing in the distance when he suddenly turned in our direction at speed (he had obviously seen the birds). He launched his boat into the middle of the school of fish, kicked it into neutral and grabbed a spinning rod to cast to fish that were no longer feeding on the surface. The fish resumed their feeding frenzy in the distance, about a ¼ mile off, as the water began to boil and the seagulls restarted their chants. Engines fire up on every boat to pursue the relocated feeding school of fish. Of course, our friend with engines still running got the jump on everyone and was off like a shot! He rammed his boat into the middle of the school of breaking fish, kicked it into neutral and picked up a spinning rod to cast to fish that were no longer there. Fortunately, there were several other schools of breaking fish, so we left the area to take advantage of a different school, leaving “Mr. Haphazard” to play his game away from us. We never saw him pull in a fish. Fishing report: The past week has produced catches of cobia and big red drum near the target ship. Although probably not fishable, a school of small spadefish were spotted at Pt. Lookout. Bluefish, stripers and Spanish mackerel seem to be everywhere. There are still a few croakers, but they seem to be getting smaller. The spot are getting a little bigger now. White perch can be had in decent numbers on oyster bars fished with peeler crab and will succumb to small spinner baits in the shallows. Flounder are still uncooperative, and I wouldn’t waste too much time fishing for Bull Sharks, since only two were caught in our area last week. conservation organizations. Blue Crabs Crabs Split Doubleheader With Bears The Blue Crabs took game one of a Tuesday doubleheader with the Newark Bears 84, while the Bears took the nightcap by a 7-3 score.loaded single. Reichert (16-9) pitched six innings, allowing four earned runs, to earn his Atlantic League-leading 16th win. Bryan Dumesnil pitched the final inning to close out the Bears. 35 Thursday, September 9, 2010 Sp rts The County Times Local Athletes Commit to College Hoops Programs In his lone season at Great Mills Harris averaged 14 points, eight rebounds and two blocks a game, helping the Hornets improve from a four-win 2008-09 season to 18 and the 4A East regional finals last season. Treveon Graham has verbally committed to Virginia Commonwealth University. Pho to B yC hri sS tev e ns Two basketball players from local high schools have made verbal commitments to NCAA Division I universities during the early recruiting period. St. Mary’s Ryken senior Treveon Graham, a 6-foot-5 shooting guard, verbally committed to Virginia Commonwealth University last month, while Great Mills graduate Mykel Harris (6-foot-6 small forward) has agreed to play his college basketball at Monmouth (N.J.) University next fall. Harris, who previously attended King’s Christian Academy in Callaway, will be attending Phelps School in Pennsylvania this year as a post-graduate before beginning his career at Monmouth, a member of the Northeast Conference. Graham, according to head coach/athletic director Dave Tallman, was also being recruited by Boston College, Clemson, Cleveland State, Northeastern and Cincinnati before deciding on VCU, located in Richmond. Graham averaged 18 points and 10 rebounds as a junior last season, and his inspired play helped the Knights set a school record for boys’ basketball wins with 18 and a top-four finish in the Washington Catholic Athletic Conference. Anderson, Williams Big Winners At Potomac BUDDS CREEK – Bunker Hill W. Va’s Andy Anderson was victorious for the third time this season as he captured the 21st running of the Ronnie McBee Memorial Sunday night at Potomac Speedway. Anderson and David Williams brought the field down to the initial green flag of the event. Anderson jumped into the race lead and would lead the first seven circuits. Point contender David Williams then flexed his muscle as he grabbed the top spot from Anderson on lap eight. Williams’ lead would be short-lived as Anderson slid by Williams to take the lead for good on lap 13. As Anderson ran-off and hid in the lead, championship contenders Williams and Dale Hollidge waged another epic Potomac battle. Hollidge, the point leader coming into the event, caught Williams with eight laps to go. The duo would virtually race sideby-side the remaining laps of the event and coming down for the checkered flag, Hollidge got a run off turn-four but came up about a foot short at the finish as Williams would claim his third-straight Potomac LM title by just three-points over Hollidge. Kyle Hardy took fourth and Matt Quade completed the top-five. “The track was slick like we expected,” Anderson stated. “We made the right choice on tires and the car really came on there at the end.” Williams’ title drive started with a heat race win earlier in the program that earned him five-points toward the title. “I think that was a good race for the fans,” Williams said. “I knew Dale was going to be tough to beat, but this was once again a total team effort and I cant thank George and Tina Moreland enough for allowing me to drive their car this season.” Williams won the heat for the 11 cars on hand. Continuing his superb night, Williams scored his third win of the season and career 31st in the 20-lap Limited Late mMdel feature. The win for Williams would be his overall 75th career feature win at Potomac. Starting in 12th position, Williams took the top spot from race long leader Tommy Wagner Jr. on lap 15 and would lead the remaining laps to post the win. Kenny Moreland was second, Wagner held on for third, Ed Pope was fourth and point-leader Derrick Quade completed the top five. Wagner and Pope took heat race wins. In other action, Craig Tankersley became the ninth different winner as he scored the win in the 16-lap Street Stock feature, Jimmy Randall rolled to win number six in the 15-lap Hobby Stock main, Greg Gunter scored his second win of the season and 54th of his career in the 15-lap four-cylinder feature while Larry Fuchs was crowned division champion. Fuchs annexed his fifth feature win in the Strictly Stocks and Josh Wilkins made it win number two in the 20-lap U-car feature. Photo By Frank Marquart Mykel Harris will attend Monmouth University next fall. Limi te By Doug Watson Potomac Speedway dT ime Only! 150 $ Mov e Special n -I Discounted Cable Playground Free on Site Storage with Every Apartment Walk to Shopping/Restaurants Late Model feature results 1. Andy Anderson 2. David Williams 3. Dale Hollidge 4. Kyle Hardy 5. Matt Quade 6. Roland Mann 7. Ryan Hackett 8. Deane Guy 9. Rick Hulson 10. Jim McBee Jr. 11. Barry Lear Sr. Limited Late Model feature results 1. David Williams 2. Kenny Moreland 3. Tommy Wagner 4. Ed Pope 5. Derrick Quade 6. Sommey Lacey 7. Paul Cursey 8. Ricky Lathroum 9. Billy Tucker 10. Dave Adams 11. Dennis Lamb 12. Kevin Cooke 13. Ben Bowie (DNS) 301-862-5307 THURSDAY September 9, 2010 Fritz Outraged With Town Hall Alliance Story Page 7 Bar Crawl Will Help Native Man Fight Cancer Story Page 21 Raiders Win Nines’ Coaching Debut Story Page 33 Knights On New Turf Photo By Frank Marquart Page 32 Published on Sep 9, 2010 The County Times -- September 9, 2010
https://issuu.com/countytimes/docs/2010-09-09.county.times
CC-MAIN-2017-39
refinedweb
28,955
63.39
Today: Idiomatic phrases, "reverse" chronicles, Better/shorter code invariant, more string functions, unicode Today, I'll show you some techniques where we have code that is already correct, but we can write it in a better, shorter way. It's intuitively satisfying to have a 10 line thing, and shrink it down to 6 lines that reads better. > Better problems > speeding() speeding(speed, birthday): Compute speeding ticket fine as function of speed and birthday boolean. Rule: speed under 55, fine is 100, otherwise 200. If it's your birthday, the allowed speed is 5 mph more. Challenge: change this code to be shorter, not have so many distinct paths. The code below works correctly. You can see there is one set of lines each for the birthday/not-birthday cases. What exactly is the difference between these two sets of lines? def speeding(speed, birthday): if not birthday: if speed < 50: return 100 else: return 200 else: # is birthday if speed < 55: return 100 else: return 200 def speeding(speed, birthday): # Set limit var limit = 50 if birthday: limit = 55 # Unified: limit holds value to use. # One if-stmt handles all cases if speed < limit: return 100 return 200 > ncopies() Change this code to be better / shorter. Look at lines that are similar - make an invariant. ncopies(word, n, suffix): Given name string, int n, suffix string, return n copies of string + suffix. If suffix is the empty string, use '!' as the suffix. Challenge: change this code to be shorter, not have so many distinct paths. Before: def ncopies(word, n, suffix): result = '' if suffix == '': for i in range(n): result += word + '!' else: for i in range(n): result += word + suffix return result Solution: use logic to set "suffix" to hold the suffix to use for all cases. Later code just uses suffix vs. separate if-stmt for each case. def copies(word, n, suffix): result = '' # Set suffix if necessary to value to use if suffix == '': suffix = '!' # Unified: one loop, using suffix for i in range(n): result += word + suffix return result > match() match(a, b): Given two strings a and b. Compare the chars of the strings at index 0, index 1 and so on. Return a string of all the chars where the strings have the same char at the same position. So for 'abcd' and 'adddd' return 'ad'. The strings may be of any length. Use a for/i/range loop. The starter code works correctly. Re-write the code to be shorter. Before: def match(a, b): result = '' if len(a) < len(b): for i in range(len(a)): if a[i] == b[i]: result += a[i] else: for i in range(len(b)): if a[i] == b[i]: result += a[i] return result def match(a, b): result = '' # Set length to whichever is shorter length = len(a) if len(b) < len(a): length = len(b) for i in range(length): if a[i] == b[i]: result += a[i] return result See guide for details: Strings Thus far we have done String 1.0: len, index numbers, upper, lower, isalpha, isdigit, slices, .find(). There are more functions. You should at least have an idea that these exist, so you can look them up if needed. The important strategy is: don't write code manually to do something a built-in function in Python will do for you. The most important functions you should have memorized, and the more rare ones you can look up. These are very convenient True/False tests for the specific case of checking if a substring appears at the start or end of a string. Also a pretty nice example of function naming. >>> 'Python'.startswith('Py') True >>> 'Python'.startswith('Px') False >>> 'resume.html'.endswith('.html') True str.replace(old, new) >>>>> s.replace('is', 'xxx') # returns changed version 'thxxx xxx it' >>> >>> s.replace('is', '') 'th it' >>> >>> s # s not changed 'this is it' Recall how calling a string function does not change it. Need to use the return value... # NO: Call without using result: s.replace('is', 'xxx') # s is the same as it was # YES: this works s = s.replace('is', 'xxx') for line in fto trim off \n >>>>> s.strip() 'this and that' 11,45,19.2,N str.split()-> array of strings str.split(',')- split on ','substring str.split()- with zero parameters >>>>> s.split(',') ['11', '45', '19.2', 'N'] >>> 'apple:banana:donut'.split(':') ['apple', 'banana', 'donut'] >>> >>> 'this is it\n'.split() # special whitespace form ['this', 'is', 'it'] >>> foods = ['apple', 'banana', 'donut'] >>> ':'.join(foods) 'apple:banana:donut' {}marks where to paste in +and str(12) to assemble string >>> 'Alice' + ' got score:' + str(12) # old: + and str() 'Alice got score:12' >>> >>> '{} got score:{}'.format('Alice', 12) # new: format() 'Alice got score:12' >>> In the early days of computers, the ASCII character encoding was very common, encoding the roman a-z alphabet. ASCII is simple, and requires just 1 byte to store 1 character, but it has no ability to represent characters of other languages. Each character in a Python string is a unicode character, so characters for all languages are supported. Also, many emoji have been added to unicode as a sort of character. Every unicode character is defined by a unicode "code point" which is basically a big int value that uniquely identifies that character. Unicode characters can be written using the "hex" version of their code point, e.g. "03A3" is the "Sigma" char Σ, and "2665" is the heart emoji char ♥. Hexadecimal aside: hexadecimal is a way of writing an int in base-16 using the digits 0-9 plus the letters A-F, like this: 7F9A or 7f9a. Two hex digits together like 9A or FF represent the value stored in one byte, so hex is a traditional easy way to write out the value of a byte. When you look up an emoji on the web, typically you will see the code point written out in hex, like 1F644, the eye-roll emoji 🙄. You can write a unicode char out in a Python string with a \u followed by the 4 hex digits of its code point. Notice how each unicode char is just one more character in the string: >>>>> s 'hi Σ' >>> len(s) 4 >>> s[0] 'h' >>> s[3] 'Σ' >>> >>>>> s.lower() # compute lowercase 'ω' >>> s.isalpha() # isalpha() knows about unicode True >>> >>> 'I \u2665' 'I ♥' For a code point with more than 4-hex-digits, use \U (uppercase U) followed by 8 digits with leading 0's as needed, like the fire emoji 1F525, and the inevitable 1F4A9. >>> 'the place is on \U0001F525' 'the place is on 🔥' >>>>> len(s) 4 The history of ASCII and Unicode is an example of ethics. In the early days of computing in the US, computers were designed with the ASCII character set, supporting only the roman a-z alphabet. This hurt the rest of the planet, which mostly doesn't write in English. There is a well known pattern where technology comes first in the developed world, is scaled up and becomes inexpensive, and then proliferates to the developing world. Computers in the US using ASCII hurt that technology pipeline. Choosing a US-only solution was the cheapest choice for the US in the moment, but made the technology hard to access for most of the world. This choice is somewhere between ungenerous and unethical. Unicode takes 2-4 bytes per char, so it is more costly than ASCII. Cost per byte aside, Unicode is a good solution - a freely available standard. If a system uses Unicode, it and its data can interoperate with the other Unicode compliant systems. The cost of supporting non-ASCII data can be related to the cost of the RAM to store the unicode characters. In the 1950's every byte was literally expensive. An IBM model 360 could be leased for $5,000 per month, non inflation adjusted, and had about 32 kilobytes of RAM (not megabytes or gigabytes .. kilobytes!). So doing very approximate math, figuring RAM is half the cost of the computer, we get a cost of about $1 per byte per year. >>> 5000 * 12 / (2 * 32000) 0.9375 So in 1950, Unicode is a non-starter. RAM is expensive. What does the RAM in your phone cost today? Say your phone costs $500 and has 8GB of RAM (conservative). Say the RAM is all the cost and the rest of the phone is free. What is the cost per byte? The figure 8 GB is 8 billion bytes. In Python, you can write that as 8e9 - like on your scientific calculator. >>> 500 / 8e9 # 8 GB 6.25e-08 >>> >>> 500 / 8e9 * 100 # in pennies 6.2499999999999995e-06 RAM costs nothing today - 6 millionths of a cent per byte. This is the result of Moore's law. Exponential growth is incredible. Sometime in the 1990s, RAM was cheap enough that spending 2-4 bytes per char was not so bad, and around then is when Unicode was created. Unicode is a standard way of encoding chars in bytes, so that all the Unicode systems can transparently exchange data with each other. With Unicode, the tech leaders were showing a little generosity to all the non-ASCII computer users out there in the world. With Unicode, there is just one Python that works in every country. A world of programmers contribute to Python as a free, open source software. We all benefit from that community, vs. each country maintaining their own in-country programming language, which would be a crazy waste of duplicated effort. So being generous is the right thing to do. But the story also shows, that when you are generous to the world, that generosity may well come around and help you as well.
http://web.stanford.edu/class/cs106a/handouts_w2021/lecture-14.html
CC-MAIN-2022-05
refinedweb
1,624
74.08
Sorting array of chars alphabetically then by length how to sort a list alphabetically in c++ sort array of strings alphabetically c++ sort the strings based on the length of the string in an array sort an array of strings according to string lengths in c++ sort an array of strings according to string lengths java sort the array of strings according to alphabetical order defined by another string sort array of strings by length java I have an array of structs where I keep track of how many times each unique word was seen in a given text: struct List { char word[20]; int repeat; }; Now I need to sort this: as 6 a 1 appetite 1 angry 1 are 2 and 4 ... To this: a 1 as 6 and 4 are 2 angry 1 appetite 1 ... (By alphabetically I mean only by first letter) So far, I have come up with this: for (i = 0; i < length - 1; i++) { min_pos = i; for (j = i + 1; j < length; j++) // find min if (array[j].word[0] < array[min_pos].word[0]) { min_pos = j; } swap = array[min_pos]; // swap array[min_pos] = array[i]; array[i] = swap; } This code works perfectly for sorting alphabetically, but I just can't write proper code to sort BOTH alphabetically and by length. Others have pointed out that there are faster and cleaner ways to sort. But if you want to use your own selection sort, as you've written, then you just need to make a few changes to your code. Separate the "do I need to swap" logic from the swapping logic itself. Then the code becomes much cleaner and it's more clear where to add the extra check. I've only copied the inner loop here. You'd want to replace your existing inner loop with this one. I'm not clear on why you need swap_pos and min_pos, so I've left the semantics alone. for (j = i + 1; j < length; j++) { // find min // first, determine whether you need to swap // You want to swap if the first character of the new word is // smaller, or if the letters are equal and the length is smaller. bool doSwap = false; if (array[j].word[0] < array[min_pos].word[0]) { doSwap = true; } else if (array[j].word[0] == array[min_pos].word[0] && strlen(array[j].word) < array[min_pos].word) { doSwap = true; } // do the swap if necessary if (doSwap) { swap_pos = j; swap = array[min_pos]; // swap array[min_pos] = array[i]; array[i] = swap; } } To more clearly illustrate the necessary logic changes, I've purposely avoided making major style changes or simple optimizations. Python Sorting | Python Education, How do you sort a list of strings based on length? We are given an array of strings, we need to sort the array in increasing order of string lengths. A simple solution is to write our own sort function that compares string lengths to decide which string should come first. Below is the implementation that uses Insertion Sort to sort the array. // according to lengths. // implements Insertion Sort. Make a comparator function. Add an operator< to your List: bool operator<(const List &lhs) const { if(word[0] != lhs.word[0]) { return word[0] < lhs.word[0]; } return strlen(word) < strlen(lhs.word); } And now use this operator to sort, using whichever algorithm strikes your fancy. Program to sort a string in alphabetical order, Which method will arrange the elements of an array in alphabetical order? Sort. You can pass a lambda to sort to do this: sort(begin(array), end(array), [](const auto& lhs, const auto& rhs){ return *lhs.word < *rhs.word || *lhs.word == *rhs.word && (strlen(lhs.word) < strlen(rhs.word) || strlen(lhs.word) == strlen(rhs.word) && strcmp(lhs.word, rhs.word) < 0); }); Which method will arrange the element of an array in alphabetical , Firstly, using just sorted will not sort alphabetically, look at your output I am pretty sure L does not come before a . What you are currently Given a string of lowercase characters from ‘a’ – ‘z’. We need to write a program to print the characters of this string in sorted order. A simple approach will be to use sorting algorithms like quick sort or merge sort and sort the input string and print it. Time Complexity: O (n log n), where n is the length of string. Use tuple lexicographical compare operators An easy way to not write this condition is to #include <tuple> Then std::tie can be used: std::tie(array[j].word[0], array[j].repeat) < std::tie(array[min_pos].word[0], array[min_pos].repeat) This works because std::tie creates a tuple of lvalue references to its arguments. (Which means std::tie requires variables. If You want to compare results from functions std::make_tuple or std::forward_as_tuple would be better) And std::tuple has operators which Compares lhs and rhs lexicographically, that is, compares the first elements, if they are equivalent, compares the second elements, if those are equivalent, compares the third elements, and so on. And the above description is also the idea how to make a comparison of more than value. Sort string array first on length then alphabetically in Python 3 , A simple solution is to write our own sort function that compares string lengths to Count of strings in the first array which are smaller than every string in the"). Sort an array of strings according to string lengths, Given a string str and an array of strings strArr[], the task is to sort the array according to the alphabetical order defined by str. Now, this map will act as the new alphabetical order of the characters. in the map i.e. if character c1 appears before character c2 in str then c1 < c2. for ( int i = 0; i < min(x.size(), y.size()); i++) {. The sort is case-sensitive. For more information on sorting character and string arrays, see Sort Order for Character and String Arrays. If A is a string array, then sort reorders the elements of the array, but does not reorder characters within the strings. Sort the array of strings according to alphabetical order defined by , Four different ways to sort characters in a string in Java with example. toCharArray();; //4; for (int i = 0; i < charArray.length; i++) {; for (int j = i + 1; Then, we have passed one lambda to compare the characters in the second Sometimes we need to sort all characters in a string alphabetically. It creates a different string variable since String is immutable in Java. For example, String ‘albert’ will become ‘abelrt’ after sorting. In this Java example, we will learn how to sort the characters of a string alphabetically in different ways. Let’s take a look : 4 different ways to Sort String characters Alphabetically in Java , To sort a given array of strings into lexicographically increasing order or into an order in which the string with the lowest length appears first, a sorting function with of distinct characters present in them, then the lexicographically smaller string C++: How do i sort array of Strings alphabetically in C++? I am trying to sort array of string (2D array of Characters) using bubble sort. and I am stuck at this. - This would be easier by using std::string. You could use std::map<std::string, int>to associate words with frequencies. The sorting would be handled for you. Natural sorting of std::stringis by letter, then length, e.g. `"aa" before "ba". - It's unclear here what the purpose of swap_posis. Is it supposed to be min_pos? - Yes, forgot to change it back. - The second for- where is it's opening brace? The first forwhere is it's closing brace? - Ended up putting your loop in do ... while (doSwap)Works like a charm, thank you. - @enjoy I don't think that conditional loop is a good idea with selection sort. The general case of selection sort doesn't allow for an early out. - Actually, I have this: bool loop; int n = 2; do { ... } while ((loop && n) || n--);So it runs several times to sort everything correctly. I am 100% sure this code is awful, but I am very new to programming and pretty happy with this. - Great idea. I would combine it with my idea to: Use tuple lexicographical compare operators. (answer below) - OP wants length, no repeat - All right, I've added your code and tuplelibrary to my project, but nothing happens. Like it just doesn't execute. I've read about std::tiefor a while, but I guess I missed something. - @enjoy where did You use this code? In the ifstatement? - @Jarod42 I thought that repeatwas the other variable to be compared. I modified the answer to suggest using make_tuplewhen function results have to be compared. - I would combine this answer and use it in the "Make a comparator function."
http://thetopsites.net/article/50495527.shtml
CC-MAIN-2020-50
refinedweb
1,475
63.09
Database support is the lifeline of every application, big or small. Unless your application deals only with simple data, you need a database system to store your structured data. Android uses the SQLite database system, which is an open-source, stand-alone SQL database, widely used by many popular applications. For example, Mozilla Firefox uses SQLite to store configuration data and iPhone also uses SQLite for database storage. In Android, the database that you create for an application is only accessible to itself; other applications will not be able to access it. Once created, the SQLite database is stored in the /data/data/<package_name>/databasesfolder of an Android device. In this article, you will learn how to create and use a SQLite database in Android. Create an Android project using Eclipse and name it Database (see Figure 1). A good practice for dealing with databases is to create a helper class to encapsulate all the complexities of accessing the database so that it's transparent to the calling code. So, create a helper class called DBAdapter that creates, opens, closes, and uses a SQLite database. First, add a DBAdapter.java file to the src/<package_name> folder (in this case it is src/net.learn2develop.Database). In the DBAdapter.javafile, import all the various namespaces that you will need: package net.learn2develop.Databases; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class DBAdapter { } Next, create a database named bookstitles with the fields shown in Figure 2. In the DBAdapter.java file, define the following constants shown in Listing 1. The DATABASE_CREATE constant contains the SQL statement for creating the titlestable within the books database. Within the DBAdapter class, you extend the SQLiteOpenHelper class—an Android helper class for database creation and versioning management. In particular, you override the onCreate() and onUpgrade() methods (as shown in Listing 2). The onCreate() method creates a new database if the required database is not present. The onUpgrade() method is called when the database needs to be upgraded. This is achieved by checking the value defined in the DATABASE_VERSION constant. For this implementation of the onUpgrade()method, you will simply drop the table and create the table again. You can now define the various methods for opening and closing the database, as well as the methods for adding/editing/deleting rows in the table (see Listing 3). Notice that Android uses the Cursor class as a return value for queries. Think of the Cursor as a pointer to the result set from a database query. Using Cursor allows Android to more efficiently manage rows and columns as and when needed. You use a ContentValues object to store key/value pairs. Its put()method allows you to insert keys with values of different data types. The full source listing of DBAdapter.java is shown in Listing 4. Please enable Javascript in your browser, before you post the comment! Now Javascript is disabled. Your name/nickname Your email WebSite Subject (Maximum characters: 1200). You have 1200 characters left.
http://www.devx.com/wireless/Article/40842
CC-MAIN-2013-48
refinedweb
523
60.01
, Panasonic P2 MXF, HVX200 and Canon C300/XF300/XF305 to store video, audio, and programmed data. However,. Pavtube MXF Converter for Mac (For windows:, VOB, AVI, MOV, MP4, MPEG, WMV, FLV for playing and editing Step 1. Run Pavtube best MXF Converter for Mac or MXF Converter, this software supports MXF conversion well. Click "Add file" or "Add from folder" button, browse to the footages and load .MXF files to the converter. Step 2. Select the items to be converted, and click on "Format" bar. If you need to convert MXF to MKV/VOB/AVI/MOV/MP4/MPEG/WMV/FLV, you just need to select corresponding format. Just click format bar and choose the format you need. To play and edit MXF on Windows, Adobe After Effects, Adobe Premiere Pro, Sony Vegas, Pinnacle Stdio,Windows Movie Maker, xBox, you can transcode MXF to AVI, MXF to WMV or MXF to MPEG format. To play and edit MXF on Mac, QuickTime, Zune, iPod, iPad, iPhone, Apple TV, etc you can convert MXF to MP4, or encode MXF files to MOV, to play on Mac, QuickTime. To import MXF to Final Cut Pro, FCE, and iMovie, you can convert MXF to ProRes MOV for FCP and MXF to AIC MOV for editing in iMovie. You can also convert MXF to any desired video formats with the professional MXF Converter. Step 3. You can click settings button to adjust output parameters. To maintain original HD quality, you may set "original" in the fields of "Size", "Bitrate" and "Frame rate". To downsize the MXF files to MOV, MKV, AVI, MPG, MP4, WMV, FLV, if you are windows user, you can refer the guide converting MXF AVI/WMV/MOV/MP4/MPEG on Windows. Now, you can easily transfer MXF video for editing, playing and sharing. Tips: 1. If you want to convert MXF to multi audio channels MKV/MOV/MP4, convert MXF to Side-by-Side 3D, Top-Bottom 3D and Anaglyph 3D in MKV/MP4/MOV/WMV/AVI formats on Windows or Mac, please choose Pavtube MXF MultiMixer and iMixMXF 2. To burn MXF videos to DVD on Windows/Mac, please refer to the guide: How to Burn MXF to DVD disc without Apple iDVD on Mac? See also: MXF Mixer: Mixing multitracks MXF files into one track on Win/Mac Convert P2 AVC-Intra 50/100 MXF Files to AVI/WMV/MPG/MP4/FLV Why MXF files not reading by Premiere Pro CS6 Workflow to Edit Canon MXF files in FCP 6/7 without XF utility on Mac OS X import Panasonic HVX200 MXF to iMovie 8/9/11 on Mac OS X Convert Canon XF300 MXF to ProRes for FCP/Premiere Pro on OS X Can FCP import Avid MXF Files on Mac? Source:
http://www.anddev.org/view-layout-resource-problems-f27/top-mxf-converter-convert-mxf-files-on-mac-windows-t2191320.html
CC-MAIN-2016-40
refinedweb
462
65.56
Razor View engine is a part of new rendering framework for ASP.NET web pages. ASP.NET rendering engine uses opening and closing brackets to denote code (<% %>), whereas Razor allows a cleaner, implied syntax for determining where code blocks start and end. Example: In the classic renderer in ASP.NET: <ul> <% foreach (var userTicket in Model) {%> <li><%:userTicket.Value %><li> <% } %> </ul> by Using Razor: <ul> @foreach(var userTicket in Model) { <li>@userTicket.Value</li> } <ul> How to import a namespace in Razor View Page? When using aspx view engine, to have a consistent look and feel, across all pages of the application, we can make use of asp.net master pages. What is asp.net master pages equivalent, when using razor views? When using razor views, do you have to take any special steps to proctect your asp.net mvc application from cross site scripting (XSS) attacks? Forgot Your Password? 2018 © Queryhome
https://www.queryhome.com/tech/99578/explain-about-razor-view-engine
CC-MAIN-2018-30
refinedweb
152
61.33
4509/how-can-i-make-the-return-type-of-a-method-generic Is there a way to figure out the return type at runtime without the extra parameter using instanceof? Or at least by passing a class of the type instead of a dummy instance. I understand generics are for compile time type-checking, but is there a workaround for this? First of all, define callFriend: public <T extends Animal> T callFriend(String name, Class<T> type) { return type.cast(friends.get(name)); } Then call it as such: jerry.callFriend("spike", Dog.class).bark(); jerry.callFriend("quacker", Duck.class).quack(); This code has the benefit of not generating any compiler warnings. This is really just an updated version of casting from the pre-generic days and doesn't add any additional safety. Whenever you require to explore the constructor ...READ MORE If you're looking for an alternative that ...READ MORE import java.util.*; public class AmstrongNumber { public static void ...READ MORE Assuming TreeMap is not good for you ...READ MORE private static class SomeContainer<E> { ...READ MORE You could probably use method invocation from reflection: Class<?> ...READ MORE Generic array creation is not allowed in Java. But, ...READ MORE Use the following code : new Timer(""){{ ...READ MORE List<String> results = new ArrayList<String>(); File[] files = ...READ MORE Here are two ways illustrating this: Integer x ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/4509/how-can-i-make-the-return-type-of-a-method-generic
CC-MAIN-2020-05
refinedweb
235
60.72
Forms provide a rich way of interacting with users. However, the form handling process is complex. Forms accept user input which poses a major security threat. I like to think of it as an unlocked door. You definitely need some security measures. The rule of the thumb is to never trust a user input or worse malicious attackers taking advantage of unsuspecting users. Caution is required to ensure that the user's data is sanitized and field validation is taken into consideration. From Class Django has an inbuilt form Class that allows you to easily create forms. You define the fields of your form, specify the layout, display widgets labels, specify how they have to validate user input and the messages associated with invalid fields. It also provides methods for rendering itself in templates using predefined formats such as tables, list or paragraphs. In this tutorial, we will focus on creating, processing forms and rendering to the template. The task is to create a form that enables users to subscribe to the newsletter app and then send the new subscribers a welcome email. Creating Newsletter App In Django, apps are small components used to build projects For an app to be active, add it to the list of settings.INSTALLED_APPS. .Apps perform a specific function and can be reused in various projects. Since we are creating a newsletter, we will name it a newsletter. Make sure you are in the same directory as manage.py and type: python manage.py startapp newsletter When Django creates the newsletter app, it also creates some files and the structure look like this: newsletter/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py views.py In order to use the app, we must activate it by adding it to settings.INSTALLED_APPS INSTALLED_APPS = [ ... 'newsletter', ] Now our app is installed and activated, let make it do something! Creating Models Next, we going to create our model in models.py. For each model defined Django will create a table for it in the database. Let's define our model and name it NewsUsers and give it 3 fields name, date_added write the following code in your newsletter/models.py from django.db import models class NewsUsers(models.Model): name = models.CharField(max_length = 30) email = models.EmailField() date_added = models.DateField(auto_now_add=True) def __str__(self): return self.email - import the models. - Next,I have defined 3 fields: name, date_added The __str__()method simply tell python to display a human-readable representation of the model Make and Run Migrations. python manage.py makemigrations newsletter python manage.py migrate Anytime you make changes to the models remember to run migrations Adding Models to Admin Site We will create a simple admin site to manage the newsletters users from django.contrib import admin from .models import NewsUsers class NewsletterAdmin(admin.ModelAdmin): list_display =('email','date_added',) admin.site.register(NewsUsers, NewsletterAdmin) Create a Superuser and runserver To Interact with the admin site, we must create a user with admin privileges python manage.py createsuperuser Then input the credentials. Below is a snippet Username: laughing-blog Email address: "email Adress" Password: Password (again): Run the server and navigate to on the browser.Log in using superuser credentials you created above. python manage.py runserver If you are successful then you will see an interface similar to this: Note: Django is 'smart' and naturally pluralizes the model In admin We have NewsUserss and that is not cool! To avoid such a scenario, define meta class in models and set the verbose _name=' singular' and verbose_name_plural. Your models should look like this from django.db import models class NewsUsers(models.Model): name = models.CharField(max_length = 30) email = models.EmailField() date_added = models.DateField(auto_now_add=True) class Meta: verbose_name = "NewsUser" verbose_name_plural = "NewsUsers" def __str__(self): return self.email always run migrations after modifying the models After applying migrations, run the server again and navigate to the admin interface and the extra s should be gone and if you click to add the user, you should be able to add users in the newsletter list Creating the Newsletter Form Django has two base classes. The form class and modelForm for creating forms. With the form you get to create standard forms and the ModelForm allows you to build forms from the model's fields. Depending on your needs you can choose either of the two methods. The standard forms are best in scenarios where the forms do not interact with the database directly. - Forms: Allows you to build Standard Forms - ModelForm: Allows you to build forms from a model by defining fields using the Meta class In our case, we will create a form using the ModelForm Create a new file called forms.py in newsletter app. it's a general practice to create Django forms in a file called forms.py Let's go ahead and declare the form. To create our ModelForm, import the form class and the model class from django import forms from .models import NewsUsers class NewsUserForm(forms.ModelForm): class Meta: model = NewsUsers fields = ['name', 'email'] - Import the forms library - derive from the ModelForm class - declare the Fields we need in the meta section Handling Django forms in views It's time for the heavy lifting from django.shortcuts import render from .forms import NewsUserForm from . models import NewsUsers def newsletter_subscribe(request): if request.method == 'POST': form = NewsUserForm(request.POST) if form.is_valid(): instance = form.save() print('your email is already added to our database') else: form = NewsUserForm() context = {'form':form} template = "newsletter/subscribe.html" return render(request, template, context) huh! what is all that? First things first, let us deal with the importations. Import NewsUserForm from form.py and NewsUsers from models. The first step in handling forms in Django is to display an empty form to the user. When our view is initially loaded with a GET request, we create a new form instance that will be used to display the empty form in the template. form = NewsUserForm() A form may be blank in the case where you creating a new record or may be pre-populated with initial values. At this stage, the form is unbound because it is not associated with any user input although it may have initial values. At this point, the form is unbound The second step is to check if the user has filled the form and submit it via POST. So, If it is a POST request, we create a new form instance and populate it with data from the request. This process is called binding and the form is said to be bound if request.method == 'POST': form = NewsUserForm(request.POST) binding allows us to validate data. I mean it's meaningless validating a form with no data right? Next, Check for form validation and clean the data. The method is_valid(), is used to check if the form is valid. Form validation means the data accepted is as specified when defining the fields. In our case, the name field accepts up to a maximum of 30 characters only, theemail` field must be a valid email and so on. This method will return true if the fields contain valid data or false if invalid throwing errors. If the form is valid, we clean the data. This means performing sanitization of the input i.e removing invalid characters that might be used to send malicious content to the server. If we have a valid form as in our case, we process the form. To save the data we call save() method. "save()method" It is worth mentioning that only modelFormshave this method and not form Creating newsletter/urls.py Okay, our data is saved in the database. We now want to create the url that will display the form we just created. Create a new file in newsletter app and name it urls.py then place the code below: python from django.urls import path from .views import newsletter_subscribe app_name = 'newsletter' urlpatterns = [ path('subscribe', newsletter_subscribe, name='subscribe'), ] In the main urls.py include the uurl confi from the newsletter app Main urls.py python from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('newsletter/',include('newsletter.urls' , namespace='newsletter')), ] To check if the form is being displayed, run the server using the command down below bash python manage.py runserver When you navigate to on the browser, it will return an error that the template does not exist. Do not panic just yet, we just need to create the template subscribe.html Rendering the Form in Templates Create a templates directory in newsletter app called templates and inside it create another directory called newsletter which will hold the file subscribe.html file. The structure should look like this: python newsletter templates newsletter subscribe.html subscribe.html python {% extends "base.html" %} {% block content %} <form action="{% url 'newsletter:subscribe' %}" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> {% endblock %} you must include cross-site request forgery {% csrf_token %} tag for POST requests Run the Server again and navigate to $ python manage.py runserver you should see the form below: Fill in your name and email and when you hit submit, it saves check the admin interface and you should see the user you just added. Recap So far we have created - Newsletter App - Creating Models - Adding Models to admin site - Creating forms from models - Writing views - Creating urls - Creating Superuser newsletter/views.py The above view will work just fine, but some custom validation on the email field is required to ensure that the same email is not used more than once! try using the same email more than once and it will save We do not want that to happen right? so let's add some queries to filter the email. If the email already exists we notify the user it already exists else save. Update your views to look like this: python from django.shortcuts import render from .forms import NewsUserForm from .models import NewsUsers def newsletter_subscribe(request): if request.method == 'POST': form = NewsUserForm(request.POST) if form.is_valid(): instance = form.save(commit=False) #we dont want to save just yet if NewsUsers.objects.filter(email=instance.email).exists(): print( "your Email Already exists in our database") else: instance.save() print( "your Email has been submitted to our database") else: form = NewsUserForm() context = {'form':form} template = "newsletter/subscribe.html" return render(request, template, context) Create the model instance with the save() method, but don't save it to the database just yet by calling commit = False - The save()method creates an instance of the model that the form is linked to and saves it to the database. - If called with commit=False, it creates the model instance but doesn't save to the database just yet! Then, we check if the email exists by using filter before we save. If it exists, we tell the user it already exists else save and display to the user it has been added to our database. fill the form using a new email and check if it saves. We have added a notification message on the console, so check your console for guidance. Use the same email again and check the console Now it validates our emails, Great Work! Sending Emails Sending Emails with Django is quite simple.All we need is an Email service Provider.You can use gmail or write to the console for testing .Refer to Sending Emails with mailjet because I will be using mailjet Remember the .env file we created in Project Structure and update it with your smtp credentials Replace "Your Username" with the actual username and "Your Password" with your actual password. settings.py EMAIL_HOST = config('EMAIL_HOST') EMAIL_HOST_USER = config('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') EMAIL_PORT = config('EMAIL_PORT', cast=int) EMAIL_USE_TLS = config('EMAIL_USE_TLS', cast=bool) DEFAULT_FROM_EMAIL = config('DEFAULT_FROM_EMAIL') newsletter/views.py We want to start sending emails, Import send_mail . python from django.shortcuts import render from .forms import NewsUserForm from . models import NewsUsers from django.core.mail import send_mail def newsletter_subscribe(request): if request.method == 'POST': form = NewsUserForm(request.POST) if form.is_valid(): instance = form.save(commit=False) #we do not want to save just yet if NewsUsers.objects.filter(email=instance.email).exists(): print('your email Already exists in our database') else: instance.save() print('your email has been submitted to our database') send_mail('Laughing blog tutorial series', 'welcome', 'mail@achiengcindy.com',[instance.email], fail_silently=False) else: form = NewsUserForm() context = {'form':form} template = "newsletter/subscribe.html" return render(request, template, context) Conclusion "What is the difference between Bound and Unbound Form?" A boundform has data associated with it. Unboundform has no data associated with it.It is either empty or contain default values.To check if a form is bound use is_bound()method.In our case form.is_bound()return false while passing even an empty dictionary binds the form. form.is_bound({})returns true We have successfully created a basic newsletter app and managed to send a welcome message to new subscriptions.The code for this tutorial is available on Github . In the next tutorial, we will continue to build our newsletter app by making it more readable! Connect with me on Twitter This post was originally posted on achiengcindy.com Discussion Great work and simple explanation and concept, all lessons were put on my list I can't find the next toturial Hi Stylop, I apologize for responding late had issues with my account.I will update soon
https://practicaldev-herokuapp-com.global.ssl.fastly.net/achiengcindy/laughing-blog-tutorial-series-part-2--creating-a-newsletter-app-3dph
CC-MAIN-2020-50
refinedweb
2,249
58.99
NAME sigprocmask - manipulate current signal mask LIBRARY Standard C Library (libc, -lc) SYNOPSIS #include <signal.h> int sigprocmask(int how, const sigset_t * restrict set, sigset_t * restrict oset); DESCRIPTION The sigprocmask() system call examines and/or changes the current signal mask (those signals that are blocked from delivery). Signals are blocked if they are members of the current signal mask set. If set is not null, the action of sigprocmask() depends on the value of the how argument. The signal mask is changed as a function of the specified set and the current mask. The function is specified by how using one of the following values from SIG_BLOCK The new mask is the union of the current mask and the specified”).
http://manpages.ubuntu.com/manpages/maverick/man2/sigprocmask.2freebsd.html
CC-MAIN-2015-14
refinedweb
120
60.14
Aside: CordovaWebView allows you to use the PhoneGap/Cordova component in a larger Android application. Extending the DroidGap class is no longer necessary if you are providing your own Activity that embeds a CordovaWebView. However, you can continue to extend the DroidGap class to give yourself a leg up. As a result of removing those methods Plugins who were dependent on them being implemented by CordovaInterface ctx member of the Plugin class were left wondering what do I need to do to get my Plugin to compile with PhoneGap 1.9.0. Well we are sorry for that, it could have and should have been handled better. When PhoneGap 2.0.0 drops we are changing ctx from a CordovaInterface to a LegacyContext class. LegacyContext is a new class that we've introduced that bridges the old CordovaInterface API to the new CordovaInterface API. This means that any Plugin that worked in 1.8.1 should continue to work in 2.0.0 without modification. This doesn't mean that LegacyContext will be around forever. In fact the class is already deprecated. We will be publishing an Plugin upgrade guide to help developers update their Plugins to the new API. I'll also be going through my plugins (ChildBrowser, TTS, VideoPlayer) and updating the repo to have 1.8.1 and 1.9.0 versions of the Plugins for people to reference. The ctx member from the Plugin class will be going away in a couple of point releases as it has been replaced by a cordova member which is an instance of CordovaInterface. For those of you who want to get a jump start on updating your plugins here is a brief guide. - ctx.getContext() replaced with cordova.getContext() - ctx.startActivity() replaced with cordova.getActivity().startActivity() - ctx.getSystemService() replaced with cordova.getActivity().getSystemService() - ctx.getAssets() replaced with cordova.getActivity().getAssets() - ctx.runOnUiThread() replaced with cordova.getActivity().runOnUiThread() - ctx.getApplicationContext() replaced with cordova.getActivity().getApplicationContext() - ctx.getPackageManager() replaced with cordova.getActivity().getPackageManager() - ctx.getSharedPreferences() replaced with cordova.getActivity().getSharedPreferences() - ctx.unregisterActivity() replaced with cordova.getActivity().unregisterActivity() - ctx.getResources() replaced with cordova.getActivity().getResources() - import com.phonegap.api.* replaced with import org.apache.cordova.api.* 59 comments: Hi, first post here. I would like to thank you for phonegap, a easy way to make apps for android with no idea of java, yet... Is extending DroidGap going to be depecrated? PD: My english sux ;) thanks Simon :) really helpful! For video player in android only we can play the files from SDcard and Youtube, Not able to play the video file from Assets! May be I have to programmatically move the file to sdcard or any solutions for that? @Joan No, DroidGap is not being deprecated. The LegacyContext class will be deprecated once we get the Plugins updated to the new API. @Subrahmanya The latest version of the VideoPlayer copies the file out of assets and onto the SD Card so the video can be player. So, yes you should be able to package a video in the assets folder and have it played by the Plugin. Replacing ctx.getContext() with cordova.getContext() still gives deprecated warning - "The method getContext() from the type CordovaInterface is deprecated". Any suggestions? Thank you. @Darrin Don't worry about that one. We put getContext back in the interface but the deprecation log needs to get removed. Thanks Simon :) I tried with updated VideoPlay.java got some Error !!!) @Subrahmanya Yup, that is that is a bug in 1.9.0 that has been fixed in 2.0.0. Use getActivity in the mean time. Hi Simon :)Error While running new android_asset VideoPlayer.java (updated to Phonegap 1.9) sample with android_asset videoplay!!) K thanks Simon, I tried to use ctx.getContext() and ignoring the deprecated warning but I get the following error: at org.apache.cordova.DroidGap.getContext(DroidGap.java:944) @Subrahmanya and @Darren Yes, that stack overflow exception is being caused by a circular reference in 1.9.0. Honestly, 2.0.0 RC1 is out now and 2.0.0 is out Friday and it'll be much better than trying to patch 1.9.0 right now. Okay, I will try RC1 and see what happens. Thank you! Hi Simon, I am now using 2.0.0 RC1 and I get the following error when I call window.plugins.childBrowser.showWebPage(): 07-16 12:08:08.267: I/Web Console(11555): Error: Status=2 Message=Class not found at Simon, I determined why I was getting the "Class not found at file..." error. It was because I named my childBrowser plugin with "cordova" instead of "phonegap". I thought I would need to change all name references to cordova but this was not the case here. Therefore, in my plugins.xml file I now have this and it works. phonegap 2.0.0 does not work with Android Barcodescanner plugin. Generates an error "barcodescanner module not found in cordova 2.0.0. Any ideas? Worked on previous versions of IOS. Simon, Are you going to update the BarcodeScanner plugin too? I came over from your old post: Thanks, George @George My plan is to give all the plugins a look see on 2.0.0 as soon as possible. I can't think of a reason why it wouldn't work but I may have missed a backwards compatibility point on that plugin. @Howard I'm confused are you talking about the Android Barcode Scanner or the iOS one? You mention both. I am talking about the Android Barcode Scanner plugin. I thought it waas important that you know that I have this code running on older versions on IOS. Sothat it is clear the problem is encountered on Android using 2.0.0. I can not use 1.9.0 because of another problem. Thanks! @Howard Like I told George in an earlier comment I hope to get a chance to look at it this week. Thanks! I would appredciate it if you let me kow when you have something that works on 2.0.0. I aalso use the Barcodescanner and have similar problems which are probably related. Thanks! Hi Simon, I am new to Android and I want to get childBrowser in my app.In my eclipse I have Android4.0.3 vesion.I installed MDS Applaud to the eclipse and followed the link but the proble i when I run the project I am getting the error ctx cannot be resolved..Please help me simon to resolve this.. Thank you and regards Ashwini Hi, So with the switch to 2.0.0 from the CordovaCtx to LegacyContext did we lose the ability to start services in Plugins? Legacy ctx does not have the startService() or bindService() calls available... Thanks. @broody Crap, no that is missing from the interface. I can add it for 2.1.0 but in the meantime you'll need to use cordova.getActivity().startService/bindService. @Ashwini Take a look at some of my other posts which include an updated ChildBrowser plugin for 2.0.0. Hi Simon, We have implemented the Phone Gap Android Push Notification using GCM, and referred from with Phone Gap 1.7.0 version. Now if I want to port it to 1.9.0 getting this below error, I read your blog where you mentioned that we need to change ctx. to cordova. but still the same error comes, Is the Phone gap 1.9.0 is stable version ? What all modification we have to do for working in 1.9.0. Error : “FATAL EXCEPTION : Thread-19, at org.apache.cordova.DroidGap.getContext(DroidGap.java)” Warm Regards MohammedIrfan @Zhakaasssss Switch to getActivity. There is a bug in 1.9.0 that getContext will cause a stack overflow error. Hi, i am newbie to phonegap I am working on Plugins for android i was trying with the localNotification plugin... Its having a class Alarm and with constructor public AlarmHelper(Context context) { this.ctx = context; } now from i am creating an object for the class and passing LegaacyContext of Cordova as an argument but the constructor of Alarm is having Context of Android API alarm = new AlarmHelper(this.ctx); @MD SIRAJUDDIN NOORUDDIN What's the question? Hi Simon Mac Donald, my question is how to get the plugin result into our app web components such as Html ? @MD SIRAJUDDIN NOORUDDIN You are not providing enough info. Regardless, check out the plugin development guide: In phonegap 2.0 how to display a wait cursor for java file of my plugin.Previously i was doing that... droidGap.spinnerStart("","Loading");. But i think they have remove this method. @Disasters Well that method is still there and it is public so I'm not sure why it wouldn't work for you as long as you have a reference to the DroidGap class. You could switch to using the JavaScript alternatives: navigator.notification.activityStart(title, message); navigator.notification.activityStop(); I also noticed that ctx.getContentResolver() should be changed to cordova.getActivity().getContentResolver() Android 4.0.3 Zebracrossing 2.1 Cordova 2.0.0 In BarcodeScanner I use Zxing IntentIntegrator tintegrator = new IntentIntegrator(tempact); Which works great but I have to pass in the Activity so that public void onActivityResult(int requestCode, int resultCode, Intent intent) { Method will execute on return from Zxing scanning Problem is that BarcodeScanner is a Java class extends Plugin but it's not an Activity. I want the Zxing IntentIntegrator to come back to BarcodeScanner Class so that I can execute the Encode and this.success just like is in the Plugin Class. When I put in my MainActivity to IntentIntegrator, it works to come back there in onActivityResutls but can't get back to Plugin to execute success. @guitar99 You need to use the following code from your Plugin to get an activity: this.cordova.getActivity(); but you can see how to call an activity from a plugin using: this.cordova.startActivityForResult(); in: I tried the barcode demo app and it is not working. this is the error "Cannot read property 'barcodeScanner' of undefined" Its working on samsung galaxy y running android gingerbread but not working in samsung galaxy tab running android froyo. What should I do to make it work in android froyo? @reineskye25 I don't have a 2.2 device but it is working in the froyo emulator. Hi Simon :) I am new to phonegap development. I m trying to implement a video module using cordova 2.1.0.. Here i can hear the sound from my video but not able to view it. Can u plss help me out. here is the code which i m using.. var video = document.getElementById('example_video_1'); video.addEventListener('click',function(){ video.play(); },false); Thanks in advance :) @vinutha v What version of Android are you using? There are many problems with the video tag on Android. Did you read my many posts on the subject on this blog? Also, if you hear the audio but not the video you are probably trying to play an unsupported video type. See this table: hi Simon, In phonegap local notification plugin for android cancelAll is not working. i am using cordovo 2.1 any idea..?? @Amit Kumar Sorry, I haven't used it in awhile. You should ask the plugin owner/originator. Hi Simon, Thanks a lot for your very useful Tutorials and great efforts. I'm using the Android Local Notifaction plugin now, but I have a problem with this line: public PluginResult execute(String action, JSONArray optionsArr, CallbackContext callBackId) { I can't change it to public boolean execute(String action, JSONArray data, CallbackContext callbackContext) { as it shows an error with return type If I did that, so is there a solution ? Hi Simon, I need your help on get phone number from Andorid PhoneGap, I have tried some options on your blog, but no luck, Plz find sending code and Error, Let me know your Suggestions, Thanks in Advance. ========================== This is my CODE ========================== package com.vasu.sms; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.telephony.TelephonyManager; import android.util.Log; import org.apache.cordova.api.*; import org.apache.cordova.api.Plugin; import org.apache.cordova.api.PluginResult; import org.apache.cordova.api.PluginResult.Status; /** * @author Guy Vider * */ public class MyPhoneNumberPlugin extends Plugin { @Override public PluginResult execute(String action, JSONArray data, String callbackId) { Log.d("MyPhoneNumberPlugin", "Plugin called"); PluginResult result = null; try { JSONObject number = getMyPhoneNumber(); Log.d("MyPhoneNumberPlugin", "Returning "+ number.toString()); result = new PluginResult(Status.OK, number); } catch (Exception ex) { Log.d("MyPhoneNumberPlugin", "Got Exception "+ ex.getMessage()); result = new PluginResult(Status.ERROR); } return result; } private JSONObject getMyPhoneNumber() throws JSONException { Log.d("MyPhoneNumberPlugin", "at getMyPhoneNumber"); JSONObject result = new JSONObject(); TelephonyManager tm = (TelephonyManager) cordova.getSystemService(Context.TELEPHONY_SERVICE); String number = tm.getLine1Number(); if(number.equals("") || number == null) { Log.d("MyPhoneNumberPlugin", "We're on a non-phone device. Returning a hash of the UDID"); number = md5(tm.getDeviceId()).substring(0, 10); } Log.d("MyPhoneNumberPlugin", "Phone number=" + number); result.put("phoneNumber", number); return result; } private++) hexString.append(Integer.toHexString(0xFF & messageDigest[i])); return hexString.toString(); } catch (NoSuchAlgorithmException e) { Log.d("MyPhoneNumberPlugin", e.getMessage()); } return ""; } } ====================== This is Error ====================== The method getSystemService(String) is undefined for the type CordovaInterface @Rana Mahdy It is not sufficient to just change the method signature. You need to go through and replace everywhere you return a PluginResult with a call to sendPluginResult. For example: callbackContext.sendPluginResult(new PluginResult(status, result)); Then you need to return a boolean variable that in most cases should be true to say that the action was valid. @Vasu Nanguluri Lots of people seem to be asking for this functionality so I'm going to do a full blog post on it. To answer your question, change: TelephonyManager tm = (TelephonyManager) cordova.getSystemService(Context.TELEPHONY_SERVICE); to: TelephonyManager tm = (TelephonyManager) cordova.getActivity().getSystemService(Context.TELEPHONY_SERVICE); Hi, i'm trying to install the LibraryProject of Barcode Plugin for PhoneGap Android. eclipse give an error in the BeepManager.java file "beep cannot be resolved or is not a field" line 97 Java Problem how to solve it? Thanks Hi. I wrote a simple plugin to call a function in my MainActivity. But it never gets called. I use this to do it from my plugin.java file MainActivity ma = (MainActivity)this.cordova.getActivity(); ma.customFunctionCalled(); Is that the right way to get a handle on the MainActivity objext? I debugged it and it doesnt get past the first line above. Using cordova 2.1. @detoxnet There is no reason why that shouldn't work. I just did a quick test with 2.3.0rc2 and it worked great for me. @Pozz I haven't ever seen that error and there is no field called "beep" in BeepManager.java so I'm having a hard time figuring out where it could be coming from. Hi simon , I am using 2.4.0 , trying to implement the PushPlugin via Eclipse for Andriod. When I build the project I get the following error : The method getContext() is undefined for the type CordovaInterfac PushPlugin.java Any suggestion would be very much appriciated @Lori Azrad The API has changed somewhat. I think you are looking for: this.cordova.getActivity().getApplicationContext() Hi Simon, I am creating a share plugin with the help of this url: I am using phonegap 2.9 version and have made changes according to that in ChildBrowser.java file however still getting errorslike one of in this line intent = new Intent().setClass(this.ctx, org.apache.cordova.DroidGap.class); Error: ctx cannot be resolved or is not a field What should I use to replace this.ctx . Please reply soon, thanks in advance. @Nitin Ajmani It's right there in the post. this.ctx becomes this.cordova or this.cordova.getContext() depending on what you need. Hi Simon, I have implemented this.cordova and this.cordova.getContext() in place of this.ctx however it is not working. I am a beginner to Android Applications and I want to implement Share button functionality to my Phonegap Android App however I am not successful in many attempts. I am using Phonegap 2.9.0 and Android Developer Tools version Build: v21.1.0-569685 . Can you please help me to add share button functionality for Facebook, Twitter, Gmail, SMS etc using phonegap. Your help is really appreciated. Thank You. @Nitin Ajmani Hello Simon, I started using PhoneGap 3 days back and I am so liking it. I am planning to integrate my PhoneGap app with Databse.com and luckily they have some very nice blogs out on there on the web for the same. I am using cordova 1.7.0 and as I got childBrowser.java in my source folder, I get several errors reading 'cordova cannot be resolved or is not a field'. Wondering why would this happen and no substantial posts for these on the web. Please help @supriya hirurkar Make sure you are using the right version of ChildBrowser.java with your version of PhoneGap. We broke the plugin api along the way so different versions of the ChildBrowser were needed.
http://simonmacdonald.blogspot.com/2012/07/phonegap-android-plugins-sometimes-we.html
CC-MAIN-2015-35
refinedweb
2,863
52.15
Here's a list of the most noteworthy things in the RAP 2.2 release which is available for download since December 20, 2013. You may also check the New and Noteworthy for RAP 2.0 and the RAP 2.0 migration guide. We introduced row templates, a new feature that allows you replace the column layout model of a table ore tree with a custom presentation. Templates consist of cells that can be freely arranged. A cell can display a text or an image from the table item, but also static content. To apply a row template on a Table or a Tree, use the setData() method with the new constant RWT.ROW_TEMPLATE as key: Table table = new Table( parent, SWT.FULL_SELECTION ); // Add as many columns as a single table item will have texts/images: new TableColumn(); Template template = new Template(); // ... create template cells here, the set the template: table.setData( RWT.ROW_TEMPLATE, template ); To position a cell, you have to set exactly two horizontal and two vertical dimensions (two out of left, right, and width and two out of top, bottom, and height). Cells can also be selectable. When a selectable cell is clicked it does not mark the the item itself as selected. Item selection is still possible (clicking anywhere but on a selectable cell), but only visualized if the SWT.FULL_SELECTION flag is set. Row templates are currently supported by Tree and Table, but we plan to apply this concept on other widgets in the future. All details are covered in the Developer's Guide article on Tree and Table Enhancements. The FileUpload widget now allows selecting and uploading multiple files at once in HTML5 enabled browsers. To enable this feature, create the widget with the SWT.MULTI style flag like this: FileUpload fileUpload = new FileUpload( parent, SWT.MULTI ); To obtain the filenames from the widget, the method getFileNames has been introduced. The method getFileName still exists and will return the first selected file. In browsers that do not support this feature (such as Internet Explorer 8) the MULTI flag will simply be ignored. The RAP Incubator file upload component and the FileDialog implementation have been updated to make use of this new feature. The look and feel of tooltips has been improved and fine-tuned: The ToolTipText property and the ToolTip widget now support markup, including hyperlinks. added the possibility to specify a number of items to be pre-loaded by the client. When scrolling the table in small steps, pre-loaded items will appear immediately. Example: Table table = new Table( parent, SWT.VIRTUAL ); table.setData( RWT.PRELOADED_ITEMS, new Integer( 10 ) ); With this snippet, in addition to visible items in the Tree/Table client area, another 10 items (above and below) will be resolved and sent to the client. The ClientScripting project has been graduated from the incubator and is now included in the RAP core as “RWT Scripting”. Using the new ClientListener class, it is possible to handle some events directly on the client without the usual latency caused by HTTP requests. The following widgets support ClientListener: Supported events are: Consult the new Developers Guide Scripting article for information on ClientListener, and the WebClient API reference to find out what widget methods are available in RWT Scripting. Note: The ClientScripting incubator project is no longer compatible with RAP 2.2 and must be used only with older RAP versions. If you port code based on the incubator ClientScripting to RAP 2.2 Scripting, please note that the namespace for ClientListener has been changed to org.eclipse.rap.rwt.scripting. Also, the number of supported widgets and methods has been reduced, but in return the properties are now always synchronized back to the server. Data attached to an SWT widget can now be transferred to the client to access it in scripting. To do so, the key for that data has to be registered with WidgetUtil.registerDataKeys. Example: WidgetUtil.registerDataKeys( "foo" ); widget.setData( "foo", "bar" ); A ClientListener can use the data like this: function handleEvent( event ) { var data = event.widget.getData( "foo" ); } This feature can also be used to access other scriptable widgets within a ClientListener. Instances of ApplicationContextListener can be attached to an application context to receive a notification before the application context is destroyed. The JavaScriptLoader implementation has been improved in the following aspects: We've polished the look and feel of tooltips in the default theme (see above). To do so, a new theming element has been introduced: Widget-ToolTip-Pointer. This element has a single property background-image and four states, up, down, left, and right. This property allows to attach a pointer image to one edge of the ToolTip. The state indicates the direction that the ToolTip points to. The image should match the background and/or border color of the ToolTip theming. A full set of four images would be defined like this: Widget-ToolTip-Pointer { background-image: none; } Widget-ToolTip-Pointer:up { background-image : url( tooltip-up.png ); } Widget-ToolTip-Pointer:down { background-image : url( tooltip-down.png ); } Widget-ToolTip-Pointer:left { background-image : url( tooltip-left.png ); } Widget-ToolTip-Pointer:right { background-image : url( tooltip-right.png ); } It is now also line" ); The default value is center. The theming was extended in several other places: There has long been an issue with RAP applications deployed as .war files that could not be properly stopped or undeployed and even prevented the servlet container from shutting down. These problems have been fixed. Stopping and undeploying RAP applications works as expected now. An overview of what changed in the RAP protocol can be found in the RAP Wiki. This list shows all bugs that have been fixed for this release. To assist you with the migration from RAP 2.x (or 1.x) to 3.0, we provide a migration guide.
http://www.eclipse.org/rap/noteworthy/2.2/
CC-MAIN-2018-22
refinedweb
971
57.57
Developing Linq to LLBLGen Pro, Day 5 (This is part of an on-going series of articles, started here) Consuming Expression trees, back to Special Case programming? I'll show you 5 different queries and what their expression tree looks like in text (tested on Linq to Sql, so you'll see Table references) Query A: // C# var q = from c in nw.Customers select new { Name = c.ContactName, Orders = from o in nw.Orders where o.CustomerID == c.CustomerID select o };gives: // Expression tree .ToString() output Table(Customer).Select(c => new <>f__AnonymousType0`2(Name = c.ContactName, Orders = value(WindowsFormsApplication1.Program+<>c__DisplayClass0).nw.Orders.Where( o => (o.CustomerID = c.CustomerID)))) In case you wonder... the WindowsFormsApplication1.Program namespace is the test app namespace I used to run the query with. As you can see, a bug pops up: instead of referring to Table(Order), it refers via the application to the context.Orders for the Where clause. This will be a pain to correct, I'm sure. Also there's just 1 Select call, while there are two in the query. This will be a pain too, but more on that below. Query B: // C# var q = from c in nw.Customers let x = c.Region ?? "Undef" where (c.Country != "Germany") && x != "Undef" select new { CompName = c.CompanyName };gives: // Expression tree .ToString() output Table(Customer).Select(c => new <>f__AnonymousType0`2(c = c, x = (c.Region ?? "Undef"))).Where( <>h__TransparentIdentifier0 => ((<>h__TransparentIdentifier0.c.Country != "Germany") && (<>h__TransparentIdentifier0.x != "Undef"))).Select(<>h__TransparentIdentifier0 => new <>f__AnonymousType1`1(CompName = <>h__TransparentIdentifier0.c.CompanyName))Yeah, I also wondered about the transparent identifier, but it's the reference to a derived table-like sub result if you look closely. See also the C# 3.0 spec, where this is explained in detail. Query C: // C# var q = from c in nw.Customers where c.Country != "USA" select new { CompName = c.CompanyName };gives: // Expression tree .ToString() output Table(Customer).Where(c => (c.Country != "USA")).Select(c => new <>f__AnonymousType0`1(CompName = c.CompanyName)) Query D: // C# var q = from c in nw.Customers select c;gives: // Expression tree .ToString() output Table(Customer).Select(c => c) Query E: // C# var q = from c in nw.Customers where c.Country=="USA" select c;gives: // Expression tree .ToString() output Table(Customer).Where(c => (c.Country = "USA")) Confused? So am I. Yesterday I spend some time on writing code for the execution of queries, setting up the proper LLBLGen Pro elements such as live transactions and the like so they're usable with the query objects so deferred execution still would take place inside a transaction if required (so SqlServer won't deadlock on you), and I also spend some time analyzing what to do with the Expression tree nodes. Yesterday, it occured to me that it was something like LR(1) parsing: you handle an element with the lookahead info and place the results on the stack for the caller to process further. If the caller sees it has enough info to reduce the elements on the stack, it reduces all those elements and handles it further, placing the result of the reduction onto the stack again. However, to make that work, the input has to be deterministic, i.e.: you shouldn't wonder in state N in what scope you're in, started in state N-M. Now take a look at queries D and E. D has a Select call, E doesn't. Why on earth doesn't E have a select call? This is undeterministic. What it should have been is: // What should have been E's correct structure Table(Customer).Where(c => (c.Country = "USA")).Select(c=>c) The expression tree created by the compiler is wrong, because the expression tree parser in the Linq provider has to decide what to leave out, however the compiler decides that for me now. The sad effect of this is that I now have to add code which has to guess what the intention was: when no Select call is present, apparently one still wants to do a select, with the native projection. This is doable, although it's a form of 'special case programming': as a provider developer you now have to anticipate on a special case: namely the one where there's no Select call in the expression tree despite the fact that there is a select statement in the query (there always is). With the occurance of a special case, one has to wonder: what kind of other special cases are there, which are unknown to me now? And also: if the compiler tries to be clever, why isn't it more clever so parsing the nodes is easier and straight forward? The main pain with writing the Linq provider isn't the code, it's the unknown voodoo which takes place inside the compiler which makes it emit calls to Queryable(Of T) extension methods which build apparently odd expression trees at runtime. To be able to write a proper Linq provider, you have to understand the intention of the query. There's no other thing to look for. You're handed an expression tree. So by parsing that tree, you try to re-build the query the developer wrote in C# (of VB.NET) which lead to this expression tree. If you solely look at elements inside the tree, you'll run into problems with things which have effect on various elements of the tree, like a join into with DefaultIfEmpty() calls to signal a left join (yes, Linq's join syntax is that cumbersome). If you know the intention, you can produce the proper query code on all databases you support via your provider and also you can optimize the query when necessary. It's now unclear what lead to which expression tree subtree, so in other words: it's impossible to deterministically determine what the meaning is of a subtree in the expression tree, at least at this point where documentation about why the expression tree looks like the way it does is non-existent. It's not hard to write code which can handle trees like the ones resulting from queries C, D and E. The main issues arise when someone introduces a line with 'let' like in query B or a second select (projection) in the main projection as in query A. Take a closer look at the differences between query A and B. You'll notice that although query A has two select statements in the query, it has just one Select method call in the expression tree, while in query B, it has two Select method calls while there's just 1 select statement in the query. Query B, with its two Select method calls gives another problem: what to do with the results? Does it have to be projected onto new types, or onto entities? Projecting onto entities is different, as shorter paths exist inside the O/R mapper core, simply because one doesn't set entity values through properties when you're fetching (to avoid triggering validation logic which shouldn't trigger at fetch time for example). However, with two (or potentially more) Select method calls exist, which one decides what is done with the end-result? Again, special case programming and not deterministic code: to handle a Select method call, one has to know the scope it is in: it can't decide based on its own parameters and the lookahead what to do: which one is the end-projection? The last one? But do you know that when you run into the first one? No, so you have to seek through the whole tree for another select. If that's not found, you know you're the only one. So doing things based on what you see in node X isn't going to work. In LR(n) parsers, the stack top is important too. So this could help in the Select method handler to determine if it should decide the end projection or if it should reduce to a derived table. But this could lead to a shift/reduce conflict , which one normally solves by either extending the lookahead or changing the grammar (no can do) or by adding a special case (not recommended). I'm sorry if I sound a litle bitter, but this whole Linq expression tree parsing system is overly complicated while this isn't necessary. I wrote my own LR(n) parser engine and action/goto generators, I know what parsing trees means, but with Linq expression trees it's like with a box of chocolates, isn't it, Forest... As I said earlier, what you want with code like this is to be able to proof that the code is correct. As there are 'special cases' popping up left and right, being able to proof something is correct is impossible, unless you have deep knowledge of the inner workings and know why the tree looks like the way it does. Without that knowledge, I can't optimize query A. Query A can be done with 2 queries in generic code (or one, if you cheat, but that leads to special code for single path graphs). However to determine this situation is seen inside the query is hard. Sure, you can look at the expression tree of query A and take a guess that if you see something like that it will be optimizable. However, Linq to Sql (and also the entity framework) will execute a myriad of queries with query A (number of customers + 1). I'll try to find a way to optimize it, but that depends on whether I can recognize the subquery/subqueries in a normal fashion. This is harder than you might think, as the subquery might or might not have a Select method call (and Microsoft, with knowledge of the inner workings of the compiler didn't know how to optimize it) Yes, I do wonder if it wouldn't be simpler if I just got the linq query as text and did the parsing myself. Anyway, I'll start simple, with queries D, E and then C. I've the whole mechanism in place now so I can now add dispatch routines to my Expression node dispatcher for the various expression node types within the range of BinaryExpression for example, so I'll move forward with my LR(1) (so 1 lookahead) lookalike engine, which is hopefully enough to handle the cases it has to fight with. It's likely I need tree traversal code for cheating in situations where the 1-lookahead isn't enough. This is cumbersome though and makes things fragile.
http://weblogs.asp.net/fbouma/developing-linq-to-llblgen-pro-day-5
CC-MAIN-2015-40
refinedweb
1,776
63.29
The high quality scaler imported as part of bug 486918 is capable of upscaling, but we only use it for downscaling. To see what results are like, you can modify RasterImage::CanScale in image/src/RasterImage.cpp to ignore aScale; you'll want to investigate both quality and memory usage, because we will hold on to the larger upscaled image. I'm working on this one :) Hello Dae and Joe. Are you working on a patch locally? I would be happy to help if you don't have time to work on it. Created attachment 728669 [details] [diff] [review] Patch to use high-quality scaler both for downscaling and upscaling. Patch to use high-quality scaler both for downscaling and upscaling. Running the quality and memory tests now. Created attachment 728670 [details] The difference in quality of the scaled image is noticeable As you can see in this image the difference of quality is noticeable. Created attachment 728671 [details] memory usage comparison between scalers The memory usage is smaller with the high-quality scaler. Created attachment 728693 [details] [diff] [review] quality scale up as well unless target size is bigger than 10mb Added some code to contain the situation where the upscaling can get too big in the memory. When we use the high quality scaler the target size is stored in memory, and not in the GPU like the standar scaler, so we need to control this. and by standard scaler I meant Imagelib. Comment on attachment 728693 [details] [diff] [review] quality scale up as well unless target size is bigger than 10mb Review of attachment 728693 [details] [diff] [review]: ----------------------------------------------------------------- This patch looks great. While I can't give it r+ yet (r+ for me means that it can go into mozilla-central as long as it passes Try[1] and any style nits I have are addressed), it's a very strong first patch. Congratulations! When you address the below issues, upload another patch and ask me for review. I'll give it a once-over and then push it to Try for you. Note: In future, you'll want to flag someone (for example, me!) for review below. We were in the middle of a conversation, so in this case it didn't matter, but in general it's very easy for this sort of thing to get lost in the deluge of bugmail people get every day. has a lot more information. :) 1. ::: image/src/RasterImage.cpp @@ +2929,2 @@ > { > + int32_t scaled_size; In C++ this declaration can be anywhere, so you may as well put it down where you assign to it. @@ +2934,1 @@ > return false; Here, surround the if's body with {} (like below); even though it's only one line, it *looks* like more than one line, so it's safer to put the braces in. @@ +2935,5 @@ > > + if (scale.width > 1.0 || scale.height > 1.0) { > + // To save memory don't quality upscale images bigger than 10mb. > + scaled_size = mSize.width * mSize.height * scale.width * scale.height; > + if (scaled_size > 2621440) This part is going to need to change, likely to a preference value. You can look at how the preference "image.high_quality_downscaling.min_factor" is handled, and do exactly the same thing. You'll also want to have this pref be stored in bytes, which means multiplying by 4 above. And as you have written this, it'll give us a warning because we're implicitly converting from a double to an integer. Silence that warning by explicitly casting. @@ +3031,4 @@ > frame = mScaleResult.frame; > userSpaceToImageSpace.Multiply(gfxMatrix().Scale(scale.width, scale.height)); > > + // Since we're switching to a scaled image, we need to transform the Looks like maybe you accidentally changed some whitespace here? Ah yes! I agree in all fronts. I posted this to see if the logic and use of data made sense to you. I will move scaled_size to a preference value. Does the size limit (assuming size calculation for RGBA) means that a user with a 2560x1600 display will rarely have the HQ upscaler kick in? John, we can make the limit bigger. What value do you suggest? I think 15MB should be enough to cover all cases, including 2560x1600 displays. John, with the comment Joe made about multiplying the pixels by 4 to make it bytes. The value to compare against is 10,485,760. This is higher than the amount of pixels in the screen size you mention. Which is 4,096,000. 15,728,640 bytes (15mb) / 4 (bytes per pixel) = 3,932,160 Your target display of 2560x1600 has 4,096,000 pixels. We are short still by a little. Joe and John, how about 20mb? As long as there's a limit, we can always tweak it later. Sounds good to me. Created attachment 728695 [details] [diff] [review] quality scale up as well unless target size is bigger than 20mb Fixed with review comments from Joe. Comment on attachment 728695 [details] [diff] [review] quality scale up as well unless target size is bigger than 20mb Review of attachment 728695 [details] [diff] [review]: ----------------------------------------------------------------- You need to add the pref to modules/libpref/src/init/all.js as well. Once you've done that and reuploaded your patch, I'll push this to try for you! ::: image/src/RasterImage.cpp @@ +70,4 @@ > static bool gHQDownscaling = false; > // This is interpreted as a floating-point value / 1000 > static uint32_t gHQDownscalingMinFactor = 1000; > +// The the amount of pixels in a 20mb image s/The the amount/The number/ Also change "20 mb" to a number of megapixels; possibly 20 :) Created attachment 729059 [details] [diff] [review] new version of the patch with review fixes Thanks a lot for the review! :) I have made the changes you mentioned. 20 megapixel is 80 mb. So changed it up to 80 mb and updated the comment to 20 megapixel. Sounds very big to me but that is what you suggested, as far as I understood. Created attachment 729069 [details] [diff] [review] fixed comments to specify size in megapixels and resolution Done :) Comment on attachment 729069 [details] [diff] [review] fixed comments to specify size in megapixels and resolution Review of attachment 729069 [details] [diff] [review]: ----------------------------------------------------------------- Looks great! I've pushed it to try: If that all comes back clean, you'll want to request checkin-needed as a keyword on this bug, and someone will get to it after not too long. To do so, be sure your patch is formatted correctly: (Incidentally, this patch will also need to be rebased on top of current mozilla-central.) Note that, when you're fixing nits or other review comments, you don't have to request another review (from me, anyways); r+ means "I trust you to make these changes and commit." ::: image/src/RasterImage.cpp @@ +70,4 @@ > static bool gHQDownscaling = false; > // This is interpreted as a floating-point value / 1000 > static uint32_t gHQDownscalingMinFactor = 1000; > +// The amount of pixels in a 5 megapixel decoded image. nit: number of pixels. Cool! I forgot to mention that I rebased the commit on current mozilla-central. Since there was a change yesterday applied to the same file, and the number lines of the patch didn't match anymore. Created attachment 729082 [details] [diff] [review] s/amount of pixels/number of pixels Thanks for all the help! In both explaining the process and reviewing the patch :) To whoever checks this in, can you confirm with me please that you can pull the patch description/author easily from the git formatted patch? Comment on attachment 728669 [details] [diff] [review] Patch to use high-quality scaler both for downscaling and upscaling. >diff --git a/image/src/RasterImage.cpp b/image/src/RasterImage.cpp >index 2546511..28be3c8 100644 >--- a/image/src/RasterImage.cpp >+++ b/image/src/RasterImage.cpp >@@ -2925,12 +2925,8 @@ RasterImage::SyncDecode() > } > > static inline bool >-IsDownscale(const gfxSize& scale) >+IsScaled(const gfxSize& scale) > { >- if (scale.width > 1.0) >- return false; >- if (scale.height > 1.0) >- return false; > if (scale.width == 1.0 && scale.height == 1.0) > return false; > >@@ -2946,8 +2942,9 @@ RasterImage::CanScale(gfxPattern::GraphicsFilter aFilter, > // We don't use the scaler for animated or multipart images to avoid doing a > // bunch of work on an image that just gets thrown away. > if (gHQDownscaling && aFilter == gfxPattern::FILTER_GOOD && >- !mAnim && mDecoded && !mMultipart && IsDownscale(aScale)) { >+ !mAnim && mDecoded && !mMultipart && IsScaled(aScale)) { > gfxFloat factor = gHQDownscalingMinFactor / 1000.0; >+ > return (aScale.width < factor || aScale.height < factor); > } > #endif >@@ -3024,7 +3021,7 @@ RasterImage::DrawWithPreDownscaleIfNeeded(imgFrame *aFrame, > frame = mScaleResult.frame; > userSpaceToImageSpace.Multiply(gfxMatrix().Scale(scale.width, scale.height)); > >- // Since we're switching to a scaled image, we we need to transform the >+ // Since we're switching to a scaled image, we need to transform the > // area of the subimage to draw accordingly, since imgFrame::Draw() > // doesn't know about scaled frames. > subimage.ScaleRoundOut(scale.width, scale.height); Thanks Matt :) \o/ First patch I accidentally botched a few lines of the patch; pushed a follow-up fix: Which version of Firefox first implemented the supplied patch? I've just noticed that the image quality when upscaling is indeed notably improved (Great work!), but upscaling still isn't excellent for stuff like comic strips and pixel art (Introduces some blur still). Is it at all possible to get a optional nearest neighbor upscaler as that would work best for comic strips and pixel art amongst other stuff. Thanks. The patch was merged in 2013-03-26. So when Firefox 23 was in nightlies.
https://bugzilla.mozilla.org/show_bug.cgi?id=795376
CC-MAIN-2017-09
refinedweb
1,568
63.9
Here are the most popular ways to make an HTTP request in JavaScript JavaScript has great modules and methods to make HTTP requests that can be used to send or receive data from a server side resource. In this article, we are going to look at a few popular ways to make HTTP requests in JavaScript. Ajax is the traditional way to make an asynchronous HTTP request. Data can be sent using the HTTP POST method and received using the HTTP GET method. Let’s take a look and make a GET request. I’ll be using JSONPlaceholder, a free online REST API for developers that returns random data in JSON format.. We log the HTTP response to the console by using the XMLHTTPRequest.onreadystatechange property which contains the event handler to be called when the readystatechanged event is fired. const Http = new XMLHttpRequest(); const url=''; Http.open("GET", url); Http.send(); Http.onreadystatechange=(e)=>{ console.log(Http.responseText) } If you view your browser console, it will return an Array of data in JSON format. But how would we know if the request is done? In other words, how we can handle the responses with Ajax? The onreadystatechange property has two methods, readyState and status which allow us to check the state of our request. If readyState is equal to 4, it means the request is done. The readyState property has 5 responses. Learn more about it here. Apart from directly making an Ajax call with JavaScript, there are other more powerful methods of making an HTTP call such as $.Ajax which is a jQuery method. I’ll discuss those now. jQuery has many methods to easily handle HTTP requests. In order to use these methods, you’ll need to include the jQuery library in your project. <script src=""></script> jQuery Ajax is one of the simplest methods to make an HTTP call. The $.ajax method takes many parameters, some of which are required and others optional. It contains two callback options success and error to handle the response received. The $.get method is used to execute GET requests. It takes two parameters: the endpoint and a callback function. The $.post method is another way to post data to the server. It take three parameters: the url, the data you want to post, and a callback function. The $.getJSON method only retrieves data that is in JSON format. It takes two parameters: the url and a callback function. jQuery has all these methods to request for or post data to a remote server. But you can actually put all these methods into one: the $.ajax method, as seen in the example below: fetch is a new powerful web API that lets you make asynchronous requests. In fact, fetch is one of the best and my favorite way to make an HTTP request. It returns a “Promise” which is one of the great features of ES6. If you are not familiar with ES6, you can read about it in this article. Promises allow us to handle the asynchronous request in a smarter way. Let’s take a look at how fetch technically works. The fetch function takes one required parameter: the endpoint URL. It also has other optional parameters as in the example below: As you can see, fetch has many advantages for making HTTP requests. You can learn more about it here. Additionally, within fetch there are other modules and plugins that allow us to send and receive a request to and from the server side, such as axios. Axios is an open source library for making HTTP requests and provides many great features. Let’s have a look at how it works.> With Axios you can use GET and POST to retrieve and post data from the server. axios takes one required parameter, and can take a second optional parameter too. This takes some data as a simple query.. Angular has its own HTTP module that works with Angular apps. It uses the RxJS library to handle asynchronous requests and provides many options to perform the HTTP requests. To make a request using the Angular HttpClient, we have to run our code inside an Angular app. So I created one. If you’re not familiar with Angular, check out my article, learn how to create your first Angular app in 20 minutes. The first thing we need to do is to import HttpClientModule in app.module.ts Then, we have to create a service to handle the requests. You can easily generate a service using Angular CLI. ng g service FetchdataService Then, we need to import HttpClient in fetchdataService.ts service and inject it inside the constructor. And in app.component.ts import fetchdataService //import import { FetchdataService } from './fetchdata.service'; Finally, call the service and run it. app.component.ts: You can check out the demo example on Stackblitz.
http://brianyang.com/here-are-the-most-popular-ways-to-make-an-http-request-in-javascript/
CC-MAIN-2018-22
refinedweb
810
75.5
A collection of cheater methods for the Django TestCase. Project description BaseTestCase BaseTestCase is a collection of cheater methods for the Django TestCase. These came about as a result of learning and using TDD. There are four different classes: 1. ModelTestCase 2. FormTestCase 3. ViewTestCase 4. FunctionalTestCase - For use with Selenium. - Origins and some methods from "Obey The Testing Goat". Quick start Import into test and use: from BaseTestCase import ModelTestCase class ModelTest(ModelTestCase): ... Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/django-basetestcase/0.0.3/
CC-MAIN-2020-29
refinedweb
103
60.11
31 May 2013 13:51 [Source: ICIS news] LONDON (ICIS)--Switzerland-based producer INEOS ChlorVinyls on Friday announced list prices for polyvinyl chloride (PVC) effective from 1 June 2013. Its list price for pipe grade suspension PVC delivered in bulk in Europe is €1,035/tonne ($1,344/tonne), while material delivered in bulk to the ?xml:namespace> INEOS ChlorVinyls’ list prices for May were set at €995/tonne in Europe and £903/tonne in the The price increases in June follow a €5/tonne increase in the feedstock ethylene contract price for the month. The list price is subject to negotiation with individual customers. ($1 = €0.77,
http://www.icis.com/Articles/2013/05/31/9674294/ineos-chlorvinyls-raises-list-price-for-europe-pvc-in-june.html
CC-MAIN-2015-18
refinedweb
108
55.58
This occurs when you attempt access an array with an illegal index... you are either passing in a negative number or a number larger than your array size. Type: Posts; User: hackthisred This occurs when you attempt access an array with an illegal index... you are either passing in a negative number or a number larger than your array size. It looks to be 'type casting' your passed in parameter 's2' Because in larger codes static methods are bad, when trying to trouble shoot code on an enterprise level. Besides I'd assume this method would be used inside a class without a main() lol. So... Then You must not have changed the type params or didn't import LinkList Stack<Integer> pNum = new Stack<Integer>(); LinkedList<Integer> link = new LinkedList<Integer>(pNum); Is perfectly... Answer: Try using a LinkedList instead or even convert your Stack to a LinkedList... This gives you the libraries of both Stacks & Queues, Stacks being LIFO, and Queues being FIFO. :confused: ... I'd recommend the following approach...:D import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class InputStuff { private List<Integer> getUserInput() There is a lot wrong with your code lol :-s For one it won't do anything, because you are calling methods that don't exist. Here is a good example that accomplishes something similar to what I... ok... I'll answer the obvious... although I'm not sure what you are trying to accomplish your main method is wrong. Just remove the ';' public static void main(String[] args) { double... I wish I could say there is nothing wrong with your code, the formatting was horrendous :-s .... anyways try copying your code into notepad then paste it back into your IDE (eclipse). You might have... There is. DJBENZ10 is using all sorts of java abnormalities to accomplish a seemly simple task, I simply posted a simple example as to how one might use a simple constructor. His post was at the very... public class Shapes { private int length; private int width; /** * This a constructor for an object * by which parameter are passed in at * object's creation * @param side1 Umm the answer is kinda obvious, you kinda already said it create a new List. public class Stuff { List<String> cards = new ArrayList<String>(); public void addCardToList (String... wrap your code in code tags so we can see the code formatted as you would see it in you IDE. But I'd recommend you repost only the section of code that is giving you errors most of your methods have... Try using a strLine = (br.readLine().trim()) The trim method as part of the String library will remove any whitespace characters on the line you read into the buffer. Hope this helps :-? Thanks for the insight, but the member had already solved their question; I was merely showing another method of accomplishing the exact same task in cleaner syntax. I recommend using a List instead of an array for this operation, assuming you don't already know the number of entries that will be recorded from the file as input. import java.io.BufferedReader;... You will probably want to use a List so you can use sorting. This will give you a list of values from low to high, simply indicate the nth greatest value you wish to retrieve. It is simple and clean... import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class NumberValueComparison { /** * @param args
http://www.javaprogrammingforums.com/search.php?s=75582d91a6cbde40ab4c4d8ae6ba32e8&searchid=1665720
CC-MAIN-2015-32
refinedweb
586
65.62
a string of length N, an index (i.e., the value between square brackets) must be in the range -N <= index < N-1." should read "[...] must be in the range -N <= index < N." or "[...] must be in the range -N <= index <= N-1." The sequence: '''MWNSNLPKPN AIYVYGVANA NITFFKGSDI LSYETREVLL KYFDILDKDE RSLKNALKD LEN PFGFAPYI TRAYEHKRNF LTTTRLKASF RPTTF''' when entered shows this part "D LEN" modifies to be "DL EN" when it should remain "D LEN". Also, without a cross reference to other formats, some (perhaps most) of the errata is lost on people with other formats. Columns listing the location in each format would be most helpful. Note from the Author or Editor:There is some confusion in the output of the examples on this page. Replace the lines of these examples after the first four with the following, but without the blank lines. The blank lines are here to indicate where new lines begin, since these lines will probably be broken up differently when this erratum is displayed in a browser. '''MKQLNFYKKN SLNNVQEVFS YFMETMISTN RTWEYFINWD KVFNGADKYR NELMKLNSLC GSLFPGEELK SLLKKTPDVV KAFPLLLAVR DESISLLD''' 'MKQLNFYKKN SLNNVQEVFS YFMETMISTN RTWEYFINWD KVFNGADKYR NELMKLNSLC GSLFPGEELK\nSLLKKT PDVV KAFPLLLAVR DESISLLD' '''MWNSNLPKPN AIYVYGVANA NITFFKGSDI LSYETREVLL KYFDILDKDE RSLKNALKDL ENPFGFAPYI RKAYEHKRNF LTTTRLKASF RPTTF''' 'MWNSNLPKPN AIYVYGVANA NITFFKGSDI LSYETREVLL KYFDILDKDE RSLKNALKDL ENPFGFAPYI\nRKAYEH KRNF LTTTRLKASF RPTTF' Finally, before the line "There are three situations that cause ..." Add "If you type these examples to Python you may see slight differences in where one line ends and another begins." "In Python 2, it would have printed as 0.0089999999999999993, and 0.003 would have printed as 0.0089999999999999993." should be "In Python 2, it would have printed as 0.0089999999999999993, and 0.03 would have printed as 0.029999999999999999." The explanation of conditional expressions is incorrect: "Written using the keywords if and else, it returns the value **preceding** (not following) the if when the condition is true and the value following the else when it is false. >>> 'no' if 1 % 2 else 'no' isn't a very instructive example, since the outcome is always 'no' regardless of the resolving of the if-else-clause. A better example (together with the first example) would be: >>> 'yes' if 1//2 else 'no' 'no' Wouldn't it? Note from the Author or Editor:Change as suggested. Example is missing Python interpreter output. Note from the Author or Editor:Delete the line ">>> False or True": The example >>> 3 > 13 % 5 False is misleading for non-programmers since the precedence of the operations in this case is "%" first and ">" second. While the example is correct in its answer, it is also correct if one uses the wrong precedence. Changing the "13" to another value would be helpful, but may introduce complexity to your description. >>> 3 > 12 % 5 True You could also use a footnote saying "see page 16, Compound Expressions" for a treatment of precedence. Alternately, you can refer back to the example on p. 8 from p. 16 and show how changing the "13" to a different value changes the answer and exposes the precedence rule. Note from the Author or Editor:This example and the one before it are both confusing. Change "2 == 5 // 2" to just "2 == 2" and change "3 > 13 % 5" to just "3 > 3". >>> 'MNKMDLVADVAEKTDLSKAKATEVIDAVFA'[7//2] 'K' should be changed to: >>> 'MNKMDLVADVAEKTDLSKAKATEVIDAVFA'[7//2] 'M' Note from the Author or Editor:Thank you! >>> 'MNKMDLVADVAEKTDLSKAKATEVIDAVFA'[:8] 'MNKMDLVADVAEKTDLSKAKAT' should be >>> 'MNKMDLVADVAEKTDLSKAKATEVIDAVFA'[:-8] 'MNKMDLVADVAEKTDLSKAKAT' on Page 11, the output ist wrong: Book: >>> 'MNKMDLVADVAEKTDLSKAKATEVIDAVFA'[:8] 'MNKMDLVADVAEKTDLSKAKAT' Python3: >>> 'MNKMDLVADVAEKTDLSKAKATEVIDAVFA'[:8] 'MNKMDLVA' Note from the Author or Editor:Whoops. Should be -8, not 8. string1.find(string2[, start[, end]]) Returns the position of the last occurrence of string2 in string1 should be string1.find(string2[, start[, end]]) Returns the position of the first occurrence of string2 in string1 You can use Ctrl-P or the down arrow to move to a later line in the input history. instead of : You can use Ctrl-N ... Note from the Author or Editor:yes seq = base_seq.upper() should be seq = base_sequence.upper() as in example 2-4. >>>return ((base_seq.count('G') + base_seq.count('C')) / >>> len(base_seq)) should be >>>return ((seq.count('G') + seq.count('C')) / >>> len(base_seq)) Note from the Author or Editor:Yes, and might as well make it len(seq) too. >>> validate_base_sequence('AUCG') >>> # second argument omitted; defaults to True True should be >>> validate_base_sequence('AUCG') >>> # second argument omitted; defaults to False False The code line: bases.replace(base, '') is not altering the bases string in Python 3.0. Changing the code to: bases = bases.replace(base, '') fixed this for me. Note from the Author or Editor:Yes. Strings are modifiable in some languages and not in others. This often leads to confusion, including among people like myself who have used many of each kind of language! newbase = bases[randint(0,2)] should be newbase = bases[randint(0,3)] in order to include base 'G' as a possible mutation Note from the Author or Editor:Change (0, 2) to (0, 3). The lines with the doc string and return statement should each begin with an additional space. In the definition of test, True and False should be exchanged. 1) gc_content doesn't work with lowercase input because of a minor mistake: def gc_content(base_seq): assert validate_base_sequence(base_seq), 'Argument has invalid characters' seq = base_seq.upper() return (base_seq.count('G') + base_seq.count('C')) / len(base_seq) should be changed to: def gc_content(base_seq): assert validate_base_sequence(base_seq), 'Argument has invalid characters' seq = base_seq.upper() return (seq.count('G') + seq.count('C')) / len(base_seq) 2) gc_content doesn't work with RNA input (raises assertion error). I'm not sure if this was by design. If not, it could be fixed by adding the RNAflag parameter to its definition: def gc_content(base_seq, RNAflag=False): assert validate_base_sequence(base_seq, RNAflag), 'Argument has invalid characters' seq = base_seq.upper() return (base_seq.count('G') + base_seq.count('C')) / len(base_seq) The title of Table 3-7 should be "Operations generally supported by sequence types" under creating char(n) should be chr(n), ord(char) should be ord(chr) Note from the Author or Editor:char(n) should be chr(n), but ord(char) does not need to be changed str1.endswith(str2[, startpos, [endos]]) should be str1.endswith(str2[, startpos, [endpos]]) str1.numeric() should be str1.isnumeric() Note from the Author or Editor:Yes. This is why it's a good policy to name all predicate functions consistently -- if it returns True or False, it should begin with "is". But then, that doesn't help notice when you've left out the "is", does it! Error in RNA_codon_table: 'UGG': 'Urp' has to be 'UGG': 'Trp' 3-Letter-code for Tryptophan : TRP Note from the Author or Editor:yes. Delete one of the two spaces between "return" and "all". Replace the body of the definition of read_FASTA_sequences with: return [[seq[0], seq[2].replace('\n', '')] # delete newlines for seq in read_FASTA_entries(filename)] Remove "[1:]" from the first line of the body of read_FASTA_sequences. replace [0] with [1] Replace with: return {line.split('|')[2] for line in file if line[0] == '>' and len(line.split('|')) > 2} The definition of first_common can be used with any two collections, so (1) replace "list1" and "list2" with "collection1" and "collection2"; and (2) in the sentence preceding the example replace "list" with "collection". I think the returned value would be False each time "some" is called with the same arguments. I suspect that the arguments are wrong in the first call to "some". >>> some([0, '', False]) True >>> some([0, '', False]) False Note from the Author or Editor:change first call to some([0, 'A', False]) I think the sentence order in the last paragraph should be reversed. The first sentence describes the sixth and seventh calls to "some" and the second sentence describes the fourth and fifth calls to "some". This was confusing at first. ... >>> some([0, 1, 4], lambda x: isinstance(x, int) and x % 2) # odd ints? True >>> def odd(n): ... return bool(n % 2) ) >>> some([0, 2, 4], odd) False >>> some({'a string', ''}, len) False >>> some({tuple(), ''}, len) False The last two lines of input illustrate that some can be used on any collection, not just a sequence. The definition of odd and the input before and after it show that the name of a function and a lambda expression have the same effect in a function call. In Example 3-24, it states >>>some({'a string', ''}, len) False This is incorrect. The output is True because len('a string') = 8. Running the provided sample code ch03_24.py confirms this. First line after the docstring of extract_gi_id should be indented four spaces fewer and "line" should be replaced with "description". Add a right parentheses at the end of the code on the right side of the table. There should be no line break after "def" at the beginning of the table. On the right side of the table insert a right parentheses between the right parentheses and right bracket. In the definition of is_number replace "elt" with "value" Add a colon at the end of the first line of the definition of list_sequences_in_file. First line after the doc string of extract_gi_id should be indented four spaces fewer and "line" should be replaced with "description". First line after the doc string of extract_gi_id should be indented four spaces fewer and "line" should be replaced with "description". (This is page 134 not 127) Note from the Author or Editor:The line beginning "if line[0]" should be indented 4 fewer spaces and the word "line" should be replaced with the word "description". The last two lines should be indented an additional 6 spaces each. In the definition of get_gene_info_from_file the open statement should have a second argument: encoding = 'utf-8' which is often necessary for HTML files saved from a web page. Replace "sites/entrez" with "gene" in the URL for Entrez Gene. Before "click the search button" add "select Gene from the dropdown to the left of the search box, " Remove the argument "testfn" from the call to item_generator at the beginning of find_item. The next to last line of item_generator should eliminate the initial '>' and final '\n', reading: description = line[1:-1].split('|') Rename next_item to item_generator and add the following definition: def get_items(src, testfn=None): """Return all the items in src; if testfn then include only those items for which testfn is true""" return [item for item in item(src) if not testfn or testfn(item)] This section should refer to DNA throughout, not RNA. Change "RNA" to "DNA" in the title and the first sentence of the subsequent paragraph, as well as in the Table of Contents. The last sentence of that paragraph should be replaced with the "This example, though, will be based on DNA, instead of RNA, codons. (For the purpose of this example we are pretending that DNA is directly translated into amino acids rather than first being transcribed into RNA which is then tranlsated into amino acid sequences.)" The table should contain DNA codons not RNA codons: replace U with T throughout the table. Likewise, replace "RNA" with "DNA" in the function definition and the example title. Replace "RNA" with "DNA" in the code and the example title "print" in the definition of print_translation_in_frame should line up with the first quote of the doc string In definition of translate_with_open_reading_frames "frame-1" should be "framenum-1" Replace "print_translations" with "print_translations_with_open_reading_frame" Replace "print_translations" with "print_translations_with_open_reading_frame_in_both_directions" Replace "RNA" with "DNA" in the example title The following sentence should appear at the end of the footnote: "The idea to use the restriction enzyme database as an example comes from James Tisdall's Beginning Perl for Bioinformatics, O'Reilly Media, 2001. Add a colon to the end of the first line of the definition of load_enzyme_data_into_table In the definition of test, delete the second space after "result =", and change "== 2" to "== 3559" in the first assertion statement. Add a right parentheses at the end of the doc string In the definition of __repr__, delete a space before the first quote of the doc string and before "repr" on the second line of the return statement. add: self.read_next_line() at the end of the definition skip_intro, repeating the first line of the definition. In the definition of gc_content replace "get_sequence" with "get_sequence()". change class AmbiguousDNASequence(DNASequence): to class AmbiguousDNASequence(BaseSequence): in definition of complement get rid of first self in self(self.get_sequence) in class RNASequence, change ComplementTrans to ComplementTable Note from the Author or Editor:Yes. Clarification on the first: remove first left parentheses and final right parentheses on same line too. The caption for Figure 5-2 should read "A deeper class hierarchy" The second DNASequence from left to right at the bottom of Figure 5-2 should be ProteinSequence The paragraph is entirely incorrect and should be deleted. In its place, the following sentence should be added to the end of the previous paragraph: "Note that output sent to both streams is "line-buffered", meaning that characters are accumulated until an end-of-line character is encountered, at which point the line is sent to the stream's actual destination. Remove right parentheses after "path" "(command)" --> "(command, shell=True)" Insert before the first comment line, the line: # other ports commonly used are 465 and 587 "conneection" --> "connection" "variables" should be "values" "return path" --> "return path" "return path" --> "return paths" val --> value In function multi_search, the start of the list comprehension is "target .find" (space between "target" and ".find"). It works OK but this might be confusing. Better without the space? Note from the Author or Editor:Delete the space after "target" in the third from last line (the one beginning "return min". the variable "m" is not defined. Is "m" supposed to be "matchobj"? Note from the Author or Editor:Replace "while m" with "while matchobj" and in the next line, "m.group" with "matchobj.group". Also, on the last line of the next Example (7-5) replace "m =" with "matchobj =". The code for the while loop should be: while itm: itm, nxtpos = next_item(buffer, curpos) # reread to ensure complete yield itm itm, curpos, nxtpos = nxtitm, nxtpos, nxtend nxtitm, buffer, nxtend = get_item(file, buffer, nxtpos, chunksize) remove the right parenthesis from the first line add a single quote before the comma on the second line replace the right parenthesis on the third line with a single quote Add a colon at the end of the second to last line of the example (that begins with def remove_html) Choose XML ABOVE Overview instead of Protein Table BELOW. It will take a while for the page to download. When it's done, do step 6. The information on the web page was reorganized somewhat since the book was published, but the general idea of the step is unaffected. remove the s from tagnames Remove p in the for places it appears in from self.parser.p Delete the first line after the doc string in the definition of start_element. indent 4 spaces in the assignment of urlpart1, the semicolon after the question mark should be a colon quote_plus(words) --> quote_plus(' '.join(words)) Add 'name' at the end of the function name make_html_for_file The syllable write_ would have been a better first syllable for all the names beginning with make_ in Example 9-20. In the line{1}</a></li>\n" replace href="{0}" with {0} First line on page, the l at the end of the line should be ) After assignments to HOST and PORT add: encoding = 'ASCII' 6th line from bottom: SimpleHTTPRequestHandler should be http.server.SimpleHTTPRequestHandler The names protnum in the parameter list and portnumber in the next to last line of the definition of run should both be port The 2nd line of open_port should be: for portnum in range(startport, startport+100): The parameter server_class should be handler_class Add parameter handler_class to open_port and handler_class to its call in run At the end of the definition of run replace SimpleHTTPRequestHandler with CGIHTTPRequestHandler. In the definition of run, portnum, portnumbe, and portnumber should each be just port The second line of open_port should be for portnum in range(startport, startport+100): The next to last line of the definition of run should use CGIHTTPRequestHandler not HTTPRequestHandler table.get(sequence, set()).add(enzyme) --> if sequence in table: table[sequence].add(enzyme) else: table[sequence] = {enzyme} # first enzyme for sequence replace the last 5 lines of parse_organism (the if/elif/return code) with: return (parts[0], parts[1], None if len(parts) == 2 else ' '.join(parts[2:]) in the line after "try:" replace "get_connection" with sqlite3.connect delete the next to last line of the definition of load_enzyme_data and the + at the end of the line before the deleted one in return statement change sequence to seqdata max(Name, --> max(Name) Add footnote to the paragraph beginning "Example 11-1": The simple form of tkinter programs shown in this chapter cannot be run from IDLE, because IDLE is itself a tkinter program; they must be run from the command line or another IDE. add ' after Verdana Delete the following extraneous lines are extraneous: tic_width = 3 xaxis_width = yaxis_width = 0 xlabel_height = ylabel_width = 0 x_label_height should be xlabel_height In the last line of __init__ (the call to super) filename should be ps_filename "+1 5" should be "+ 15" "variable" should be "name" It's a table of two columns: Statement and Equivalent. The mistake is on the last row. First column reads: name **= expression Second column reads: name = name * expression (second column should be: name = name ** expression .) "genus name" --> "species name" !!! © 2015, 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.oreilly.com/catalog/errata.csp?isbn=9780596154516
CC-MAIN-2015-22
refinedweb
2,950
61.36
Hi there, I'm writing a C program to simulate a software system that would be used to monitor the movement of shipping. I am required to write a program that simulates a passage of time and calculates whether or not a "risk of collision" exists between any ships and whether or not any ships actually collide. If ships do collide, I will assume that they sink without a trace and need to have features to record that in my data structures. Once a ship has sunk, it cannot collide with anything again. Currently, my program prompts the user for the name of a file which will contain the shipping data for the area I am concerned with; it then opens the file, reads in all of the data and stores it in a couple of data structures. My program then prompts the user for a "duration", that being the length of time in hours that my program should then attempt to simulate. It then prompts the user for a "time step", that being the length of time in minutes that my program should move forward at each step of its simulation. It should then run, with time moving forward, and at each step, should evaluate the new position of all of the ships and whether or not any significant events occur, i.e. a risk of collision an actual collision a ship sails out of the area I'm monitoring a ship sails into the area I'm monitoring Appropriate output should be sent to "standard output" to show the current state of simulation and any significant events. I have got as far as reading all of the data in from the text file specified by the user, and prompting the user for a "duration" and "time step", but I'm not sure how to then "run it", with time moving forward, and evaluate the new position of all of the ships at each step, and whether or not any significant events occur. This is what I have so far: I'm currently trying to implement a method to determine whether or not a 'risk of collision' occurs- this would happen if any two ships' courses overlap at all, but I'm not sure how I would work that out...I'm currently trying to implement a method to determine whether or not a 'risk of collision' occurs- this would happen if any two ships' courses overlap at all, but I'm not sure how I would work that out...Code:/* * File: main.c * Author: eef8 * * Created on 06 December 2011, 15:53 */ #include <stdio.h> #include <stdlib.h> #include "structs.h" #include "navigation.h" /* * */ extern int errno; /* Here, I need to create the linked list, so that the data for each ship is stored in a new instance of the array. */ typedef struct shipInfo item; int main(int argc, char** argv) { char text[500]; /* Create a character array that will store all of the text in the file */ char line[100]; /* Create a character array to store each line individually */ dateTime *dates = (dateTime *) malloc (6 * sizeof (int)); FILE *file; /* Create a pointer to the file which will be loaded, to allow access to it */ char fileName[30]; /* Create a character array to store the name of the file the user want to load */ printf("Enter the name of the file containing ship information: "); scanf("%s", fileName); /*Try to open the file specified by the user. Use error handling if file cannot be found*/ file = fopen(fileName, "r"); /* Open the file specified by the user in 'read' mode*/ char lineBuffer[100]; if(file == NULL){ perror("The following error occurred: "); printf("Value of errno: %d\n", errno); } else { /* Read in the date and time of the ship information */ dates = calloc(1, sizeof(dateTime)); fscanf(file, "%d %d %d %d %d %d", &dates->day, &dates->month, &dates->year, &dates->hour, &dates->minute, &dates->second); printf("File loaded for %d/%d/%d\n", dates->day, dates->month, dates->year); /* Display a message to let the user know * that the file has been loaded properly. * Need to use fscanf to read the information in from the file */ item *current, *head; int i; head = NULL; while(!feof(file)){ /* Will need to give i some proper value (not 10) * that will be correct depending of the number of * ships in a file- maybe read how many lines there are * in the file, to find out how many ships there will be */ current = (item *)malloc(sizeof(item)); fscanf(file, "%s %f %f %f %f\n", ¤t->AISID, ¤t->latitude, ¤t->longitude, ¤t->direction, ¤t->speed); current->nextShip = head; head = current; } current = head; /* Print out the contents of the array for each ship, to check that the data is being stored correctly */ while(current!=NULL){ printf("%s\n%f\n%f\n%f\n%f\n", current->AISID, current->latitude, current->longitude, current->direction, current->speed); current = current->nextShip; } /*Now ask the user to provide a duration, for which the program should simulate*/ float duration, timeStep; printf("Please enter the duration in hours of time for which you would like to simulate: "); scanf("%f", &duration); printf("Please enter the 'time step' in minutes that the program should move forward in each step of the simulation: "); scanf("%f", &timeStep); fclose(file); // return 0; } free(dates); dates = NULL; /*free(ships); ships = NULL;*/ return (EXIT_SUCCESS); } /* Here, use the 'great_circle' method in navigation.h to calculate the distance between each of * the ships in the file. If any of the ships are within 2 miles of each other AND are on courses * that overlap at anytime in the future, a 'risk of collision' is deemed to exist*/ int riskOfCollision(location ship1, location ship2){ if((great_circle(ship1, ship2)<=2) &&(/*Need code here to determine whether or not ships' * courses overlap at all here*/)){ } } If someone could point me in the right direction, I would be very grateful. Thanks in advance.
http://cboard.cprogramming.com/c-programming/144385-monitoring-variables-regard-time.html
CC-MAIN-2014-35
refinedweb
988
53.17
The DataList control is used to display data that is in some sort of collection. As with the Repeater , the DataList supports a number of templates. These can be seen in Table 10.2. The DataList control has a richer feature set than the Repeater control. It supports selecting and editing. If you use a DataList control, you must at least define an ItemTemplate. Within the ItemTemplate, you can set the attributes with which the DataList is to render the data. The other templates determine other aspects of the DataList appearance. Template Name Description AlternatingItemTemplate If defined, provides the content and layout for alternating items in the DataList . If not defined, ItemTemplate is used. EditItemTemplate If defined, provides the content and layout for the item currently being edited in the DataList . If not defined, ItemTemplate is used. FooterTemplate If defined, provides the content and layout for the footer section of the DataList . If not defined, a footer section is not displayed. HeaderTemplate If defined, provides the content and layout for the header section of the DataList . If not defined, a header section is not displayed. ItemTemplate Required template that provides the content and layout for items in the DataList. SelectedItemTemplate If defined, provides the content and layout for the currently selected item in the DataList . If not defined, ItemTemplate is used. SeparatorTemplate If defined, provides the content and layout for the separator between items in the DataList . If not defined, a separator is not displayed. DataList objects normally render their bound data into tables. You can change the DataList output type with the RepeatLayout property. The two values that are supported are flow (where data is simply output to the HTML stream) and table (where data is rendered as a table). The following five lines of code show you how to set the DataList output type: // Set to Flow layout DataList1.RepeatLayout = RepeatLayout.Flow; // Set to Table layout DataList1.RepeatLayout = RepeatLayout.Table; You also can set the repeat direction for the DataList control. In other words, you can set in which direction the DataList sorts: horizontal or vertical. To do this, you set the RepeatDirection property to one of two values: either horizontal or vertical. The following five lines of code show you how it can be done: // Set to Horizontal DataList1.RepeatDirection = RepeatDirection.Horizontal; // Set to Vertical DataList1.RepeatDirection = RepeatDirection.Vertical; I very easily changed the ShowData application, which I created earlier in this chapter, to use a DataList rather than a Repeater control. All that was necessary was to remove the Repeater control, add a DataList control, insert an ItemTemplate into the DataList control, and alter the code that binds the data slightly so that the recordset was bound to a DataList rather than to a Repeater . The following code shows the DataList that was inserted into the .aspx code: <asp:datalist <ItemTemplate> <%# DataBinder.Eval(Container, "DataItem.Name") %> <%# DataBinder.Eval(Container, "DataItem.NDC") %> </ItemTemplate> </asp:datalist> As I have already said, the next thing to do was to data bind to the DataList control rather than to the Repeater control. The following code shows the simple change made to switch from using a Repeater to a DataList :(); You can see the ShowData application executing in Figure 10.3. In this figure the application is using a DataList and not a Repeater . One of the things you might want to do to give your DataList a more attractive appearance is to add a SeparatorTemplate. A SeparatorTemplate enables you to control the look of the separation object that is between each rendered data item in the DataList . The following code uses a simple HR tag as the separator, which is inside a SeparatorTemplate: <asp:datalist <ItemTemplate> <%# DataBinder.Eval(Container, "DataItem.Name") %> <%# DataBinder.Eval(Container, "DataItem.NDC") %> </ItemTemplate> <SeparatorTemplate> <hr> </SeparatorTemplate> </asp:datalist> To make the lines of your DataList selectable, you must add a SelectedItemTemplate to your DataList . The SelectedItemTemplate determines what a row of data will look like when it is selected. Inside the ItemTemplate you need to provide a way for users to select items. The easiest way to add the capability to select items is with a LinkButton object. If you use a LinkButton , be sure to specify the CommandName attribute as select . The following code shows how to add an ItemTemplate and a SelectedItemTemplate so that users can select a row of data in a DataList : <ItemTemplate> <asp:LinkButton <%# DataBinder.Eval(Container, "DataItem.NDC") %> </ItemTemplate> <SelectedItemTemplate> NDC: <%# DataBinder.Eval(Container, "DataItem.NDC") %> Name: <%# DataBinder.Eval(Container, "DataItem.Name") %> </SelectedItemTemplate> If you want to be able to edit an item, you need to add an EditItemTemplate. The EditItemTemplate normally has a TextBox in which users can edit some data. Many times, EditItemTemplates also have LinkButtons , which enable them to issue some kind of command to the underlying code. The following code shows a typical ItemTemplate that can be used to edit some data in a DataList object: <EditItemTemplate> NDC: <asp:Label Name: <asp:TextBox <asp:LinkButton <asp:LinkButton <asp:LinkButton </EditItemTemplate> To capture a selection event from a DataList object, you must create a SelectedIndexChanged() event method. This is the method that gets fired off when the user selects an item in a DataList . In essence, everything is managed for you automatically. The control figures out which item is selected and renders it in the manner that you have specified in the SelectedItemTemplate. Look at Listing 10.1. What you should note is a method called QueryDatabase() . The QueryDatabase() method simply goes to the database, performs a query, and then binds the data to the DataList control. This method is being called from two different places. It is being called from the Page_Load() method the first time this page is loaded up. The IsPostBack property is used to make sure that the QueryDatabase() method is not called on subsequent postbacks. You also can see the QueryDatabase() method being called from the DataList 's SelectIndexChanged() method. using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Data.SqlClient; namespace ShowData { /// <summary> /// Summary description for WebForm1. /// </summary> public class WebForm1 : System.Web.UI.Page { protected System.Web.UI.WebControls.DataGrid DataGrid1; protected System.Web.UI.WebControls.DataList DataList1; protected System.Web.UI.WebControls.Repeater Repeater1; public WebForm1() { Page.Init += new System.EventHandler(Page_Init); } public void QueryDatabase() {(); } private void Page_Load(object sender, System.EventArgs e) { if( !IsPostBack ) { QueryDatabase(); } } private void Page_Init(object sender, EventArgs e) { // // CODEGEN: This call is required by the ASP.NET // Web Form Designer. // InitializeComponent(); } #region Web Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.DataList1.SelectedIndexChanged += new System.EventHandler( this.DataList1_SelectedIndexChanged); // this.DataList1.ItemCommand += new System.EventHandler( this.DataList1_ItemCommand); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void DataList1_SelectedIndexChanged(object sender, System.EventArgs e) { QueryDatabase(); } } } It is time now to take the DataList control in this application and make it look better. Listing 10.2 shows presentation code that gives a nicer effect than the simple code shown earlier. <asp:DataList <SelectedItemTemplate> <tr bgcolor="yellow"> <td width="50%" align="right"> Name: <asp:Label </td> <td width="50%"> NDC: <asp:Label </td> </tr> </SelectedItemTemplate> <ItemTemplate> <tr> <td width="50%" align="right"> <asp:LinkButton </td> <td width="50%"> <%# DataBinder.Eval(Container, "DataItem.NDC") %> </td> </tr> </ItemTemplate> </asp:DataList> You can see this application running in Figure 10.4, where one of the lines is highlighted. Datalist controls are easy to use, and even more powerful than Repeaters . You will find that they often make their way into your applications. Of all of the data bound controls, I use them the most. That's because there's a little more work to use them than the Repeater , but I often need the ability to offer users selectable items.
https://flylib.com/books/en/2.628.1.79/1/
CC-MAIN-2019-43
refinedweb
1,326
50.63
Sorting a list of objects of user-defined class using Comparator interface Sorting is vital in every aspect of programming. The java.util.Collections.sort() function can be used to sort the elements of a list of a predefined data type. The Comparator interface is used to sort list of user defined objects. This interface is present in java.util package. For comparing, compare method of the interface is used. A class implementing the interface will be passed to sort method. Collections.sort() method call compare method of the classes it is sorting. The compare method returns -1, 0 or 1 to say if it is less than, equal, or greater to the other. It uses this result to swap the elements. public void sort(List list, Comparator c): is used to sort the elements of List by the given comparator. Sort list of objects of user-defined class using Comparator interface in Java- Example Suppose, we want to sort elements of a Player class based on their score in Java. The Player class has two data members, score and name. We want to sort the players on the basis of score. The SortbyScore class implements the Comparator interface. import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class MyComparator { public static class Player { int score; String name; public Player(int s, String str) { score = s; name = str; } } public static class SortbyScore implements Comparator<Player> { @Override public int compare(Player o1, Player o2) { return o1.score - o2.score; } } public static void main(String[] args) { ArrayList<Player> al = new ArrayList<>(); al.add(new Player(54, "Rohit")); al.add(new Player(67, "Dhawan")); al.add(new Player(101, "Virat")); al.add(new Player(34, "Dhoni")); Collections.sort(al, new SortbyScore()); for (int i = 0; i < al.size(); i++) { System.out.println(al.get(i).name + " " + al.get(i).score); } } } The Output for this code : Dhoni 34 Rohit 54 Dhawan 67 Virat 101 You may also read:
https://www.codespeedy.com/sort-list-of-objects-of-user-defined-class-using-comparator-interface-in-java/
CC-MAIN-2021-17
refinedweb
328
60.01
Internationalization of Haskell programs using gettext From HaskellWiki?" Using these recomendations, prepare strings and wrap them to some 'translation' function '__': module Main where import IO import Text.Printf __ = id main = do putStrLn (__ "Please enter your name:") name <- getLine printf (__ "Hello, %s, how are you?") name, %s, how are you?\n" msgstr "" We are interested in the with following strings: #: Main.hs:0 msgid "Please enter your name:" msgstr "Wie heißen Sie?" #: Main.hs:0 msgid "Hello, %s, how are you?\n" msgstr "Hallo, %s, wie geht es Ihnen?\n" 3 Install translation files Now we have to create" (Just ".") textDomain (Just "hello") putStrLn (__ "Please enter your name:") name <- getLine printf (__ "Hello, %s, how are you?\n") name Here we added three initialization strings: setLocale LC_ALL (Just "") bindTextDomain "hello" (Just ".") textDomain (Just > Any other files could be generated from the previous, so they shouldn't be included to the distribution package. Let's create the directory structure for our project. This is simple project, so directory structure should be simple too. Here it is: hello\ | |-po\ | | | |-messages.pot | |-en.po | |-de.po | |-src\ | |-Main.hs Category: Hello Synopsis: Internationalized Hello sample Build-Type: Custom Extra-Source-Files: po/*.po po/*.pot x-gettext-po-files: po/*.po x-gettext-domain-name: hs-hello Executable hello Main-Is: Main.hs Hs-Source-Dirs: src Build-Depends: base,hgettext >= 0.1.5, setlocale This is standard .cabal file, but there we added two more lines: - x-gettext-po-files<, and specified Build-type: Custom. The second file to create --- Setup.hs: import Distribution.Simple.I18N.GetText main = gettextDefaultMain 6.3 Update the program code So our installer knows where to put the *.po files and the domain name for them. Our code should know it too --- to make proper initialization. It is not Haskell way to duplicate same information twice, so let's modify the code to get the initialization parameters directly from the installer: module Main where import Text.Printf import Text.I18N.GetText import System.Locale.SetLocale import System.IO.Unsafe __ :: String -> String __ = unsafePerformIO . getText main = do setLocale LC_ALL (Just "") bindTextDomain __MESSAGE_CATALOG_DOMAIN__ (Just __MESSAGE_CATALOG_DIR__) textDomain __MESSAGE_CATALOG_DOMAIN__ putStrLn (__ "Please enter your name:") name <- getLine printf (__ "Hello, %s, how are you?\n") name So, the only lines were changed are: bindTextDomain __MESSAGE_CATALOG_DOMAIN__ (Just __MESSAGE_CATALOG_DIR__) textDomain __MESSAGE_CATALOG_DOMAIN__>
http://www.haskell.org/haskellwiki/Internationalization_of_Haskell_programs_using_gettext
CC-MAIN-2014-23
refinedweb
393
53.17
February 2015 Volume 30 Number 2 Visual Studio 2015 - Build Better Software with Smart Unit Tests By Pratap Lakshman | February 2015 Editor’s note: "Smart Unit Tests" has been renamed “IntelliTest” with the release of the Visual Studio 2015 Release Candidate. The world of software development is hurtling toward ever-shortening release cycles. The time when software development teams could strictly sequence the functions of specification, implementation and testing in a waterfall model is long past. Developing high-quality software is hard in such a hectic world, and calls for a reevaluation of existing development methodologies. To reduce the number of bugs in a software product, all team members must agree on what the software system is supposed to do, and that’s a key challenge. Specification, implementation and testing have typically happened in silos, with no common medium of communication. Different languages or artifacts used for each made it difficult for them to co-evolve as the software implementation activity progresses, and so, while a specification document ought to connect the work of all the team members, that’s rarely the case in reality. The original specification and the actual implementation might diverge, and the only thing holding everything together eventually is the code, which ends up embodying the ultimate specification and the various design decisions made en route. Testing attempts to reconcile this divergence by resorting to testing just a few well-understood end-to-end scenarios. This situation can be improved. A common medium to specify the intended behavior of the software system is needed, one that can be shared across design, implementation and testing, and that’s easy to evolve. The specification must be directly related to the code, and the medium be codified as an exhaustive suite of tests. Tool-based techniques enabled by Smart Unit Tests can help fulfill this need. Smart Unit Tests Smart Unit Tests, a feature of Visual Studio 2015 Preview (see Figure 1), is an intelligent assistant for software development, helping dev teams find bugs early and reduce test maintenance costs. It’s based on previous Microsoft Research work called “Pex.” Its engine uses white-box code analyses and constraint solving to synthesize precise test input values to exercise all code paths in the code under test, persist these as a compact suite of traditional unit tests with high coverage, and automatically evolve the test suite as the code evolves. Figure 1 Smart Unit Tests Is Fully Integrated into Visual Studio 2015 Preview .png) Moreover, and this is strongly encouraged, correctness properties specified as assertions in code can be used to further guide test case generation. By default, if you do nothing more than just run Smart Unit Tests on a piece of code, the generated test cases capture the observed behavior of the code under test for each of the synthesized input values. At this stage, except for test cases causing runtime errors, the remaining are deemed to be passing tests—after all, that’s the observed behavior. Additionally, if you write assertions specifying the correctness properties of the code under test, then Smart Unit Tests will come up with test input values that can cause the assertions to fail, as well, each such input value uncovering a bug in the code, and thereby a failing test case. Smart Unit Tests can’t come up with such correctness properties by itself; you’d write them based on your domain knowledge. Test Case Generation In general, program analysis techniques fall between the following two extremes: - Static analysis techniques verify that a property holds true on all execution paths. Because the goal is program verification, these techniques are usually overly conservative and flag possible violations as errors, leading to false positives. - Dynamic analysis techniques verify that a property holds true on some execution paths. Testing takes a dynamic analysis approach that aims at detecting bugs, but it usually can’t prove the absence of errors. Thus, these techniques often fail to detect all errors. It might not be possible to detect bugs precisely when applying only static analysis or employing a testing technique that’s unaware of the structure of the code. For example, consider the following code: int Complicated(int x, int y) { if (x == Obfuscate(y)) throw new RareException(); return 0; } int Obfuscate(int y) { return (100 + y) * 567 % 2347; } Static analysis techniques tend to be conservative, so the non-linear integer arithmetic present in Obfuscate causes most static analysis techniques to issue a warning about a potential error in Complicated. Also, random testing techniques have very little chance of finding a pair of x and y values that trigger the exception. Smart Unit Tests implements an analysis technique that falls between these two extremes. Similar to static analysis techniques, it proves that a property holds for most feasible paths. Similar to dynamic analysis techniques, it reports only real errors and no false positives. Test case generation involves the following: - Dynamically discovering all the branches (explicit and implicit) in the code under test. - Synthesizing precise test input values that exercise those branches. - Recording the output from the code under test for the said inputs. - Persisting these as a compact test suite with high coverage. Figure 2 shows how it works using runtime instrumentation and monitoring and here are the steps involved: - The code under test coverage for each test case, and tracks how the input value flows through the code. If all paths are covered, the process stops; all exceptional behaviors are considered as branches, just like explicit branches in the code. If all paths haven’t been covered yet, the testing engine picks a test case that, the code under test is run with the new concrete input value. - If coverage increases, a test case is emitted. Figure 2 How Test Case Generation Works Under the Hood .png) Steps 2 through 5 are repeated until all branches are covered, or until preconfigured exploration bounds are exceeded. This process is termed an “exploration.” Within an exploration, the code under test can be “run” several times. Some of those runs increase coverage, and only the runs that increase coverage emit test cases. Thus, all tests that are generated exercise feasible paths. Bounded Exploration If the code under test doesn’t contain loops or unbounded recursion, exploration typically stops quickly because there are only a (small) finite number of execution paths to analyze. However, most interesting programs do contain loops or unbounded recursion. In such cases, the number of execution paths is (practically) infinite, and it’s generally undecidable whether a statement is reachable. In other words, an exploration would take forever to analyze all execution paths of the program. Because test generation involves actually running the code under test, how do you protect from such runaway exploration? That’s where bounded exploration plays a key role. It ensures explorations stop after a reasonable amount of time. There are several tiered, configurable exploration bounds that are used: - Constraint solver bounds limit the amount of time and memory the solver can use in searching for the next concrete input value. - Exploration path bounds limit the complexity of the execution path being analyzed in terms of the number of branches taken, the number of conditions over the inputs that need to be checked, and the depth of the execution path in terms of stack frames. - Exploration bounds limit the number of “runs” that don’t yield a test case, the total number of runs permitted and an overall time limit after which exploration stops. An important aspect to any tool-based testing approach being effective is rapid feedback, and all of these bounds have been preconfigured to enable rapid interactive use. Furthermore, the testing engine uses heuristics to achieve high code coverage quickly by postponing solving hard constraint systems. You can let the engine quickly generate some tests for code on which you’re working. However, to tackle the remaining hard test input generation problems, you can dial up the thresholds to let the testing engine crunch further on the complicated constraint systems. Parameterized Unit Testing All program analysis techniques try to validate or disprove certain specified properties of a given program. There are different techniques for specifying program properties: - API Contracts specify the behavior of individual API actions from the implementation’s perspective. Their goal is to guarantee robustness, in the sense that operations don’t crash and data invariants are preserved. A common problem of API contracts is their narrow view on individual API actions, which makes it difficult to describe system-wide protocols. - Unit Tests embody exemplary usage scenarios from the perspective of a client of the API. Their goal is to guarantee functional correctness, in the sense that the interplay of several operations behaves as intended. A common problem of unit tests is that they’re detached from the details of the API’s implementation. Smart Unit Tests enables parameterized unit testing, which unites both techniques. Supported by a test-input generation engine, this methodology combines the client and the implementation perspectives. The functional correctness properties (parameterized unit tests) are checked on most cases of the implementation (test input generation). A parameterized unit test (PUT) is the straightforward generalization of a unit test through the use of parameters. A PUT makes statements about the code’s behavior for an entire set of possible input values, instead of just a single exemplary input value. It expresses assumptions on test inputs, performs a sequence of actions, and asserts properties that should hold in the final state; that is, it serves as the specification. Such a specification doesn’t require or introduce any new language or artifact. It’s written at the level of the actual APIs implemented by the software product, and in the programming language of the software product. Designers can use them to express intended behavior of the software APIs, developers can use them to drive automated developer testing, and testers can leverage them for in-depth automatic test generation. For example, the following PUT asserts that after adding an element to a non-null list, the element is indeed contained in the list: void TestAdd(ArrayList list, object element) { PexAssume.IsNotNull(list); list.Add(element); PexAssert.IsTrue(list.Contains(element)); } PUTs separate the following two concerns: - The specification of the correctness properties of the code under test for all possible test arguments. - The actual “closed” test cases with the concrete arguments. The engine emits stubs for the first concern, and you’re encouraged to flesh them out based on your domain knowledge. Subsequent invocations of Smart Unit Tests will automatically generate and update individual closed test cases. Application Software development teams may be entrenched in various methodologies already, and it’s unrealistic to expect them to embrace a new one overnight. Indeed, Smart Unit Tests is not meant as a replacement for any testing practice teams might be following; rather, it’s meant to augment any existing practices. Adoption is likely to begin with a gradual embrace, with teams leveraging the default automatic test generation and maintenance capabilities first, and then moving on to write the specifications in code. Testing Observed Behavior Imagine having to make changes to a body of code with no test coverage. You might want to pin down its behavior in terms of a unit test suite before starting, but that’s easier said than done: - The code (product code) might not lend itself to being unit testable. It might have tight dependencies with the external environment that will need to be isolated, and if you can’t spot them, you might not even know where to start. - The quality of the tests might also be an issue, and there are many measures of quality. There is the measure of coverage—how many branches, or code paths, or other program artifacts, in the product code do the tests touch? There’s the measure of assertions that express if the code is doing the right thing. Neither of these measures by themselves is sufficient, however. Instead, what would be nice is a high density of assertions being validated with high code coverage. But it’s not easy to do this kind of quality analyses in your head as you write the tests and, as a consequence, you might end up with tests that exercise the same code paths repeatedly; perhaps just testing the “happy path,” and you’ll never know if the product code can even cope with all those edge cases. - And, frustratingly, you might not even know what assertions to put in. Imagine being called upon to make changes to an unfamiliar code base! The automatic test generation capability of Smart Unit Tests is especially useful in this situation. You can baseline the current observed behavior of your code as a suite of tests for use as a regression suite. Specification-Based Testing Software teams can use PUTs as the specification to drive exhaustive test case generation to uncover violations of test assertions. Being freed of much of the manual work necessary to write test cases that achieve high code coverage, the teams can concentrate on tasks that Smart Unit Tests can’t automate, such as writing more interesting scenarios as PUTs, and developing integration tests that go beyond the scope of PUTs. Automatic Bug Finding Assertions expressing correctness properties can be stated in multiple ways: as assert statements, as code contracts and more. The nice thing is that these are all compiled down to branches—an if statement with a then branch and an else branch representing the outcome of the predicate being asserted. Because Smart Unit Tests computes inputs that exercise all branches, it becomes an effective bug-finding tool, as well—any input it comes up with that can trigger the else branch represents a bug in the code under test. Thus, all bugs that are reported are actual bugs. Reduced Test Case Maintenance In the presence of PUTs, a significantly lower number of tests cases need to be maintained. In a world where individual closed test cases were written manually, what would happen when the code under test evolved? You’d have to adapt the code of all tests individually, which could represent a significant cost. But by writing PUTs instead, only the PUTs need to be maintained. Then, Smart Unit Tests can automatically regenerate the individual test cases. Challenges Tool Limitations The technique of using white-box code analyses with constraint solving works very well on unit-level code that’s well isolated. However, the testing engine does have some limitations: - Language: In principle, the testing engine can analyze arbitrary .NET programs, written in any .NET language. However, the test code is generated only in C#. - Non-determinism: The testing engine assumes the code under test is deterministic. If not, it will prune non-deterministic execution paths, or it might go in cycles until it hits exploration bounds. - Concurrency: The testing engine does not handle multithreaded programs. - Native code or .NET code that’s not instrumented: The testing engine does not understand native code, that is, x86 instructions called through the Platform Invoke (P/Invoke) feature of the Microsoft .NET Framework. The testing engine doesn’t know how to translate such calls into constraints that can be solved by a constraint solver. And even for .NET code, the engine can only analyze code it instruments. - Floating point arithmetic: The testing engine uses an automatic constraint solver to determine which values are relevant for the test case and the code under test. However, the abilities of the constraint solver are limited. In particular, it can’t reason precisely about floating point arithmetic. In these cases the testing engine alerts the developer by emitting a warning, and the engine’s behavior in the presence of such limitations can be controlled using custom attributes. Writing Good Parameterized Unit Tests Writing good PUTs can be challenging. There are two core questions to answer: - Coverage: What are good scenarios (sequences of method calls) to exercise the code under test? - Verification: What are good assertions that can be stated easily without reimplementing the algorithm? A PUT is useful only if it provides answers for both questions. - Without sufficient coverage; that is, if the scenario is too narrow to reach all the code under test, the extent of the PUT is limited. - Without sufficient verification of computed results; that is, if the PUT doesn’t contain enough assertions, it can’t check that the code is doing the right thing. All the PUT does then is check that the code under test doesn’t crash or have runtime errors. In traditional unit testing, the set of questions includes one more: What are relevant test inputs? With PUTs, this question is taken care of by the tooling. However, the problem of finding good assertions is easier in traditional unit testing: The assertions tend to be simpler, because they’re written for particular test inputs. Wrapping Up The Smart Unit Tests feature in Visual Studio 2015 Preview lets you specify the intended behavior of the software in terms of its source code, and it uses automated white-box code analysis in conjunction with a constraint solver to generate and maintain a compact suite of relevant tests with high coverage for your .NET code. The benefits span functions—designers can use them to specify the intended behavior of software APIs; developers can use them to drive automated developer testing; and testers can leverage them for in-depth automatic test generation. The ever-shortening release cycles in software development is driving much of the activities related to planning, specification, implementation and testing to continually happen. This hectic world is challenging us to reevaluate existing practices around those activities. Short, fast, iterative release cycles require taking the collaboration among these functions to a new level. Features such as Smart Unit Tests can help software development teams more easily reach such levels. Pratap Lakshman works in the Developer Division at Microsoft where he is currently a senior program manager on the Visual Studio team, working on testing tools. Thanks to the following Microsoft technical expert for reviewing this article: Nikolai Tillmann
https://docs.microsoft.com/en-us/archive/msdn-magazine/2015/february/visual-studio-2015-build-better-software-with-smart-unit-tests
CC-MAIN-2022-27
refinedweb
3,020
50.67
URLs adhere to a standard. [scheme:]//[user[:password]@]host[:port][/path][?query][#fragment] The benefit of such a standard is that we might parse out the parts that we're interested in. Before doing that yourself though, it'd be better to check yarl. Yarl stands for Yet Another URL Library and it makes it easy to deal with URLs. Here's an example of how you might use the library. from yarl import URL url = URL('') url.host, url.scheme, url.path, url.query_string, url.query, url.fragment The library can also deal with url encodings that are percent-decoded. A common example of this in a URL would be the whitespace character. url = URL(' world') url.path, url.raw_path, url.human_repr() Finally, it's also good to know that yarl doesn't just parse URLs. It can also be used to build them. There's the .build() constructor. URL.build(scheme="https", host="example.com", query={"a": "b", "number": 1}) But you can also create a URL by chaining together appropriate python operators. It's similar to the syntax in pathlib. URL("") / 'things' % {"prop1": 1, "prop2": "a"} Back to main.
https://calmcode.io/shorts/yarl.py.html
CC-MAIN-2022-05
refinedweb
192
68.16
One. Below is a simple tutorial on how you can use this with web projects to automate creating a standard page template that inherits from a common page base class (in this example: “ScottGu.Test.MyBasePage”), is defined within a common code namespace (in this example: "ScottGu.Test"), and which has a common CSS stylesheet and Javascript script reference pre-set (note: you should probably use the new ASP.NET 2.0 Masterpage feature for the common CSS and Javascript file – but I thought I’d show it here nonetheless). Note: I’m pretty sure this didn’t work with Beta2 builds of VS 2005 – but it is supported with the final release and probably the more recent August CTP builds. Step 1: Define the page you want to become a template The below two files are a sample page I added into a web project. Note that the page derives from a base-page called “MyBasePage”, lives in the “ScottGu.Test” namespace, has two custom namespaces defined with using blocks in the code-behind, and has a stylesheet and client-side javascript file already added to it. The only change I’ve made from the standard page markup is that I’ve replaced the class name of the code-behind file to have the marker name of “$safeitemname$”, and updated the Inherits attribute of the .aspx file to also point to the “$safeitemname$” class. VS 2005 will then use this marker to set an appropriate classname based on the filename selected in the Add New Item dialog below (if you don't set a marker, then VS 2005 will default to just using the same classname as what was defined in the template). Default.aspx ------------------------------------------ <%@ Page Language="C#" AutoEventWireup="true" CodeFileBaseClass="ScottGu.Test.MyBasePage" CodeFile="Default.aspx.cs" Inherits="ScottGu.Test.$safeitemname$ " %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns="" > <head runat="server"> <title>My Sample Page</title> <link href="Common.css" rel="stylesheet" type="text/css" /> <script src="ScriptLibrary/AtlasCore.js" type="text/javascript"></script> </head> <body> <form id="form1" runat="server"> <div> <h1>My Template Page</h1> </div> </form> </body> </html> Default.cs.aspx MyCustomNamespace; using MyCustomNamespace2; namespace ScottGu.Test { public partial class $safeitemname$: MyBasePage { protected void Page_Load(object sender, EventArgs e) { } } } Step 2: Export the Page as a Template To export and re-use the above page, go to the File menu in VS and select the “Export Template” menu item. This will then walk you through the below wizard, where you can choose which project and then which file in the project you want to use as a template: Once you select an item, you can then provide a name for what this template will show up as in the “Add New Item” dialog, an optional icon for the dialog, as well as a help text string. In this example I am going to create a new template I’ll call “MyCustomTemplatePage”. VS will then generate a .zip file containing the item you selected and optionally add it automatically to your current Add New Item dialog (note: this dialog is populated from the C:\Documents and Settings\UserName\My Documents\Visual Studio 2005\Templates\ItemTemplates directory): Step 3: Create a new Page using the Template You can now create new items in your project based on the template you defined (or which you picked up from someone else or downloaded online). To-do this, just choose the usual New File or “Add New Item” menu item in your project to pull up the “Add New Item” dialog. This dialog will include all the standard VS 2005 file items provided by the particular project type you are working on, as well as expose a new “My Templates” section beneath the standard items. Included in the “My Templates” section are all the item templates you've either created yourself (see step 2 above) or imported from others. For example, I can now select the “MyCustomTemplatePage” item, and name the page I want to create (based on the template) “UsingTheTemplate.aspx”. When I select OK, VS 2005 will then add two new files into my project – UsingTheTemplate.aspx and UsingTheTemplate.aspx.cs. These files are based on the template we defined earlier and look like this: UsingTheTemplate.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFileBaseClass="ScottGu.Test.MyBasePage" CodeFile="UsingTheTemplate.aspx.cs" Inherits="ScottGu.Test.UsingTheTemplate " %> UsingTheTemplate.aspx.cs public partial class UsingTheTemplate : MyBasePage Note that they look just like my original template – the only difference is that the classname has been automatically set by VS 2005 to match the filename I entered in the Add New Item dialog, and the CodeFile attribute in the .aspx has automatically been updated to point to the new code-behind filename. I can now quickly work on the page without the hassle of setting my common settings up. Hope this proves useful and saves you some time, Scott This page lists some of the more popular &ldquo;ASP.NET 2.0 Tips, Tricks, Recipes and Gotchas&rdquo; Typically when you work on projects you have a standard approach that you like to use to structure and Hi Dav, If you can send me email I can connect you with someone on the VS team who might know how to-do this. Hope this helps, Scott Txs for the great article. I just have created a multiple project template. It seems that when using this, you cannot assign another name to your projects then defined in the projectcollection. I ask this because we have a naming guideline that all projects are in the format : <Companyname>.<Project>.BL. I want to dynamicly change the projectname when creating the solution. Do you know if there's a way to do this ? Thanks. Hi Sven, Any chance you could send me an email with this question in it? I don't know the answer off the top of my head - but can loop you in with someone who might be able to help. Thanks, Thanks U very much . Defining Custom Item Templates in Web Projects with VS 2005 Visual Studio Magazine Online | C# Corner: Define Your Own Item Templates Did you know what i like most weblogs.asp.net/.../424780.aspx%E8%BF%99%E9%87%8C%E4%BB%8B%E7%BB%8D%E7%9A%84%E6%AF%94%E8%BE%83%E8%AF%A6%E7%BB%86
http://weblogs.asp.net/scottgu/archive/2005/09/09/424780.aspx
crawl-002
refinedweb
1,066
58.62
Hi - Hibernate Interview Questions Hi please send me hibernate interview update count from session - Hibernate update count from session I need to get the count of how many rows got updated by session.saveOrUpdate(). How would I get this? Thanks, mpr hibernate - Hibernate hibernate hi friends i had one doubt how to do struts with hibernate in myeclipse ide its when I run Hibernate Code Generation wizard in eclipse I'm...;Hi Friend, Please visit the following link: Hope that it will be helpful for you. Thanks Hi Radhika, i think, you hibernate configuration... Hibernate; import org.hibernate.Session; import org.hibernate.*; import.... Hibernate Count In this section you will learn different way to count number of records in a table: spring hibernate - Hibernate with hibernate? Hi friend, For solving the problem Spring with Hibernate visit to : Thanks. Thanks Criteria Count Distinct Hibernate Criteria Count Distinct The Hibernate Criteria count distinct is used to count the number of distinct records in a table. Following a way to use... this application it will display message as shown below: select count(distinct Hibernate code problem - Hibernate Hibernate code problem Hi, This is Birendra Pradhan.I want... & Regards Birendra Hi friend, For solving the problem visit to : example code of how insert data in the parent table and child tabel coloums at a time in hibernate Hi friend, I am...: Thanks Search Hibernate Search Where to learn Hibernate Search module? Thanks Hi, Check the tutorial: Hibernate Search - Complete tutorial on Hibernate Search Thanks Struts-Hibernate-Integration - Hibernate Struts-Hibernate-Integration Hi, I was executing struts hibernate...) javax.servlet.http.HttpServlet.service(HttpServlet.java:802) Hi Friend, Please visit the following link: Hope
http://www.roseindia.net/tutorialhelp/comment/96862
CC-MAIN-2015-48
refinedweb
279
54.93
Combined “Change” Maps: Animations & Transitions Combine your $times and $easing values to create entire transitions and animations – all stored in one place and easy to access for consistent “changes” across your project. $changes $changes: () !default; A variable storing the map of all your standardized changes (transitions and animations). Any changes added to the $changes map will be accesible to the change() function by default. Define each change with a name and value, or use interpolation to compose more complex changes. $changes: ( // single animation 'glow': glow time('slow') ease('in-out-quad') infinite alternate, // single transitions 'slide': transform time('fast'), 'fade': opacity time('fade') ease('out-quad'), // interpolate using '#name' (quotes optional) // to build on existing "changes" 'slide-in': #slide ease('out-back'), 'slide-out': '#slide' ease('in'), // or string together multiple "changes" 'sidebar-in': ('#slide-in', '#fade' time('delay')), // or create a 1-to-1 alias 'modal-in': #sidebar-in, ); - Name your changes anything – from abstractions like fade, to concrete patterns like sidebar-in. - Values can be CSS-ready values, references other changes in the map, or format strings to interpolate. Used By @mixin add-changes() @function change() Access a named change in your $changes map. Since 1.0.0: - NEW: Accepts $domap argument, for on-the-fly adjustments - NEW: Accepts $sourcemap argument, for custom source-palette Parameters & Return $name: (string) The name of a change in your configuration (e.g. fade-in) $do: null (map | null) A map of function/ratio adjustments to run on the returned value $source: $changes (map) Optional Accoutrement-format map of changes to use as the origin palette @return (length) The change value requested Requires @function get() [private] Used By @mixin transition() @mixin add-changes() Merge individual change maps into the global $changes variable, in case you want to define changes in smaller groups – such as button-changes, page-changes, etc – before merging them into a single global changes-palette. Parameters & Output $maps: (map...) Pass any number of maps to be merged and added {CSS output} (code block) - An updated global $changesvariable, with new maps merged in. Requires @function multi-merge() @function compile-changes() Compile all the tokens in a change map. This is particularly useful for exporting a static version of the token map with all the Accoutrement syntax removed – e.g. for use in javascript or documentation. Since 4.0.0: - NEW: Provides an export option for change token maps Parameters & Return $map: $changes (map) The map to be compiled $source: $changes (map | null) A map of reference tokens that can be used for resolving changes. (defaults to the global $changes map) @return (map) A copy of the original map, with all token values resolved Requires @function map-compile-with() @mixin animate() Access named animations in your $changes map, and apply them to the animation property. Parameters & Output $names: (string) Named animations to apply {CSS output} (code block) - The requested animations, applied in CSS Example tools.$changes: ( 'fade-in': fade-in 300ms ease-out both, ); .example { @include tools.animate('fade-in'); } .example { animation: fade-in 300ms ease-out both; } @mixin transition() Access named transitions in your $changes map, and apply them to the transition property. Parameters & Output $names: (string) Named transitions to apply {CSS output} (code block) - The requested transitions, applied in CSS Example tools.$changes: ( 'fade': opacity 300ms ease-out, ); .example { @include tools.transition('fade'); } .example { transition: opacity 300ms ease-out; }
https://www.oddbird.net/accoutrement/docs/animate-change.html
CC-MAIN-2022-27
refinedweb
560
50.16
Opened 3 years ago Closed 3 years ago #24926 closed enhancement (fixed) add names to some strongly regular graphs Description some strongly regular graphs should not have their names empty, e.g. SRG_276_140_58_84 should get Haemers-Tonchev Change History (10) comment:1 Changed 3 years ago by - Priority changed from major to minor comment:2 Changed 3 years ago by - Branch set to u/dimpase/graphnames - Commit set to 80726679cee74eaacaab87b88fcd7897b4fbd551 comment:3 Changed 3 years ago by - Reviewers set to Frédéric Chapoton ok if bot is green comment:4 Changed 3 years ago by it's not done yet, I'll add more... :-) But thanks for looking at it. comment:5 Changed 3 years ago by - Commit changed from 80726679cee74eaacaab87b88fcd7897b4fbd551 to dbdbd52a538261377d29cab88f02110a59a3fde0 Branch pushed to git repo; I updated commit sha1. New commits: comment:6 Changed 3 years ago by it also needs a bit of work on py3 side - I notice that there is no from __future__ import division in the file I hack on, and adding it breaks some stuff. comment:7 Changed 3 years ago by - Commit changed from dbdbd52a538261377d29cab88f02110a59a3fde0 to 2f6905462bb0148ade9bb0b553b3dc0698590dc2 Branch pushed to git repo; I updated commit sha1. New commits: comment:8 Changed 3 years ago by - Status changed from new to needs_review OK, done. I wonder how much code in Sage still needs to be dealt in regard of py3 division. We certainly seldom want automatic conversion into floats... comment:9 Changed 3 years ago by - Status changed from needs_review to positive_review ok, thanks. Concerning division, this file was maybe one of the largest can of issues remaining. comment:10 Changed 3 years ago by - Branch changed from u/dimpase/graphnames to 2f6905462bb0148ade9bb0b553b3dc0698590dc2 - Resolution set to fixed - Status changed from positive_review to closed New commits:
https://trac.sagemath.org/ticket/24926
CC-MAIN-2021-31
refinedweb
292
56.79
The long-awaited Nuxt 3 beta was launched on 12 October 2021, making it a momentous day for the Nuxt and Vue developer ecosystems. This is an updated version that has been rearchitected for improved performance and lighter builds. And in this article, we will look at the new features in Nuxt 3, as well as the installation process and how to migrate your existing Nuxt apps (Nuxt 2) to this latest version. Migrating from Nuxt 2 to Nuxt 3 N.B., before we begin, please keep in mind that Nuxt 3 currently only supports Node v14 or v16. While there is currently no stable migration technique for a smooth transition from Nuxt 2 to Nuxt 3, Nuxt Bridge (which we will discuss in more detail later) can be used to try out some of the new capabilities of Nuxt 3 in prior versions. To do this, first delete any package-lock files ( package-lock.json or yarn.lock) from your project, then remove the Nuxt dependency and create a new entry in your package.json file for the most recent version of nuxt-edge: - "nuxt": "^2.15.0" + "nuxt-edge": "latest" The next step is to reinstall all of your dependencies: npm install # OR yarn install And you are ready to go! You can also choose to install Nuxt Bridge as a development dependency: npm install -D @nuxt/[email protected]:@nuxt/bridge-edge # OR yarn add --dev @nuxt/[email protected]:@nuxt/bridge-edge However, doing so will also require updating your package.json file to reflect the fact that Nuxt will now generate a Nitro server as a build result. Starting a new project The process of creating a new application in Nuxt 3 differs significantly from earlier versions. Because Nuxt 3 is still in beta, you’ll have to start by initializing a fresh app: npx nuxi init project-name The next step is to install the dependencies that were included in the generated package.json file: cd project-name npm install # OR yarn install Once these steps are completed, we can go ahead and start our application: npm run dev # OR yarn dev If everything works fine, a browser window should automatically open for with an output like in the image below: What’s new in v3 Nitro Engine Nuxt 3 has a new cross-platform server engine that adds full-stack capabilities to Nuxt applications. Nitro engine also includes out-of-the-box serverless functionality and is believed to be the first JavaScript application server that works with a wide range of current cloud hosting services. This makes integrating APIs into your Nuxt apps a breeze. To use this functionality, just create a new /server directory in your project root folder. This directory will hold your project’s API endpoints and server middleware, and Nuxt will automatically read any files in the /server/api directory to create API endpoints: // server/api/hello.js export default async (req, res) => { return { foo: "bar", }; }; This will generate a new API endpoint that can be accessed at. Server middleware Nitro Engine also supports adding middleware to API endpoints. Similar to how an API works, Nuxt will read any files in the /server/middleware directory to generate server middleware for your project. But unlike API routes, which are mapped to their own routes, these files will be executed on every request. This is usually done so that you may add a common header to all responses, log responses, or alter an incoming request object. Below is an example that adds someValue to every API request: // server/middleware/addValue.js export default async (req, res) => { req.someValue = true } Nuxt Bridge Nuxt 3 now includes Nuxt Bridge, a forward-compatibility layer that enables you to access many of the new Nuxt 3 features by simply installing and activating a Nuxt module. You can use Nuxt Bridge to ensure that your project is (nearly) ready for Nuxt 3 and that your developers have the greatest experience possible without having to do a large rewrite or risk breaking modifications. While we’ve already discussed how migration with Nuxt Bridge works, you can learn more about Nuxt Bridge here. NuxtApp Nuxt Context, which provides access to runtime app context from within composables, components, and plugins, has now been renamed to NuxtApp in Nuxt 3. And within components and plugins, we can access NuxtApp with useNuxtApp: import { useNuxtApp } from "#app"; function useMyComposable() { const nuxtApp = useNuxtApp(); // access runtime nuxt app instance console.log(nuxtApp); } In addition, the inject function, which makes functions and/or values available across your Nuxt application, is now known as provide. For example, creating a plugin that logs a provided name to the console in Nuxt 2: // plugins/hello.js export default ({ app }, inject) => { inject("hello", (name) => console.log(`Hello ${name}!`)); }; // Can be accessed using this.$hello('Elijah') In Nuxt 3, it becomes this: const nuxtApp = useNuxtApp() nuxtApp.provide('hello', (name) => console.log(`Hello ${name}!`)) // Can be accessed using nuxtApp.$hello('Elijah'); New file structure The pages/ directory is now optional in Nuxt 3, and if it is not there, Nuxt will not include the vue-router dependency. Instead, the new app.vue serves as the core component of your Nuxt application; everything you add to it (JS and CSS) will be global and included on all pages. This is advantageous when working on a one-page application, such as a landing page, or an application that does not require routing. Composables directory Nuxt 3 also includes support for a new composables/ directory that is used for auto-importing Vue composables into your application. If you are not already familiar with what composables are in Vue, this was introduced in Vue 3, and you can learn more about composables here. With the Nuxt composable directory, we can easily create both named and default composables. Example: // composables/useFoo.js import { useState } from '#app' export const useFoo = () => { return useState('foo', () => 'bar') } Our composable is exported as useFoo in this case; if no export name is supplied, the composable will be accessible as the pascalCase of the file name without the extension. They are also auto-imported, and we can access them in any page or component: <template> <div> {{ foo }} </div> </template> <script setup> const foo = useFoo() </script> Vue 3 and Vite support Nuxt 3 was designed to work with Vue 3. Because Nuxt 3 is developed in Vue 3, you’ll have access to features like the Composition API, enhanced module imports, and better overall app speed. Vite support is included in Nuxt 3, and it is backward compatible with Nuxt 2. Conclusion In this post, we’ve gone through the new features in Nuxt 3, as well as how to convert existing Nuxt apps to this newest version. You should keep in mind that Nuxt 3 is still in beta, so anticipate things to break. It is also recommended that you do not utilize it in production until the first stable release..
https://blog.logrocket.com/whats-new-nuxt-3/
CC-MAIN-2022-40
refinedweb
1,157
50.67
check the run.sh script located in the docker folder We are given a executable to download with the description So you want to be a pwn-er huh? Well let's throw you an easy one ;) Check for the easy stuff Running files says its a 32 bit elf but before we open it up ida checking for a buffer over flow resulted in a seg fault λ cat input | ./warmup -Warm Up- WOW:0x40060d > Segmentation fault (core dumped) The address after wow is probably the return address we need to overwrite. The python script to do this is. from pwn import * #context.log_level=True if __name__ == "__main__": bufferSize = 72 filler = 'a' * bufferSize r = remote('localhost', 1235) address = r.recvuntil(">") print address address = address.split(":")[1] address = address.strip("\n>") address = p64(int(address, 16)) print address payload = filler + address r.sendline(payload) print r.recvline() Executing script λ python exploit.py [+] Opening connection to localhost on port 1235: Done -Warm Up- WOW:0x40060d >aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\x06@\x00\x00\x00\x00\x00 FLAG{LET_US_BEGIN_CSAW_2016}
https://paxson.io/csaw2016-warm-up-50/
CC-MAIN-2021-49
refinedweb
174
68.36
io query and will return a list of documents where the given words appear. 1. Your... the words specified appear closer to one another. For example, if you search print print How to print JFrame All Componant? Please visit the following link: record management application - Java Beginners record management application write a small record management application for a school.Tasks will be Add record, Edit record,Delete record, List records. Each record contains: name(max 100 char), Age,Notes(No Max.Limit J2ME Record Store MIDlet Example J2ME Record Store MIDlet Example This is a simple program to record data and print... and delete the record: RecordStore r_store; r_store =  Print Print In system.out.println,what meant ln..? System: It is a class made available by Java to let you manipulate various operating system... into the stream and, as opposed to print() method, gets you to the new line after the text sorting student record - Java Beginners . Insert Record"); System.out.println("2. Delete Record"); System.out.println...sorting student record Program in java for inserting, recording...("insert"); //do ur work here } public void delete(){ System.out.println delete record delete record how to delete record using checkbox and button in php We are providing you the jsp code that displays the database table...=conn.createStatement(); for(int a=0;a<10;a++){ st.executeUpdate("delete from book where Java FileOutputStream Example Java FileOutputStream Example In this section we will discuss about the Java IO FileOutputStream. FileOutputStream is a class of java.io package which... example a message will print on the console and the content of abc.txt file Print Form - Java Beginners want to get Print of that forms Contents,How I can Do it with JAVA SWING,plz...:// Hope that it will be helpful...Print Form Hello Sir I have Created Admission Form when user fills Java delete file if exists Java delete file if exists Hi, Hi how to delete file if exists? I need example code of java delete file if exists. Thanks Hi, following code can be used: String tempFile = "C:/mydir/myfile.txt"; // delete jsp delete jsp <%@ page language="java" contentType="text/html...;<br/> <input type="submit" value="Delete record"/></center>...; charset=ISO-8859-1"> <title>Delete Student</title> </head> io - Java Beginners . Thanks Amardeep Java IO PrintWriter Java IO PrintWriter In this tutorial we will learn about the the PrintWriter class in Java. java.io.PrintWriter class is used for format printing of objects... the PrintWriter in the Java applications. In this example I have created Java IO LineNumberReader Java IO LineNumberReader In this tutorial we will learn about the LineNumberReader in Java. java.io.LineNumberReader class extends... are kept into a buffer and this class keeps the record of line numbers JDBC Select Record Example JDBC Select Record Example In this tutorial we will learn how select specific record from table use mysql JDBC driver. This select... all row record that user_name =User1.The code of " JDBC Delete Row In Table Example JDBC Delete Row In Table Example : In this tutorial we will learn how delete... or more specific row delete from table that follow any given condition. If any datrabase or table not exist first create and enter record Java IO FilterWriter Java IO FilterWriter In this example we will discuss about the FilterWriter...(); bw.write("Java IO FilterWriter Example"); System.out.println("Data is written... an example is being given which demonstrates about how to use Java FilterWriter How to delete a character from a file in java - Java Beginners /beginners/ Thanks I...How to delete a character from a file in java I'm not gettting how to remove a character from a file in java....could any one help me out??  Edit the record. Edit the record. sir, I have a table consist of huge data.I have... to previous edited row or edit the previous record of the previously edited...;/form> </body> </html> 2)edit.jsp: <%@page language="java Java IO SequenceInputStream Example Java IO SequenceInputStream Example In this tutorial we will learn about...; started form the offset 'off'. Example : An example... or concatenate the contents of two files. In this example I have created two text How to delete files in Java? , we use the delete() function to delete the file. Given below example... Delete a File using File Class Object Delete a File using File Class Difference between Java IO Class - Java Beginners Difference between Java IO Class What is the difference in function between Two set of Stream class as mention below- 1)FileInputStream... information. Thanks Hibernate delete Query to use HQL delete query. An example is being given regarding how delete query may... query is used to delete the fields, field records, table, etc. In our example we will delete the field's record. To do so at first I have created a table Java Programming Implement a virtual print queue Java Programming Implement a virtual print queue Implement a virtual print queue. A single print queue is servicing a single printer. Print... records: q,3,10 is a q type record which indicates that a print job, # 3, shall print - JSP-Servlet print write easy program for printing a page? Hi Friend, Please visit the following link: Hope that it will be helpful for you. Print Only Forms Contents - Java Beginners the following link: Only Forms Contents Hello Sir I Have Created Simple Registration Form with Database Connectivity, Now I Want To Print Registration form Java IO OutputStreamWriter "); bw.newLine(); bw.write("Java IO OutputStreamWriter Example...Java IO OutputStreamWriter In this section we will learn about the Java..."); osw = new OutputStreamWriter(os); osw.write("Java IO How to print this in java? How to print pattern in Java? How to print a particular pattern in Java...; How to print this in java add record to database - JDBC add record to database How to create program in java that can save record in database ? Hi friend, import java.io.*; import java.sql....); if(i!=0){ out.println("The record has been inserted JDBC Delete Statement Example .style1 { text-align: center; } JDBC Delete statement Example A JDBC delete statement deletes the particular record of the table. At first create...: Record deleted Successfully.... Download this example JDBC: Delete Record using Prepared Statement JDBC: Delete Record using Prepared Statement In this section, we will discuss... statement. You can delete any specific record under some condition using WHERE... of string type and returns int. Example : In this example, we are deleting record JSP Delete Record From Table Using MySQL . In this tutorial you will learn that how to delete a record of a database table in JSP. In this example we will discuss about how to delete a record of database table...JSP Delete Record From Table Using MySQL This tutorial explains you that File Java IO File In this section we will discuss about the File class in Java..., numbers etc and may arranged in string, rows, columns, lines etc. In Java we can also create a File to store the data. To create file in Java a class named dotmatrix print with JasperReports - Development process a print preview of the page. Is this possible with Java, or maybe JasperReports... that, this link will help you. print with JasperReports Hello, I was wondering how Print the URL of a URLConnection Print the URL of a URLConnection  ... it. In the example we open the connection by using the openConnection() method. After... to display the assign URL. Here is the Output of the Example Write a query to delete a record from a table Write a query to delete a record from a table Write a query to delete a record from a table Hi, The query string for the delete operation is as follows- delete from employee where id='35'; Thanks Java Print Dialog Java Print Dialog Using java.awt.print.PrinterJob and javax.print.attribute.PrintRequestAttributeSet. I call .printDialog(ps) and the standard print dialog is displayed with options preset to my chosen attributes. Now I can delete delete how delete only one row in the database using jsp.database... type="button" name="edit" value="Delete" style="background-color:red;font-weight... = conn.createStatement(); st.executeUpdate("DELETE FROM employee WHERE empid To print initials To print initials import java.util.Scanner; class initials { String a ; int e ; char f ; int b ; int c ; char d; Scanner sc = new... link: print rectangle pattern in java print rectangle pattern in java * * * * * * * how to generate this pattern in java?? Hi friend try this code may this will helpful for you public class PrintRectangle { public static void main how to print - Java Beginners how to print how to print something on console without using System.out.print() method ? Hi Friend, You can use PrintWriter to write anything on the console. import java.io.*; public class Print{ public static Using a Random Access File in Java C:\nisha>javac RandAccessFile.java C:\nisha>java RandAccessFile Enter File name : Filterfile.txt Write Successfully Download this example. The another program reads print a rectangle - Java Beginners print a rectangle how do I print a rectangleof stars in java using simple while loop?Assuming that the length n width of the rectangle is given. Hi friend, I am sending running code. import java.io. Java Print the all components Java Print the all components This is my code. Please tell me...; ImageIcon images; Container c; Employee_report f1; JButton print; String s,days...(td); np=ge-td; net=Double.toString(np); data = createData(); print=new JDBC Delete All Rows In Table Example JDBC Delete All Rows In Table Example: In this tutorial provide the example of how to delete all records from table using mysql ...; driver and java class "DeleteAllRows" that import all related Simplest way to print an array in Java Simplest way to print an array in Java Simplest way to print an array in Java JDBC Insert Record element in the table.Finally the println print the required Insert record out put... JDBC Insert Record  ... Record. In this code we have a class JdbcInsertRecord.Inside this class Java delete non empty directory Java delete non empty directory This section demonstrates you how to delete a non empty directory. It is easy to delete a directory if it is empty by simply calling the built in function delete(). But if the directory is not empty Print in a long paper - Java Beginners Print in a long paper how to print text in long paper?? each print text, printer stops. not continue until the paper print out. Thanks Java IO OutputStream Java IO OutputStream In this section we will read about the OutputStream class...) throws IOException Example : An example... to the specified file. In this example I have tried to read the stream of one file java - file delete - Java Beginners java - file delete I will try to delete file from particular folder... will try to delete these files. But it doesn?t delete from this folder. My code...){ try { File delete = new File (incurrentFile); System.out.println Write a java program that prints the decimal representation in reverse. (For example n=173,the program should print 371.)c Write a java program that prints the decimal representation in reverse. (For example n=173,the program should print 371.)c class rose { int n...); System.out.println("\nReverse the number"+i); S.out(); } } print Java FileInputStream Java FileInputStream In this section we will discuss about the Java IO... of bytes. Syntax : public long skip(long n) throws IOException Example : In this example I have created a class named ReadFileInputStream.java Delete Cookie Delete Cookies In the following program, you will learn how to delete the cookie through setting session. In the given example, we have set the value... cookie value echo "<br/>"; print_r($_COOKIE); # view all How to Print a Stack Trace Message How to Print a Stack Trace Message Debugging of Java program requires... of the Exception class to print errors to debug the process. For example... times you have to print the detailed error message on the console How to print the following pattern in java? How to print the following pattern in java? How to print the following pattern in java? he he is he is going he is going in import java.io.*; class StringPattern { public static void main(String[] args How to Print a Stack Trace Message How to Print a Stack Trace Message As we have seen that java provides a method getMessage() method that is used with an object of the Exception class to print J2ME delete file - Java Beginners J2ME delete file How do i delete a textfile on a mobile phone using j2me? Hi Friend, Please visit the following link: Hope that it will be helpful for you. Thanks Print the following format Print the following format how to print the following format given string "00401121" in java 0-** 1-* 2-* 3- 4 how to write a program in java to print numbers in equalateral triangle how to write a program in java to print numbers in equalateral triangle the output must be 1 324 76589 Here is an example of pattern 1 2 3 4 5 6 7 8 9 Example: public class NumberTriangle{ public How to Print Array in JavaScript How to Print Array in JavaScript In this section you will learn about Array...=mycity.indexOf["Agra"]//return the index of Agra Now, here is the example how...<h1>Java Script Array example</h1><p>
http://www.roseindia.net/tutorialhelp/comment/81354
CC-MAIN-2014-52
refinedweb
2,253
65.93
In Java, objects are created with "new" keyword. " Java new" allocates memory to the newly created object at runtime. Observe the following on Java new Keyword, then we will go into details. public class Employee { int salary = 5000; public static void main(String args[]) { Employee emp1 = new Employee(); System.out.println("Employee Salary Rs."+emp1.salary); } } Employee emp1 = new Employee(); By program wise it it simple code. emp1 is an object of Employee class. The Java new keyword allocates memory for the newly created object emp1. Generally an object takes 4 bytes of memory. The constructor Employee(), creates an object of Employee but without name, The nameless object created by the constructor and returned is given name called emp1. With emp1 you call call a method or instance variable etc. Finally to say, the constructor creates an object, new allocates memory for the newly created object. More detailed explanation is available on Java new in the following two tutorials clearly with Programs and Screenshots. 1. Java Reference Variables – Objects – Anonymous objects 2. First Java Program 2 thoughts on “Java new Keyword” sir how to find object size in java. you said 4 bytes memory that means 64 bits how it comes. nice one…………. thanks sir
https://way2java.com/java-introduction/java-new-keyword/
CC-MAIN-2020-50
refinedweb
205
50.43
This section describes the XFN naming model from several perspectives. The primary services provided by a federated naming system are mapping a composite name to a reference and providing access to attributes associated with a named object. This section defines the elements of the XFN naming model. The smallest, indivisible component of a name is called an atomic name. For example, the machine name nismaster or the user name chou. An atomic name may have one or more attributes, or no attributes at all (see "Attributes"). A. A. Attributes may be applied to named objects. Attributes are optional. A named object can have no attributes, one attributes, or multiple attributes. Each attribute has a unique attribute identifier, an attribute syntax, and a set of zero or more distinct attribute values. Attributes are indicated by the dotted lines in Figure 21-1 above.. A compound name is a sequence of one or more atomic names. An atomic name in one context can be bound to a reference to another context of the same type, called a subcontext. Objects in the subcontext are named using a compound name. Compound names are resolved by looking up each successive atomic name in each successive context. A familiar analogy for UNIX users is the file naming model, where directories are analogous to contexts, and path names serve as compound names. Furthermore, contexts can be arranged in a "tree" structure, just as directories are, with the compound names forming a hierarchical namespace. For example: UNIX: usr/local/bin. UNIX atomic names are ordered from left to right and are delimited by slash (/) characters. The name usr is bound to a context in which local is bound. The name local is bound to a context in which bin is bound. DNS: sales.doc.com. DNS atomic names are ordered from right to left, and are delimited by dot (.) characters. The domain name com is bound to a context in which doc is bound. doc is bound to a context in which sales is bound. X.500: c=us/o=doc/ou=sales. An X.500 atomic name comprises an attribute type and an attribute value. Atomic names are known as relative distinguished names in X.500. In this string representation, X.500 atomic names are ordered from left to right, and are delimited by slash (/) characters. An attribute type is separated from an attribute value by an equal sign (=) character. Abbreviations are defined for commonly used attribute types (for example, "c" represents country name). The country name US is bound to a context in which doc is bound. The organization name doc is bound to a context in which the organizational unit name sales is bound. A). Atomic names and reference addresses may also be resolved relative to one or more namespaces. By default, FNS provides six namespaces: org (for organization), site, host, user, service, and fs (for files). FNS policies are used to determine how names associated with namespaces relate to each other. For example; a user is named sergei in the user namespace and is identified as /user/sergei. A calendar application is named in the service namespace and is identified as /service/calendar. With this system, you can then identify Sergei's calendar service as: /user/sergei/service/calendar. (See "Introduction to FNS and XFN Policies" for more information on namespaces and how they are used.) If an application is expecting you to type a user name, the application can include the namespace identifier user/ in front of names that you enter. If the application needs to name one of the user's services, such as the user's default fax machine, it can append the service namespace and the name of the service (/service/fax), to the input supplied. Hence, a fax tool might take as input the user name jacques and then compose the full name user/jacques/service/fax for the default fax of the user jacques. Similarly, to access a person's calendar, you just need to type the person's user name. The application takes the input, raj, and uses it to construct the composite name, in this case, user/raj/service/calendar. An XFN link is a special form of a reference that is bound to an atomic name in a context. Instead of an address, a link contains a composite name. Many naming systems support a native notion of link that can be used within the naming system itself. XFN does not specify whether there is any relationship between such native links and XFN links. Every XFN name is interpreted relative to some context, and every XFN naming operation is performed on a context object. The initial context object provides a starting point for the resolution of composite names. The XFN interface provides a function that allows the client to obtain an initial context. The policies described in Chapter 22, FNS Policies, specify a set of names that the client can expect to find in this context and the semantics of their bindings. This provides the initial pathway to other XFN contexts. Users experience federated naming through applications. Typically, the user does not need to compose or know the full composite name of objects because the application takes care of constructing the composite names. This allows the user to interact with XFN-aware applications in a simple, intuitive, and consistent manner. Users. The way that client applications interact with XFN to access different naming systems is illustrated in a series of figures. Figure 21-2 shows an application that uses the XFN API and library. Figure 21-3 shows the details beneath the API. A name service that is federated is accessed through the XFN client library and a context shared object module. This module translates the XFN calls into name service-specific calls. Many clients of the XFN interface are only interested in lookups. Their usage of the interface amounts to: Obtaining the initial context Looking up one or more names relative to the initial context Once the client obtains a desired reference from the lookup operation, it constructs a client-side representation of the object from the reference.
http://docs.oracle.com/cd/E19455-01/806-1387/6jam692de/index.html
CC-MAIN-2016-07
refinedweb
1,023
64
I'm not sure how to ask this but here it goes. I am building a C++ application, in this case I'm building it in Code::Blocks with a MingW compiler. I want to incorporate/utilize/whatever, SQLite into my applicaiton by including (#include) the sqlite C code header file sqlite3.h in my project file. This question is not necessarily about SQLite but it's about using the sqlite3 source code file written in the C Programming Language in my C++ program (statically linking) not DLL. If the sqlite3.c (source code file) is written in c, how can I compile my application written in C++ (I'm using a C++ compiler). Here's what I have. 1 - My project file written in C++. 2 - I have included the header file for SQlite written in C. 3 - I have placed the C source code file in my Project File directory. (maybe thats not correct but thats what Iv'e done.) If the C source code file is written in C and I can't compile it in a C++ compiler (so I'm told) then how do I compile a SQlite cource code file in any compiler (a C compiler) if it is not called by a Main() function which in this case is written in C++? As I said, this is not a question about SQlite but it is a conceptual question to understand the process of statically linking a C source code file into a C++ project. Any help with this would be greatly appreciated. Thanks If the C source code file is written in C and I can't compile it in a C++ compiler (so I'm told) They told you wrong. There is no problem at all mixing C and C++ files in the same program, I've done it several times. It's all in the file extension, the compiler sees a *.c and knows that it has to compile it as C code, and if it sees *.cpp extension the compiler compiles it as c++ code. No other special things have to be done to the source files or the compiler flags. sqlite.h already contains the preprocessor flags needed to tell the compiler that all the functions are written in C instead of C++ so that the header file can be included in c++ programs. Some C header files are not C++ safe. If you get compiler and/or linker errors when you try to do so, then "guard" the #include <someCheader.h> directives with extern "C" {...}. Example: #ifndef MYCPPHEADER_H #define MYCPPHEADER_H // My C++ header file extern "C" { #include <someCheader.h> } . . . #endif // MYCPPHEADER_H Thanks allot for that. It's the first time I've had a clear explanation on this. Part of the reason for the confusion is a section in the book: 'Using SQLite', Orielly book (August 2010) which says the below. Is this just wrong or are they being cautious about mixing C and C++? Just remember that the core SQLite library is C, not C++, and cannot be compiled with most C++ compilers. Even if you choose to wrap the SQLite API in a C++ class-based interface, you’ll still need to compile the core SQLite library with a C compiler. Secondly, if you can easily mix C and C++ code like that then why do we need all those C++ wrappers out there for wrappign C code for SQLite. Is that more about the style of the interface (API)? Thanks Is this just wrong or are they being cautious about mixing C and C++? No, it is correct. When you are using a compiler like GCC (within MinGW distribution), this is actually the GNU Compiler Collection which includes both a C compiler and a C++ compiler (at least, but often a few others like Fortran, Ada, and possibly Objective-C and Java compilers). What Ancient Dragon explained about extensions *.c vs. *.cpp is that CodeBlocks will invoke the gcc.exe program to compile all the source code, and that program is made to check the file extension and compile the code accordingly with the appropriate compiler (i.e., its C or C++ compiler). GCC uses the same backend for all its compilers and it uses one linker for all linking tasks, so, once individual source files were compiled, it doesn't make a difference from which original language they were compiled from, they all just link together (as long as they have the appropriate extern "C" wrapping in the headers in between C and C++ code). So, SQLite is correct in saying you can't compile their code with a C++ compiler, only with a C compiler, but that is already what is happening under-the-hood when you add the C code to your project. The more pedantic way to do this is to take all the C code from that external library and compile it into a static or shared library, and then link that static library to your compiled C++ code. It is generally considered somewhat bad style to put together many source files for different libraries into a single "project", but it works as long as the compiler in question can do the dispatching to the appropriate compiler for each source file (as does GCC and most other compiler suites). Secondly, if you can easily mix C and C++ code like that then why do we need all those C++ wrappers out there for wrappign C code for SQLite. Is that more about the style of the interface (API)? Yes, it is mostly about style. The more you program in C++ the more you develop a certain distaste for C-style code (opaque-pointers, struct + free functions instead of classes, lots of type unsafe code, etc.). Then, there are many common and recommended practices in C++, such as resource encapsulation (or RAII), which are generally beneficial to the robustness of the code and also simplifies the source code (e.g., being able to use the compiler-defaulted destructor, copy-assignment, and copy-constructor). If you want to abide by those coding practices, which are often incompatible with C-style coding (due to lack of classes, references or strong type safety), then you need to wrap the C-style code (that interfaces the external library) very early on such that your code only is not "infected" by the C-style code too deeply. And then, there are technical reasons, for instance, inter-operability with standard C++ libraries, like wrapping a networking library into a set of classes derived from C++ iostream base classes such that anything that can already be printed to the console or a file (i.e., for which you have overloaded the iostream << and >> operators) can also be sent over a network connection. Or making an external C library look like a STL container, and so on. Another technical reason is for a technique called the "compilation firewall" (or "PImpl idiom", or "Cheshire Cat") whose aim is to isolate the external dependency completely from your project's code, which is often a good idea when the external library has a C interface or is of doubious quality of implementation. To do that, you already need to implement a wrapper that hides away the external dependency in a separate cpp file while exposing functions and classes in its header which show no traces of the external dependency, so, you might as well write that wrapper in good C++ style. Finally, C is the lingua franca of external library interfaces (this is mostly for technical reasons, mostly, and partly for legacy reasons). Often, the original source code of the library will not be in C, often in C++. So, in this case, since, as the library developer, you already have to create wrapping code to make the C++ source code look like C source code, it is not so much trouble to also make the wrapping code that does the opposite, for those who will want to use your library in a C++ project. And there are technical reasons why you can't just skip the C interface, and go with C++ all the way, so, you very often see libraries that have a C API and a C++ wrapper available for it. Thanks Mike.. Thats a great explanation. I understand now.
http://www.daniweb.com/software-development/cpp/threads/435938/using-c-source-code-in-a-c-application
CC-MAIN-2014-10
refinedweb
1,391
66.67
Client Logic for an Accpac 6 Web Form Last week we talked about creating Accpac 6 Web UIs (). Part of the process is creating the XML representation of the Web Form which we discussed previously:. Now suppose you have an XML form designed either in an XML editor or using our SwtUIDesigner and you want functionality beyond that which is given to you by default. By default you have record navigation, save and delete. From last week’s article you will now have a simple runnable project. So where do you put your client side code? Within the client files is a file xxFeatureModule.java which contains: /* * Copyright 2010 Sage Software Inc. All rights reserverd. */ package com.sage.accpac.SS60A.ss1005.client; import com.sage.swt.client.ui.builder.AbstractSynchronousFeatureModule; import com.sage.swt.client.ui.builder.InstanceContext; public class SS1005FeatureModule extends AbstractSynchronousFeatureModule { public String getDebugName() { return "SS1005 Feature Module"; } protected boolean handleInstanceLoaded(InstanceContext context) { // TODO: Handle what happens when an instance context is loaded. // Return true if the handling was successful; false otherwise. return true; } } This is where you put your code. The handleInstanceLoaded routine is provided for you to hook your code in. Basically this is called once the UI has initialized and the XML form has been processed and everything has been created. At this point you can hook into any UI controls, data sources or do any other initialization you require. The context that is passed into this routine is the object from which you can get to everything else in the UI. It contains the collection of controls on the form, collection of datasources , etc. Below is a snippet of code for a simple handleInstanceLoaded routine that retrieves a button from the context by calling its getWidgets() method. Then it calls addClickListener() to add a listener that will be called whenever the button is clicked. protected boolean handleInstanceLoaded(InstanceContext context) { DefaultAllClickListener defaultAllListener = new DefaultAllClickListener(context); SwtButton btnDefaultAll = (SwtButton) context.getWidgets().get ( UIConstants.WidgetIDs.CONFIG_BTN_DEFAULTALL ); if (null != btnDefaultAll) btnDefaultAll.addClickListener(defaultAllListener); return true; } private class DefaultAllClickListener implements ClickListener { public DefaultAllClickListener(InstanceContext context) { } public void onClick(Widget sender) { SwtMessageDialog.showMessageDialog( UILanguageResources.AppContent.DIALOG_RESTORE_DEFAULT.getValue(), UILanguageResources.AppContent.DIALOG_CONFIRM_DEFAULT.getValue(), SwtMessageDialog.ResponseButtonSetType.YES_NO, SwtMessageDialog.MessageType.CONFIRM, "", new MessageDialogListener[] {new ConfirmDefaultAllListener()}); } } private class ConfirmDefaultAllListener implements MessageDialogListener { public void onRespond(MessageDialogEvent evt) { SwtMessageDialog.ResponseButtonType response = evt.getResponse(); if (response == SwtMessageDialog.ResponseButtonType.YES) { defaultConfigInfo(popupContext); } } } Notice that we defined a new class DefaultAllClickListener which implements ClickListener. Basically this is defining the class for the object that will be called whenever a button is pressed. So in handleInstanceLoaded we call “new DefaultAllClickListener(context)” to create a new object in the DefaultAllClickListener class. This object will now be called whenever the button is pressed. In Java this is the typically way you get event notifications. There is nothing like a COM Event special type of method. Event handlers are just regular methods in regular classes. You hook them up by passing them to the object that does the notifying, usually by some sort of addXXXListener() type method call. It’s up to each routine that does notifications to keep a list of all the objects they need to notify and to call each one in turn whenever anything happens. This is true for all UI events, notice that even the confirmation dialog displayed has a ConfirmDefaultAllListener() that will be called when the button is pressed on this dialog. All notifications are asynchronous like this. You can’t call a UI action and expect to wait (in the code) for a response. If VB we could just do answer = MsgBox () and our code would wait for the user to choose Yes or No. In the browser, everything is asynchronous, nothing waits, everything is via notifications. This is a different metaphor than people are used to. In languages like VB some things are asynchronous and work via event notifications and some things are synchronous. The big difference is that calls to the server are asynchronous, so whenever you make an SData call, you are notified via this mechanism when something arrives. Contrast this to VB where you make a server call, your code waits for the response and no more code is executed until you get it. In the web world this could take quite a long time and the browser would be completely unresponsive if no code executed until you got this response. This is the world of AJAX (Asynchronous JavaScript and XML ). AJAX is the key to creating rich internet applications in the Browser. If we didn’t use this, then the input forms would be quite boring lists of titles and edit boxes followed by a submit button, where nothing happens until you hit submit. This is another reason that you want to put groups of View calls in your server module, where everything works synchronously as normal. Generally you only want to make one server call at a time, since then you don’t need to chain together a number of responses, plus you get the performance benefit of only making one server call over the Internet. Here we’ve been putting the code in the xxFeatureModule.java file, but unlike VB, there are no restrictions on how many source files you have and no rules that certain things have to be in certain files. So you can freely create as many class files as you like and organize your code in whatever manner you like. The nice thing is that you can follow industry best practices and aren’t under constraints like an event listener has to be in a special file in order to be called. So the expectation would be that you can create common Java libraries to share over UI projects and that you can keep your class files small and maintainable without putting everything including the kitchen sink into the xxFeatureModule.java file. One aspect of Java that trips up VB (and C) programmers is the use of inheritance. When using an API or framework in C or VB, basically you look for all the functions, properties and events you can use. If you take this approach with Java, you will probably find that you are having trouble finding what you are looking for. This is because Java supports inheritance in a proper object oriented manner. So often the paradigm isn’t to do something by calling API functions, rather what you do is extend a class that does much of what you want and then just add the code that’s needed to make the difference. People new to Java often take a bit of time getting used to this. If you are stuck and aren’t finding an API that you are sure must be provided, instead look for a class that is along the lines of what you need that you can extend. This code is Java and definitely not JavaScript. Yet this is what we are writing to run in the Browser. To produce the final runnable code we have to feed this through the GWT Compiler to get it compiled into JavaScript. The GWT Compiler will produce 6 versions of JavaScript from this code, one optimized for each major Browser family including WebKit (Safari and Chrome), Gekko (Firefox) and separate versions for IE 6 and 8. This then is the final code that you would deploy to your customer’s web servers to run. In the meantime while you are developing, you keep working in Java. You can run this code as a Java application inside the Eclipse IDE. You can use the Eclipse Java debugger to single step through the code, set breakpoints and examine variables. You can also use all sorts of other Java tools to make yourself more productive like JUnit (), Emma () or TPTP (). Plus you can use all the plug-ins that are available for Eclipse such as say SubVersion for source control (). All the methods are documented in the HTML JavaDoc which is generated from the comments in the source code. This is included as part of the SDK. Below is a sample of the beginning of the page that documents the InstanceContext. This page documents all the methods in this object. Customization Generally you can do quite a bit of customization just with the screen XML file. But at some point you are going to have to write some code to do the more deep customizations. To customize such UIs with code, you basically want to get hold of the context object, so you can access the collections of widgets and datasources. Then you can add your own listeners, or change the properties of the various objects. Basically you extend the main entry point class of the UI and extend the xxFeatureModule class. Add your functionality and then feed everything back through the GWT compiler to generate a new set of web pages to deploy. Summary Hopefully this gives a flavor for how the Browser part of a UI control is coded in the new Accpac SWT framework. Most of the basic functionality is automatic from the XML screen definition, but UIs are more complex than just CRUD (Create/Read/Update/Delete) and this is how you add that extra complexity to handle sophisticated UI needs. […] This post was mentioned on Twitter by smist08, Geek Fetch. Geek Fetch said: ACCPAC Client Logic for an Accpac 6 Web Form: Last week we talked about creating Accpac 6 Web UIs (…. […] Tweets that mention Client Logic for an Accpac 6 Web Form « Stephen Smith's Blog -- Topsy.com August 21, 2010 at 4:54 pm What will happen to the default screens when we customize and compile new set of web pages to deploy? How about rvspy and dbspy are they are also getting upgraded to include sdata calls or there will be some other tool we need to use? Shamprasad August 22, 2010 at 3:50 pm You can either leave the default screen (have yours with a different name) or replace it. Best practice is to give yours a new name and leave the default screen. Rvspy and Dbspy will still work as always. To spy on SData calls, you can use any network monitoring tool. One that works really well is Fiddler (), just can’t use localhost, must use the actual computer name in the URL. Another great tool is Firefox’s Firebug add-in. smist08 August 22, 2010 at 4:27 pm […] and how to write code that runs as JavaScript in the Browser in. This blog posting looks at how you can write server side code in Java to assist your UIs do their […] Writing Server Side Code for Accpac 6 Web UIs « Stephen Smith's Blog August 28, 2010 at 4:21 pm […] […] Accpac 6 FAQ « Stephen Smith's Blog January 1, 2011 at 10:39 pm […] We’ve refactored the client side SWT (Sage Web Toolkit) framework quite a bit since I wrote this blog post, so we’ll cover how that all works in detail over following blog […] Sage 300 ERP Web UIs and MVC « Stephen Smith's Blog October 29, 2011 at 5:23 pm
https://smist08.wordpress.com/2010/08/21/client-logic-for-an-accpac-6-web-form/
CC-MAIN-2019-39
refinedweb
1,855
61.56
Sometimes small is beautiful. Juha Lindstedt's FRZR, a 4kB view library, was a nice example of that as we saw earlier. This time we'll discuss evolution of Juha's work - a solution known as RE:DOM. I create all my projects with it, even large single page applications. You can also render it on server-side with NO:DOM. I gave a more detailed explanation in my talk in HelsinkiJS / Frontend Finland, but basically it allows you to create HTML elements and components really easily with HyperScript syntax. Another thing it does is it helps you to keep a list of components in sync with your data. Check out examples at the RE:DOM website. The basic idea is to use HyperScript to create HTML elements: import { el, mount } from 'redom' const hello = el('h1', 'Hello world!') mount(document.body, hello) You can also create components by defining an object with el property, which is the HTML element: import { el, text, mount } from 'redom' class Hello { constructor () { // how to create a component this.el = el('h1', 'Hello', this.name = text('world'), '!' ) } update (name) { // how to update it this.name.textContent = name } } const hello = new Hello() mount(document.body, hello) setTimeout(() => { hello.update('RE:DOM') }, 1000) Keeping lists in sync is also really easy: import { el, list, mount } from 'redom' // create some data const data = new Array(100) for (let i = 0; i < data.length; i++) { data[i] = { id: i, name: 'Item ' + i } } // define Li component class Li { constructor () { this.el = el('li') } update ({ name }) { this.el.textContent = name } } // create <ul> list const ul = list('ul', Li, 'id') mount(document.body, ul) // shuffle it every second setInterval(() => { data.sort((a, b) => Math.random() - 0.5) ul.update(data) }, 1000) RE:DOM doesn't use Virtual DOM, but still allows you to define components and how to update them. For me it's the best of both worlds: mutability gives great flexibility and performance, but defining a one-directional flow of updates is very close to VDOM-approach. It's also really tiny, but still does quite a lot of work. Not to mention it's really fast. The source is also really easily readable. I actually first developed FRZR, which eventually got renamed to RE:DOM. RE:DOM is a bit more clever with element creation from queries, and better designed lists. Originally I created FRZR because I was one of the Riot 2.0 early contributors and wrote a HTML element reorder method for it, which Riot lacked. Riot's original idea was to be a really simple UI library, which I think have got a bit out of hand. RE:DOM is basically my view of the simplest possible UI library. RE:DOM is also much more performant than Riot at the moment. There's some things in RE:DOM I need to think through. For example, mounted and unmounted "events" happen when attached/detached related to the parent component/element. They might be better if called when attached/detached to the DOM instead. But that's something that needs careful approach, so it doesn't affect the performance that much. There's also a possibility to use Web Components instead, let's see. I think web standards will eventually make frameworks and UI libraries quite obsolete. That's something recently discussed a lot in the Polymer Summit. That's a good direction, because I think frameworks are actually the source of most of the "JavaScript fatigue" and frustration in general. Web standards are more thought through and also a safer choice, because they will (almost) always be backwards compatible – you can't say the same about frameworks. Abstraction usually also comes with a vendor lock-in: if you start a project with Angular for example, it's really hard to convert the project to some other framework. Be open-minded about web standards and the DOM. It's not as scary and complex as many say it is. You don't always need a framework and you don't always have to follow the crowd. Less is more. I recently wrote a Medium post about the subject. Even if you use some framework, you should learn how the DOM work. You should interview Tero Piirainen, the original author of Riot.js. Ask about web standards and simplicity in web development :) Thanks for the interview Juha! RE:DOM looks great to me. Especially that Web Component direction sounds interesting. I think you are right in that given enough time, web standards will make a lot of the current solutions obsolete (a good thing!). To get started with, head to RE:DOM website. Check out also the GitHub project.
https://survivejs.com/blog/redom-interview/index.html
CC-MAIN-2018-34
refinedweb
781
66.84
>>-#190-Johnson's Russia List Released on 2012-10-10 17:00 GMT Johnson's Russia List 2011-#190: Public Trust in Russian Authorities Fading - Poll. 2. Interfax: Medvedev Denies Russia Heading Back to Soviet Era. 3. Reuters: Medvedev vows Russia's ruling party will win fairly. 4. RBC Daily: MEDVEDEV'S EFFORTS. RUSSIAN POPULAR FRONT'S ANALOG IS TO BE SET UP FOR THE PRESIDENT. 5. Interfax: Authorities Become More Accessible to Citizens Than Previously - Medvedev. 6. Business New Europe: President Dmitry Medvedev hosts a follow-up meeting of the Supporters Committee. 7. BBC Monitoring: Russian pundits offer mixed reaction to president's meeting with supporters. 8. Kremlin.ru: Dmitry Medvedev meets with representatives of the Public Support Committee. 9. RIA Novosti: Russian president joins Facebook community. 10. Kommersant: SHORT OF MAJORITY. SOCIOLOGISTS DO NOT THINK THAT UNITED RUSSIA WILL HAVE THE CONSTITUTIONAL MAJORITY IN THE NEXT DUMA. 11. Politkom.ru: Dubious Practices in Russian Election Campaign Funding Examined. 12.: Nikolai Petrov, Russian elections: the abandoned script. 13. BBC Monitoring: Top Kremlin official says existence of new democratic Russia undeniable fact. (Sergey Naryshkin) 14. Gazeta.ru: Report Sees 'Blow' to Liberal Hopes as 'Illusion' of Medvedev Dashed. (Marina Litvinovich) 15. AFP: Internet hit song puts Putin supporters in 'madhouse' 16. Interfax: Poll: Russian police approval rating on the rise. 17. Nezavisimaya Gazeta: Teen Suicide is on the Rise. 19. Itogi: Profile of FSB "Alfa" Spetsnaz Group Stresses its Independent Role. ECONOMY 20. Business New Europe: Russia moves to 120th, from 124th, in the Doing Business ranking by World Bank. 21.: 'Russia may become WTO member in weeks' 22. Kommersant: Ousted Russian Finance Minister Kudrin Views Country's Budget Policy Risks. 23. Moscow Times: Luc Jones, 8 Tips for Expats to Get the Most Out of Russia. FOREIGN AFFAIRS 24.: Gaddafi's end is not the end of the war. 25. Nezavisimaya Gazeta: SIGNALS FROM WASHINGTON, D.C.. The rift between Russia and the United States over the future European missile shield remains wide. 26. RIA Novosti: Expert Views Russia's Possible Response To US Missile Defence System. 27. Moscow Times: Top Election Official 'Barred From U.S.' 28. Russia Beyond the Headlines: Eugene Ivanov, Mitt Romney: The no-apology candidate. The Republican front-runner has taken an aggressive stance on Russia in his campaign speeches, but will it translate into policy in a Romney administration? 29. Russia Beyond the Headlines: Getting the Congressional Russian Caucus off the ground. 30. Russia Profile: The Unwilling Emperor. Despite the Success of Some Russian-Inspired Regional Economic Integration, Russia Says it Does Not Want to Recreate a Soviet-Type Economic Empire. 31. The Japan TImes: Andrey Borodaevskiy, What is in store for Russian Asia? 32. Moscow Times: Trade Pact Draws Kiev Closer to Russia. 33. Izvestia: EXCUSE FOUND. Both Ukraine and the European Union were glad to drop the pretense of rapprochement. 34. RIA Novosti: Fyodor Lukyanov, Endgame in Ukraine. #1 Public Trust in Russian Authorities Fading - Poll MOSCOW. Oct 19 (Interfax) - Russians expect changes for the better in the social sector but have little faith in them; head of Levada center Lev Gudkov has said quoting the results of a recent poll. "Out of the polled 56% believe that the public is tired of waiting for the fulfillment of the promises of the Russian leadership," he said at a Wednesday press conference in Moscow. "Today the sentiments of Russians are marked by extreme uncertainty. There is balance between those dissatisfied with life and those happy with it at 47% each," he said. "Confidence in the authorities is weakening and fading quite fast. People are not sure about the state of affairs the country with 52-53% not believing that the government will cope with the crisis and 44-47% thinking a way out will be found," Gudkov said. He said that people are most of all concerned about their families and friends. Russians are also afraid of poverty and war. "They fear terrorism, the police or criminals much less," Gudkov said. In the poll 62% said they feared the growth of prices and inflation, 42% feared unemployment, 24% - growing crime and 18% - the arbitrariness of the authorities. Young people are less fearsome while elderly people, especially women, are constantly anxious, Gudkov said. [return to Contents] #2 Medvedev Denies Russia Heading Back to Soviet Era GORKI. Oct 19 (Interfax) - President Dmitry Medvedev on Wednesday rejected speculation that Russia is in for a playback of the Soviet era. "Analogies are drawn to the (Soviet leader Leonid) Brezhnev's period. All such analogies are faulty, they are senseless, because we live in another country, in another world. We ourselves are different, we have another social system, other economic relations, but despite this, we must, of course, remember what we had in the Soviet period," the president said at a meeting with the Public Committee of Supporters of Dmitry Medvedev. The main fears "that are in the air at the moment" are whether Russia is on a path of progress or heading for "stagnation," Medvedev said. "No stagnation is acceptable no matter what beautiful words are used for it. We must move forward, move confidently, maybe gradually in some matters but steadily, such is my creed," he said. [return to Contents] #3 Medvedev vows Russia's ruling party will win fairly Reuters By Denis Dyomkin October 19, 2011 GORKI, Russia - President Dmitry Medvedev promised on Wednesday the ruling United Russia party would play fair in a December parliamentary election and said the resource-reliant nation cannot modernise its economy without support from abroad. Medvedev's remarks appeared aimed at addressing Kremlin critics' concerns that authorities will rig the vote in United Russia's favour, and speculation Vladimir Putin's planned return to the presidency could worsen relations with the West. Medvedev will head United Russia's candidate list for the Dec. 4 parliamentary election as part of a plan to swap jobs next year with Putin, who is now prime minister and will run for president in a March vote. He was president from 2000-2008. Medvedev will be under pressure to lead United Russia to a convincing victory in elections to the State Duma, the lower parliament house in which it now holds a comfortable two-thirds majority. "I am certain that there will be victory (for United Russia) and that it will be secured by legal means," Medvedev said in a meeting with loyal party supporters, entrepreneurs and show business figures at his residence outside Moscow. The lengthy meeting was shown live on state television in an apparent attempt to cast Medvedev as an effective party leader. The announcement last month of the planned job swap deepened feelings of disenfranchisement among Russians who believe they have little say in politics. Putin and Medvedev have tried to counter that by saying voters are free to use their ballots in the parliamentary and presidential elections to reject the plans. In a July survey by independent pollster Levada, a majority of respondents said the December election "will be only an imitation of a struggle and the distribution of parliament seats will be determined by the authorities". Medvedev, whose decision to make way for Putin's return disappointed those who hoped he would stay on and enact reforms, said fears that Putin's return would bring Soviet-style political and economic stagnation were unfounded. "We must not slide backwards," Medvedev said. "People are worried now ... Are we moving forward or stagnating? Comparisons are drawn to the Brezhnev period. All these comparisons are misplaced." Medvedev, who has championed the need to diversify Russia's economy away from reliance on energy exports, said Moscow must look to foreign countries for investment and know-how. "We cannot carry out modernisation without the support of other countries. An Iron Curtain never helped anyone," Medvedev said, referring to the Soviet Union's isolation. [return to Contents] #4 RBC Daily October 20, 2011 MEDVEDEV'S EFFORTS RUSSIAN POPULAR FRONT'S ANALOG IS TO BE SET UP FOR THE PRESIDENT Author: Tatiana Kosobokova [Attempts are made to fuse Dmitry Medvedev's electorate with United Russia's.] Analog of Vladimir Putin's Russian Popular Front is to be set up for the president who met with his followers and supporters yesterday to call them members of the Presidential Public Committee eventually to evolve into the so called larger government. Dmitry Medvedev even said that some people present at the meeting would become Cabinet members after March 2012. Several reasons at once compel the Kremlin to establish yet another structure that will hopefully mobilize the electorate for the forthcoming parliamentary election. First, there is an undeniable gap between the Russians prepared to vote for Medvedev and the ruling party's electorate. Second, Medvedev himself is not exactly pleased with the kind of people calling the tune within United Russia and the methods they prefer. This is why the Kremlin is going out of its way to accomplish two things: prevent the ruling party from losing voters and enable Medvedev as the leader of its ticket to add his electorate to United Russia's. Pressed for time or simply too lazy to invent something new, the Presidential Administration (Vladislav Surkov, to be more exact) chose to emulate Putin's Russian Popular Front. The people invited to the president's Gorki residence yesterday were in for a surprise. All of them were automatically included in the Presidential Public Committee. Medvedev said, "This Public Council is going to be a prototype for the future larger government." The president reminded the audience that he was the leader of United Russia's ticket now and that this party "of course" aspired to the parliamentary majority. That done, Medvedev proceeded to call those present his associates and ask them to be his envoys in the parliamentary campaign. The way he put it, they were expected to "meet with people, hear our criticism, discuss problems, and reveal our plans." Medvedev omitted reminding his would-be envoys that it was United Russia they were supposed to represent and promote. The promise to make this Presidential Public Committee permanent became a carrot dangled in front of those present. Medvedev said, "I do not think that we ought to dissolve the committee afterwards. We'd better make it a permanent advisory structure... I cannot presume to know how we will fare with this larger government, but if we succeed, then I will certainly invite some of you to state structures including the Cabinet as such." Medvedev's associates certainly liked the idea. They spent the following three hours thanking the president. Tula Governor Mikhail Gruzdev suggested making Mikhail Abyzov the Presidential Public Committee coordinator. This correspondent asked United Russia functionaries if the Russian Popular Front was to be replaced with the Presidential Public Committee now. Assistant Secretary of the Presidium of the General Council Andrei Isayev said, "They are different. The Committee is a structure comprising individuals who will be elevated to the government whereas the Front is a coalition of organizations." [return to Contents] #5 Authorities Become More Accessible to Citizens Than Previously - Medvedev GORKI. Oct 19 (Interfax) - Unlike previously, ordinary citizens can get the authorities' attention with greater ease now, said President Dmitry Medvedev. "However paradoxical, getting the attention of the government - from village officials to the president - is easier now than in the 1990s, to say nothing of the Soviet era," Medvedev told representatives of his supporters' Public Committee. "In principle, everyone has the chance to put his message across. The problem is that people write letters to the village chief, to the president or to the prime minister, but the result in nil. This is a real problem," he said. "The situation, where top leaders' interference is needed to get public mechanisms moving, is extremely bad. It shows that the system of authority is inefficient in general, if one has to turn to the president, the prime minister or the governor to get an elementary problem solved," he said. But Medvedev said he disagrees with the opinion that the authorities have pulled too far from the people. "There has been much talk in recent years of a growing gap between the government and the public and public interests, of a super-centralization of governance and that we supposedly have tightened the grip on public activity so much it suffocated," he said. "It's wrong to paint everything black," Medvedev said. [return to Contents] #6 Business New Europe October 20, 2011 President Dmitry Medvedev hosts a follow-up meeting of the Supporters Committee VTB Capital --- Mikhail Abyzov designated the coordinator --- committee to design proposals for the 2012-18 policy agenda --- watch for early signals on the contours of the next cabinet News: President Dmitry Medvedev met yesterday with the Supporters Committee, the creation of which was suggested during his televised Q&A with a larger collection of supporters last Saturday. The declared idea behind this initiative is to prepare an agenda for the next government, and design the framework for the operations of the so-called Enlarged Government, which was also proposed by Medvedev as an advisory body to provide the feedback loop between society and the government proper. Mikhail Abyzov, 39 years old and a self-made entrepreneur (Deputy CEO of UES in 1998-2007 and now principal owner of E4 Group, Russias largest engineering company, with a primary focus in utilities), was appointed the coordinator of the Supporters Committee. Our View: It is too early to judge what effect this latest organisational innovation will have, or how long it will last. Taken at par, it appears to be Medvedevs attempt to bring about the substantial renewal of the government to which both he and Prime Minister Vladimir Putin referred in their keynote speeches at the United Russia convention, where the political configuration for the next political cycle was presented. That said, multiplying the layers of advisory bodies (as it stands, the Supporters Committee is to advise on the formation of the Enlarged Government, which itself will be an advisory body for the government proper) skirts the question of action and implementation. It is also unclear how this initiative correlates with other large-scale projects to devise the policy agenda for the next administration, for example revising the Strategy 2020 which, on the Prime Ministers orders, has been underway since the start of this year. Bottom line: we shall watch where this effort goes, namely, for any early signs of the outline of the next cabinet (Medvedev hinted that some of the committees participants could be invited to senior roles in public service in May 2012). For now, however, it only creates additional questions. [return to Contents] #7 BBC Monitoring Russian pundits offer mixed reaction to president's meeting with supporters Ekho Moskvy Radio October 19, 2011 Three Russian commentators interviewed by the Ekho Moskvy radio station have taken a cautious view of President Dmitriy Medvedev's meeting with prominent supporters in Moscow Region on 19 October, during which he expanded on his idea of "Big Government". The pundits welcomed Medvedev's intention to improve his relationship with some of his high-profile supporters ahead of the 2011-12 parliamentary and presidential elections, but were sceptical about whether these people were genuinely loyal to the president. Political expert and One Russia MP Sergey Markov believes that Medvedev is trying to reinvigorate his relationship with his supporters. He said: "I think Dmitriy Medvedev was a little bit disappointed with the reaction of many of his backers to his support for Vladimir Putin's candidacy for the presidency and this compelled him to reset his relations with his supporters. We are now witnessing specific formats of this reset. A core of those supporters who are not disappointed with his decision has already formed, and it is those supporters who are backing him and his policy and who have not been disappointed with his decision to support Vladimir Putin, and it is with them that Dmitriy Medvedev is conducting a dialogue, and is conducting a dialogue, I believe, to the envy of those who were previously his supporters but then criticized him. I think they are now kicking themselves, looking at those people who are regularly meeting Medvedev and who will be entering this standing committee, the public committee of supporters, and will be taking part in developing the government's policy." He also said he sees Medvedev's meeting with his supporters as an important part of both the parliamentary and presidential election campaigns. Political expert Aleksandr Tsypko doubted whether those people who attended the meeting would really be involved in running the country. "The meeting between Medvedev and his supporters made a good impression on me from the moral and human point of view. People supported Medvedev, wanted him to become the president, but things turned out differently. The fact that they remained with Medvedev despite Russian history moving in a different direction from the way they wished, is, in my opinion, respectable and even very good for the moral health of our current Russian society. This is one aspect, human and moral. The second aspect is purely political. But honestly, I do not see any people among his supporters who can be effective ministers and can enter the government. There will probably be someone who will fit the post of minister for culture and deal with humanitarian problems, but I do not see any people there who can take responsibility for the economy, the army." Sergey Aleksashenko, formerly first deputy chairman of the Russian Central Bank and now an economic commentator, believes that the problem with Dmitriy Medvedev's supporters is that they lack creativity. "Dmitriy Anatolyevich has already been our president for three-and-a-half years. One of the most popular reproaches against him is that, in three-and-a-half years, he has failed to form his own team. And now he is going and saying: 'Though I have not moved anywhere yet, let's set up a support committee.' I welcome Dmitriy Anatolyevich's decision, but one thing that confuses me is that the team, frankly speaking, is too varied. But I have not heard any proposals from these people about changing something. I believe that if they are faced with the choice of whether you, you personally, Mr X, will support either the incumbent president or the incumbent prime minister, the future president or the future premier, they will not answer immediately and will think it over. So, it seems to me that these supporters are supporters of both parties." Aleksashenko said he believed that most of the president's supporters who attended today's meeting would not take part in the elections. [return to Contents] #8 Kremlin.ru October 19, 2011 Dmitry Medvedev meets with representatives of the Public Support Committee Gorki, Moscow Region The idea of establishing an 'extended government', which the President advanced at the meeting with his supporters last Saturday, was one of the main subjects of discussion. The Public Committee's purpose is to draft proposals for state administration reform and also propose feedback tools that would get the public more involved in running the country. ------ PRESIDENT OF RUSSIA DMITRY MEDVEDEV: Good afternoon everyone, thank you for coming here today. Let me remind you of the events of these last few days. There was the meeting with my supporters on Saturday, at which the proposal was made to establish a public committee to work on state administrative reform and reflect on the way we want our government and society to look in the future. It was Mikhail Abyzov who made this proposal, though the idea was in the air really and so Mikhail probably can't claim exclusive authorship, but thanks to him anyway for formulating the proposal. It received my support and the support of the others present at the meeting too, as I recall it. There has been quite a lot of reaction in the media, and I have read much of what people have been writing. We can discuss all of this today, discuss your comments and my responses. Whatever the case, the proposal has not gone unnoticed, and this is good because it means that we have touched the right public nerve. I therefore decided not to delay and to invite you all here to my office, those who were at the meeting on Saturday, and those who were not there, but who I see as likeminded people, to decide how to proceed from here. If there are no principled objections to the idea of this public committee then we could discuss today what exactly the committee will do, what its future tasks will be, and how we can ultimately use it as a communications tool and prototype of the 'extended government' that I spoke about on Saturday at the Digital October centre. All of you here are people who I know, people I have heard about, or people who work together with me. But the circle of likeminded people does not stop here. It can grow in any case, change and transform. Simply, today I have invited those who I want to invite to begin this work. Last time, at the Digital October centre, I did a lot of the talking myself, talked for more than two hours in fact. I don't know how you all found the patience. I heard some say it was no problem, but others say it got a bit wordy. I will not talk a lot today. I want to hear what you have to say, listen to your proposals on what you think the best way to begin this work. You come from a broad range of walks of life: from the regional and local authorities, journalists, politicians, State Duma deputies, businesspeople, and members of the creative professions. Some of my helpers in the election campaign are also here, people from United Russia, but not only United Russia. You could say in any case that what has brought us all here today is also a kind of battle, not so much a political battle as the battle for our country's brighter future. It has become a real tradition over time here to use battle terminology. It seems we cannot think in any other terms, though I can't help but see in this the reflection of a constant sense of emergency that, frankly, is not to my liking. But our language has become so infused with this martial vocabulary that I cannot avoid it either. In any case, we must move forward. I want us to discuss today how to go about modernising our country and society over the coming years in the political configuration that will result if we win the upcoming elections in December and next March. We have set ambitious but noble goals that deserve our battle efforts. You all know these goals: a modern new economy based on intellectual advantage rather than raw materials resources, and modern democratic institutions that do not just exist on paper alone. I am far from thinking that our democratic institutions today exist on paper alone, otherwise I would not be in government at all and would no doubt join some other political movement, but I do think that our political institutions are not ideal in their work and frequently suffer from a range of problems. Just how to deal with these problems is another of the subjects we can discuss. What else do we need? We need an effective social policy that encompasses the broad mass of our people and reaches out to almost every social group in the country. I do not think social policy should be narrowly focused on any one particular group. Of course we need to work on the essential tasks such as eliminating poverty in our country and expanding the middle class. But it is clear that until such time as this happens we will need to think about the least well-off people in our country and try to make their lives more stable, attractive and modern. Of course we also need to think about our veterans. Every country cares about its senior citizens of course. This is normal. We all need to reflect too on the situation we will face ourselves with time, because we all start off young of course, but eventually we all grow old. We need to consider the needs of our people with disabilities. There are a lot of people with disabilities in Russia. These are active and creative people, but sadly, various social norms and laws have prevented them from always taking a full part in the normal modern life of which they would like to be a part. This is an issue we have discussed before. We need to look at how best to reorganise the legislation relating to people with disabilities and properly enforce these laws. We need interethnic harmony. This is a separate and very complex issue for our country, which is home to a large number of peoples and religions, and for our society, in which we see the same processes and threats as exist in other countries today. These are challenges that need decisive and effective responses. We must act, and not just talk about building a harmonious world. The Soviet period did not succeed in building it, but perhaps we will. We need to feel out the right approach, work out how best to proceed. Our political institutions, judicial system, law enforcement agencies, an honest police force, and the intelligence services all need to be under the control not just of the state authorities but of the public too. The strong army that we have been developing and modernising over these last years is also an important institution in public life. It is my conviction, and I hope you support my view, that we must make sure that the changes that have taken place in the armed forces will remain in place and continue. Some of my colleagues think that our defence spending is a waste of money, but I do not share this view at all. We have begun genuine defence reform, and this has brought real change to the armed forces' morale, as we saw in 2008, and not only then. Service pay and wages are higher, spirits are higher too, and they are getting new equipment. No country, and certainly not a vast and complex nuclear-weapon state such as ours, can get by without an army. You all know these issues well. I want to hear what you have to say on any of these matters. We need to develop our international relations, develop relations with the entire world based on mutual respect, recognition of state sovereignty of course, and also mutual enrichment. We cannot carry out our modernisation without other countries' help and support. We should not fall for illusions: the iron curtain did not help anyone and the theory that social systems could develop autonomously ended up in a dead-end. But outside help should take the right form, meet our needs, and be based on equal partnership. I have worked over these last few years to build our relations with the world, with West and East, and with our integration organisation partners, in just this spirit. I hope that we will continue developing this subject too, because much depends on the kind of relations we build with the countries around us. The thing I want to say for a start is that of course everyone here believes that Russia and its people have a bright future ahead even if we do not always like everything that takes place here within the country and beyond its borders. But under no circumstances can we turn back. The main fears in the air at the moment are about what this new political configuration will bring in the future: will we keep moving forward, or will we come to a halt and sink into stagnation. People draw analogies with the Brezhnev period. I already spoke about this at the meeting with my supporters at Digital October. Such analogies never hold up and are essentially pointless because the country has changed, we have changed, our social and political system and economic relations have changed, although we must not forget the past of course, must remember what the Soviet period meant. There can be no stagnation of any kind, no matter what fine words may decorate it. We must keep moving forward, confidently, perhaps gradually in some areas, but steadily. This is my credo, and I would hope that you all share it, so that we can continue our stubborn and steady progress towards achieving our goals. Hasty measures never bring any good, although of course at times we would all like to set reforms moving faster, change the political system quicker and get our economic relations developing at a swifter pace, but not everything is in our hands here. As far as the economy goes, for example, we depend a lot on what happens elsewhere in the world, and no matter how great an effort we make ourselves to recover from the global economic crisis, we realise that what goes on abroad affects our growth rate, our recovery, our GDP growth, our efforts to curb inflation, and our work to resolve various social and economic problems. In any event, the State Duma election campaign that is getting underway now is an excellent moment to reflect on the situation overall and consider the future. This is the main purpose of today's meeting to sum up the results and set out some approaches for the future. You know, I am now top of United Russia's party list. The party list was registered yesterday [at the Central Election Commission]. Naturally, the party's main challenge is to win a majority in the parliament. But as I already said yesterday, this must be done transparently and fairly. United Russia has that opportunity. Some people may criticise United Russia, but it is the party garnering the greatest popular support among our citizens, and it doesn't need any special political technologies or administrative resources to win. I am certain that we will be victorious, and that our victory will be ensured by lawful means. This victory will give us the opportunity to form a new government, which I hope will consist of young, energetic, modern people who think first and foremost about their nation. Naturally, it depends on how the people vote, because it is up to our voters to determine the fate of our nation. Now, a few words regarding 'large or extended government.' Naturally, I am not referring to an increase in civil servants. As soon as this idea occurred, people began to interpret it in different ways, which is probably normal. On the contrary, I feel that the bureaucratic nucleus for this kind of government must be absolutely compact, inexpensive, and not a burden on our taxpayers and all citizens. Something very important we discussed at Digital October is the system of feedback. I want to emphasise again that a system of feedback may be one of the most lacking elements in our society, due to historical reasons as well as the shortcomings in our work today. I would like to talk to you about how we can create such a system, whether through actions, councils, or a critical approach. And all this work can become part of a major public mechanism again, I emphasise, a major public mechanism. Because big reforms, major transformations and modernisation cannot be achieved by a small group of people. After all, we know what happens to various reform projects when they are dictated from the top, when nobody votes for them or needs them they are complete fiascos. We have an enormous number of examples of this. So in this work (perhaps this will sound too broad), I would like to rely on just about all societal forces, first and foremost, the United Russia party and the People's Front, as well as the expert community, NGOs, civic unions, and even representatives of parties that may not be fans of our work, if they so desire, because there are always issues where we can reach a compromise and which unite any political forces. When I meet with heads of parliamentary parties, or sometimes, all parties, there are certain topics that seem obvious to us, where we hold exactly the same position. This mainly involves international issues, because all throughout the world, people criticise their own governments and presidents of their own nations, but when they are abroad, they nevertheless defend the interests of their government. Incidentally, I feel that everybody should learn this approach. We often see various Russian political and semi-political figures that go abroad and, according to habits dating back to the 19th century, begin criticising their own state, talking about its deficiencies, how awful and corrupt it is, and how important it is for a particular foreign superpower to help fight that government. This was all invented at the end of the 19th century; we recall under what conditions, and what it led to. I am not saying we shouldn't criticise our international course, but sometimes, it's shocking the way that certain of my colleagues behave when they are abroad with regard to their own Fatherland. But, as they say, it's up to God to judge. Today, we need to discuss how this type of public communication system will work, and what will be necessary. I would very much like to hear your thoughts on this matter, regardless of your positions. In recent years (and to me, as someone who monitors the public sphere carefully, this is obvious), there have been many conversations about the growing divide between government agencies and the society, the public's interests about the over-centralisation of government, about how we have gone too far, and as a result, how public activity has faded, and how the authorities are deaf and callous. You know, my feeling about it is as follows. I do not think we should paint the government only in negative colours. That's just not an accurate representation. I would even go so far as to say (and maybe you will agree with me), paradoxically, that there are now more opportunities to reach the authorities, ranging from village leaders to the nation's President, than there were in the 1990s, not to mention Soviet times. In principle, everyone has a chance to be heard by any level of power. That's not the problem; the problem is that people are writing to the village leaders, and the President, and the Prime Minister, but the efficacy of these appeals is minute. That is a real problem. It is very bad that in order for certain public mechanisms to function, the highest authorities must intervene. This is a sign of the power system's inefficacy overall, when to resolve an elementary issue, you must appeal to the President, Prime Minister, or governor of a large region. In addition, although all of us here are on the same team, if you will, with similar ways of thinking (among us are governors from various regions, including very large regions, as well as heads of municipalities and cities, and city mayors; you are all big bosses making very important decisions), let's nevertheless look truth in the eyes: who among the governors can tell me that people consult with you on every issue? Nobody. Very often, even governors learn about decisions taken, which concern them personally, from the media. Sure, that isn't how they learn about the socio-political course that will be taken in the next ten years (although this, too, is very important) or international decisions, but rather, concrete economic decisions. In other words, the authorities are also alienated from one another. I talk regularly with all the governors present here. But even those with whom I speak frequently still fall out of the global communication flow. This means our mechanisms are bad; they are not working. What can we say about public communication between authorities and businesses, cultural figures, professional unions, and public institutions? Often, it is merely for show. Please understand, I am not calling on every member of the community to appeal directly to the President; that's the worst possible option. It's just that we need a system that will allow us to resolve simple, basic issues at the relevant and adequate level. That is what we are lacking. If we fail to do this, we will not have normal development. I am not even talking about regular citizens, regardless of what class they belong to, or the poor, the elderly, or children, who represent a separate and even more complicated matter. Indeed, they should be the motivation for us to unite in our work. We will not be able to resolve our political challenges using a single resource, even the most powerful resource, such as television, although television is already fading into the background. We have the Internet and other channels of communication, but most people still watch television. It is not the only resource, and perhaps not the most important one for solving a wide variety of problems. That is why, in order to create this kind of big platform, I am asking for your help in this work. I have a few concrete suggestions. What do we need to do? First, we need to update our strategic development programmes. This does not mean our strategies are wrong. No, overall, they are quite adequate, but on the other hand, we are following these strategies very slowly, and moreover, life is making its own adjustments. Furthermore, long-term plans are called that because they are created for years ahead. Some of them were formulated when Vladimir Putin was the President of Russia, and some were created during the current presidency. But all of them must be updated regularly, and most importantly, they must be made suitable for modernisation. I feel that is critical. Second, I would like for us to discuss the issue of creating a working 'extended government.' For this, we need a concept, including a concept for profound reform of administrative management, state administration, reform and modernisation of government agencies, for cleaning out those agencies, if you will. And this topic should be discussed as widely as possible, while making use of a range of resources: real resources, virtual resources, party-affiliated and independent resources. Third, it is very important to involve as many people and organisations in this work as possible, including with the help of online technologies we spoke about the importance of using them at the meeting in Digital October, so naturally, we will be making use of them. Fourth, we need to form a talent pool at every level in order to create this 'large' or 'extended government.' This is an extremely important issue. I have tried to create a talent pool over the course of all these years. I cannot say this pool is entirely absent, but there are some serious problems. We are falling behind more developed democracies and, sad as it may sound, even our Soviet predecessors for certain positions. Yes, they had their own selection criteria and methods, their own system of 'social elevators,' which does not suit us, but the fact remains that there was a system in place. We do not have a full-fledged system of this kind, although it is working quite well in many territories under regional conditions. Fifth, we need to participate in elections, and I invite anyone interested to be my election agent in this campaign not just in the legal sense of the word, but in fact, as well: to meet with people, talk with them about problems, listen to criticism of the government, the President, and the Cabinet, and share our plans. I would like to add something that everyone is waiting for that is, everyone who has been analysing our recent meetings. I do not know how well we are doing with establishing this 'extended government,' although I am certain that we can create an interesting working mechanism. But if we are successful, if we succeed at the elections and I am certain that there is a good chance we will then some of you will certainly be invited by me or other government agencies, from 'small government' (various ministries and departments) to other organisations, because we always need like-minded people with whom we can share responsibility for important processes we are working on. I think that is absolutely the right goal. But even if this phase goes as planned (again, I have no doubt that it will), then I propose we maintain this public committee, which is present here today. Because otherwise, this serves as just another kind of pre-election poster we use it, thank everyone, and sign certificates for participating in the electoral campaign. I feel that this public committee should not be disbanded. Instead, it should be made a permanent consultative body of the Cabinet. That does not mean, of course, that it should supplant the Cabinet, but in any case, it could continue meeting at reasonable intervals, meeting with Cabinet leadership; we could even form certain groups within this public committee. Some of you could even head these groups, assuming the work is not transferred to government positions, especially since some of you are already in those positions. Well, I only wanted to speak a little bit, but in the end, I said a lot. I promise that I will say almost nothing else today. I hope that you will do most of the talking, although naturally, I will make some concluding remarks at the end of this conversation. STATE DUMA DEPUTY SPEAKER AND DEPUTY SECRETARY OF UNITED RUSSIA'S GENERAL COUNCIL PRESIDIUM SVETLANA ZHUROVA: Mr President, Just to continue what we've been talking about. I've been sitting here thinking about Russia being a raw materials supplier and the possible alternatives. Marat beat me to it: it should be tourism. Both domestic tourism and inbound tourism these things are very important for our country to overcome the raw materials dependency. This encompasses the environment, as Ivan has said, eco tourism, the beauty of our countryside, culture tourism, which has also been mentioned, we've got a lot to share. There are exciting projects in every region, but it's important for them to be noticed, and we shouldn't just watch TV programmes about them but make sure that people go and take part in them. There must be accessibility and competition among the regions to attract visitors, but this requires infrastructure. I know that you support so many projects, including the resorts in the North Caucasus and other projects, such as Altai, the Kuril Islands and Kamchatka. There are so many beautiful places, but they must be more affordable for young people. Most importantly, tourism creates an environment in which small and medium businesses can flourish, businesses built by creative young people who stay in their home regions, who perhaps went away to study but later came back to set up their businesses, to develop this industry in their regions because it has a special meaning for them. I have often heard young people talk about the fields they would like to work in and many say they would like to get involved in developing their regions, to improve them, to improve the country as a whole so that the people from around the world come and see it. DMITRY MEDVEDEV: Thank you. I think we should give Svetlana a round of applause because it is absolutely true, we often fail to appreciate what we have. Remember how in the 1990s those of us who were old enough to travel thought going abroad was the only possible way to spend the holidays. Best holiday destination? Abroad, of course. MIKHAIL ABYZOV: Kayaking. DMITRY MEDVEDEV: That's for particularly gifted people. I support kayaking all the way. I used to kayak too but mostly I spent my holidays at different resorts abroad. I came to the realisation only recently that we have such a great country. It's not as developed, and the number of attractive tourist destinations is small, but it is so beautiful that we have to use this potential one hundred percent. Americans are often criticised for their shallow mentality and lack of culture I mean people in the United States. But I think there's one area in which we must follow their example (at least one, and actually many other things as well). Most Americans spend their holidays in their own country, which is also very big and very beautiful, and they don't think there's anything wrong with that. And when we start to feel about our big and amazingly beautiful country the way Americans feel about theirs, that's when we will become real citizens of our state. And it is our duty to set the example, so I completely agree with Mikhail about kayaking. I never go abroad for holidays and you could show your support as well. So let's spend our holidays at home and let's develop our country, because it is very important. DIRECTOR OF APPLIED POLITICS INSTITUTE OLGA KRYSHTANOVSKAYA: Mr President, My name is Olga Kryshtanovskaya, I am the coordinator of United Russia's liberal club, the leader of the Otlichnitsy public organisation and one of your friends on Facebook. I heard your idea of 'large government' today and I think it's absolutely brilliant. Just yesterday, I posted a proposal to Facebook to discuss what a perfect government in our country would be like. DMITRY MEDVEDEV: Olga, I didn't steal the idea from you. I didn't visit your page yesterday. OLGA KRYSHTANOVSKAYA: This just goes to show that this idea is in the air, so you are absolutely in the mainstream. Well, as a representative of the liberal club, which was established two years ago, I want to say that you have enjoyed the support of United Russia and you still do. Naturally, we hope to work together and provide you with all the support and assistance you need. I would like to raise the issue of women in politics. DMITRY MEDVEDEV: A complex issue. OLGA KRYSHTANOVSKAYA: I think it is just catastrophically complex. DMITRY MEDVEDEV: For our country, yes. OLGA KRYSHTANOVSKAYA: We have only 6% of women in the establishment while women make up 53% of the population and 58% of university degree holders. What do you think we should do? For our part, the Otlichnitsy public organisation does not want to ask for special quotas. We don't think that women are weak. We just want to consult with you whether it may be wise to create a special women's pool of high-potential managers? Your presidential personnel pool has only 18% of women. That's not enough. DMITRY MEDVEDEV: Good idea. OLGA KRYSHTANOVSKAYA: I think it would be good so that the 'large government' consists of 50% women rather than 8%. After all, how does a normal family work? There's a husband and a wife, and then the children will have a balanced upbringing. What about state policy? We talk about the need to humanise our policy and to harmonise it. But how do we achieve that without women? We are ready to help and to get involved because it is a serious matter. We must train women like that and get rid of all the internal shackles. By the way, could you tell your wife that we would like to invite her to join Otlichnitsy? DMITRY MEDVEDEV: Thank you. There are many successful men here. I don't know what your views on this issue are but I'll tell you about my feelings. I've always enjoyed working with women. I'm not kidding. Let me explain why. There are those who think that some issues should be discussed only with men, in the company of men, otherwise it just won't work. Fist of all, I think that's just because of their hang-ups. Second. Clearly, women are able to give men a head start in many areas, and I say this in all sincerity. This is true in terms of their capacity for work, their alertness and persistence. Most women who do real work are much more consistent and much more firm in his beliefs than men. Men grind their teeth, swear, whatever, but it is clear that for them it is a secondary issue. Once a woman sets an objective, she is unstoppable. So, I think this makes a lot of sense. Finally, and this seems particularly important to me, as soon as women come to work at government agencies, be it a ministry department or a village administration, the atmosphere changes, for most men anyway. It creates a new mood. So if we talk about my views, I think we don't need any quotas; we should just not be afraid of making bold decisions, without fear that women should join what used to be a men's team, a team of successful people. Most states with very different government organisation, religious and historical traditions, which would seem much less civilised than Russia, have long ago started employing women in management positions. And we are still dragging our feet. And the last point. If you take the offensive, men will not be able to stop you. I can still go on but do you want me to? Nobody is bored? I think when such events take over two hours it is always tiring. People will think, when is it going to finish? It doesn't matter who the speaker is, in fact. So shall we go on a bit longer? All right. Let's have five more questions. Okay? To be continued. [return to Contents] #9 Russian president joins Facebook community MOSCOW, October 20 (RIA Novosti)-Russian President Dmitry Medvedev has decided to expand his interaction with internet users by posting regular comments on Facebook is a social networking service with more than 800 million active users worldwide. "I have decided to write in Facebook as well. Read it!" Medvedev wrote in his Twitter and Facebook blogs on Thursday. Medvedev, who styles himself as a technologically savvy leader,. [return to Contents] #10 Kommersant October 20, 2011 SHORT OF MAJORITY SOCIOLOGISTS DO NOT THINK THAT UNITED RUSSIA WILL HAVE THE CONSTITUTIONAL MAJORITY IN THE NEXT DUMA Author: Maxim Ivanov, Alexandra Larintseva [Results of opinion polls indicate...] The Russian Public Opinion Research Center (VCIOM) traditionally relies on results of opinion polls and opinions of political scientists. The last time its sociologists approached 1,600 Russians in 46 Russian regions was on October 1 and 2. (Statistical error does not exceed 4.3%.). They discovered that 45% respondents were prepared to vote for United Russia, 13% for the CPRF, 10% for the LDPR, 5% for Fair Russia, and approximately 1% for each of the three non-parliamentary parties. Fifteen percent respondents denied the intention to vote and 10% said that they were still thinking. In other words, had it been just results of opinion polls, four parties would have made it to the Duma come December. They are the parties already represented in the lower house of the parliament. United Russia would have polled 53.8%, CPRF 16.4%, LDPR 11.6%, and Fair Russia 9.4%. Right Cause would have come in with 2.6%, Russian Patriots with 2.4%, and Yabloko with 2.9%. The opinions of political scientists differed from the respondents'. Experts believe that United Russia will poll between 50.7% and 56.9%, CPRF between 15.4% and 17.7%, LDPR between 9.6% and 12.6%, and Fair Russia between 5.6% and 7.1%. Considering the opinions of political scientists and the Russians, sociologists say that Fair Russia will finish the parliamentary race with 7.9%, LDPR with 11.3%, CPRF with 17.1%, and United Russia with 53.8%. According to the same estimate, Yabloko will perform better than all other non-parliamentary political parties and end up with 3.3%. The turnout might reach 56%. If these estimates are correct, the ruling party will have but 269 seats on the Duma (it has 315 nowadays) i.e. less than the constitutional majority. Other political parties will do better from the standpoint of factions. The CPRF will enlarge its current faction from 56 to 85. Even Fair Russia will increase its faction by two lawmakers despite the crisis it has been in since its leader Sergei Mironov was chucked out of the Federation Council. VCIOM Director General Valery Fyodorov said, "There is a difference between this parliamentary campaign and the election held in 2007. The previous campaign took place when the national economy was fine whereas the current one is convened in between two crises. It cannot help affecting the rating of the ruling party." Fyodorov said that respondents took note of the decisions proclaimed at United Russia convention (the forthcoming castling within the ruling tandem and the president's consent to become number one on the ticket of the ruling party). He said, however, that it failed to produce a noticeable effect on the Russians' readiness or willingness to cast their votes for United Russia. "Anyway, the ruling party just might accumulate the votes of up to 10% of Medvedev's electorate," said Fyodorov. Political scientist Dmitry Orlov said that United Russia could actually poll 60%, particularly if it nominated Vladimir Putin for president several days before the parliamentary election. As a matter of fact, VCIOM published a similar forecast on the eve of the 2007 election and said that United Russia could only count on a mere majority (257 seats) in the Duma. Political Technologies Editor Sergei Polyakov said, "Yes, but the situation four years ago was different. Nobody expected United Russia to poll more than 46% or 48% right until the moment Putin became number one man on the ruling party's ticket... It's different now. Putin's factor is history now whereas Medvedev's association with the ruling party merely weakened it. Being a liberal president, he is a poor match for the party of conservators. His supporters are unlikely to cast their votes for United Russia... It is they after all who regard United Russia as a party of thieves." Polyakov said that United Russia could poll 45% or 45% in a truly free and fair election but governors had been instructed to make it 70%. According to Levada-Center Director Lev Gudkov, the number of the Russians prepared to vote for the ruling party increased from 34% in August to 44% in October. Gudkov even suggested that the ruling party might up its rating to 57% or 59% in the time remaining before the election. The sociologist said that whether or not Fair Russia made it to the lower house of the parliament would play its part too and have an effect on the number of seats won by the ruling party. Levada-Center sociologists say that the Russians are disinterested in politics because they do not think that their opinions matter. Gudkov said, "No wonder so few people turn up at polling stations... Mostly budget sphere employees who are pressed and bullied into participation or pensioners who vote by inertia." [return to Contents] #11 Dubious Practices in Russian Election Campaign Funding Examined Politkom.ru October 18, 2011 Commentary by Valeriy Vyzhutovich: "A Parliamentary Seat Is Expensive Nowadays" Elections are not conducted on credit. This immutable truth is encapsulated in the cynical saying of TV executives: "No budget means no story." Which means: Money up front! No service will be provided in an election campaign without 100 percent payment in advance. According to some stories, a minute of primetime pre-election television advertising is valued at 600,000-800,000 rubles. Party publications also requires significant investment. Their pre-election print runs are increased many times over. For example, experts estimate that the Communists will spend more than 61 million rubles on a special edition of Pravda with a print run of 5 million copies. Spending by the LDPR (Liberal Democratic Party of Russia), whose newspaper is published with a print run of 2 million copies, will be significantly less. Just Russia will spend the most on the press. The print run of its newspaper, according to figures from party headquarters, will total 25 million copies in October-November. The print runs of this party's regional publications will also increase. In the three months ahead of the elections Just Russia will produce 222 million copies of newspapers, spending 288.5 million rubles on the party press. Yet the party of power does not intend to increase the total print run of its publications. In the words of Andrey Isayev, head of the United Russia Commission for Campaigning and Propaganda, print runs will be increased only "in individual regions, primarily where the federal elections coincide with regional elections, and this will undoubtedly result in spending from the pre-election front." Incidentally, pre-election funds have also become much more substantial. A year ago legislative amendments were adopted increasing the upper limit for expenditure. From 400 to 700 million rubles for parties (not counting spending on regional branches' pre-election funds). For regional branches the increase is from 6 million to 15 million rubles -- if no more than 100,000 voters are registered on the territory of a Federation component; from 10 million to 20 million rubles if there are more than 100,000 voters; and from 30 million to 55 million rubles if there are more than 2 million voters. The Communists consider that such a procedure "in practice turns elections from a competition between party ideas and political programs into a competition between moneybags." The Liberal Democrats are actually proposing the removal of any restrictions on parties' pre-election spending. Be that as it may, parties are now allowed to spend much more money on election campaigns than previously. With such indulgences election funds could and should finally become transparent. The Central Electoral Commission is constantly urging this. Well, slush funds may indeed recede this under the onslaught of the new rules. But precisely to the level specified by permitted expenditure. Whereas beyond the limits of the legal estimates they will continue to be invincible. Because there is a market for political services. And here, as in any market, everything costs as much as it costs. As is befitting, the price here is determined by the balance between supply and demand, not by a paragraph in the law. In accordance with this paragraph, the size of a party's election fund must not exceed 700 million rubles. But experts estimate that this budget will be exceeded. In limiting pre-election spending legislators were guided by a desire to ensure equal financial opportunities for all parties. Yet different parties have different levels of investment attractiveness. And no monetary standards prescribed in a law can make things equal for all and sundry in an election race. Each participant will receive from sponsors as much as they deserve. No more and no less. The pattern of pre-election spending is approximately the same for all parties. There is the surety (or, in the absence of that, the collection and checking of signatures). There is the spending on sociological studies, ratings polls, the formation of focus groups, and so forth. There is the campaigning. At the risk of upsetting individual representatives of the electorate, I will cite yet another item of expenditure -- "managed rumors." Commissioned by a given party, they spread through towns and villages. And finally there is the "other expenditure" paragraph. "What does 'other expenditure' mean?" was, I remember, a question asked during the public discussion of the report "The Economic Cost of Elections" produced by a certain consultancy. The expert who presented the report was sheepishly hesitant: "Well, you understand what I mean...." The suggestion that it includes bribes to officials and other "nontransparent" expenditure was not rebutted. Experts in electoral techniques considered that a seat in the State Duma has become more expensive. There many reasons for this. First, there has been an increase in the attractiveness of legislators' administrative leverage. The status fee currently obtainable from a parliamentary seat bears no comparison to such income at the dawn of Russian parliamentariansism. Not just a supremely strong but almost a deadly link exists between those who invest and those who, justifying the investment, operate on Okhotnyy Ryad (the location of the State Duma). I was once told a story. When a certain Duma figure holding a prominent post on one of the key committees intended to run for mayor in his home town, and with a good chance of winning, he immediately started to receive visitors. Saying approximately the following: "You will stay in the State Duma until the end of your parliamentary term. Otherwise, you see, anything might happen to you. An accident, for example...." A second reason for the high cost is the increase productiveness of Duma lobbyists. A third reason is the population's apathy. The mass flight from ballot boxes and deliberate spoiling of ballot papers are the people's response to no-choice elections. Because the outcome of the election campaign is often predetermined. Simple, unsophisticated people feel this intuitively. While the most educated and enlightened part of the population casually explain to us that there are three real "voters" in Russia -- administrative leverage, capital, and PR. It is their "votes" that decide everything. In general, increasing the turnout requires more and more resources. We would add to this the capital-intensive bureaucratization of party machines extracting their own pickings from the elections. We can also factor in the surplus on a budget stuffed with petrodollars, which makes it possible to painlessly increase state spending on the election campaign. Finally let us not forget the following point: 35 percent of the money dispatched to pre-election coffers goes astray. That is, it is simply stolen. So would it not be better to remove the useless restrictions, as was done in the United States a long time ago? In that case the market for pre-election services would become more transparent and the sale of the services would be taxable. Experts believe that the crazy election campaign spending carried out using black and gray schemes constitutes deferred investment in the Russian economy. Somehow the result is that there are two electoral systems in Russia today. In one system financial limits are declared but do not operate. In the other system financial outrages operate but are not declared. In Soviet times, when exchanging apartments for a supplementary payment was banned and regarded as speculation, citizens would write in advertisements: "I will exchange a two-room apartment for a three-room one. By agreement." And those who were making the exchange and those who authorized the exchange realized equally well what "agreement" meant. There is a similar symbol of hypocrisy in the financial part of the Russian electoral system. It is a xero x-paper box (allusion to 1996 scandal when Yeltsin campaign officials were arrested for trying to smuggle $538,000 in illegal campaign funds out of the Russian White House in a photocopier-paper box) [return to Contents] #12 October 19, 2011 Russian elections: the abandoned script By Nikolai Petrov Nikolai Petrov is a senior research associate with the Institute of Geography at the Russian Academy of Sciences. Scholar-in-residence at the Moscow Carnegie Center. Internal and external pressures seem to have triggered a radical readjustment in the Kremlin's pre-election planning. The consequences may prove long-lasting, writes Nikolai Petrov No Russian election cycle has been accompanied by quite such a large number of scandals and cadre unrest as the current one. First, there was the sensational removal of Mikhail Prokhorov from the leadership of Right Cause [pravoye delo], and the de facto death of that party political project, which meant the anticipated entrance of patriot-nationalist Dmitry Rogozin into the campaign never materialised. Then, after the reshuffle made Medvedev the anointed heir to PM, Minister of Finance and Deputy Prime Minister Aleksey Kudrin resigned. All of this seemed to indicate abrupt recalculation of future plans and strategy. At the same time, it changed the entire nature of a campaign already in full flow. Strategy 2020 and the People's Front We can talk first about a revision of Strategy 2020, a plan which was being developed by a working group of liberal economists under the personal instruction of Vladimir Putin. The group's first reports were taken quite seriously by those in power (indeed, in March, the group's report on federalism and local self-governance was initially presented as a document from the ruling United Russia party). Today, in the absence of a functioning right-liberal vehicle like Prokhorov's "Just Cause", there is no way of bringing policy recommendations into the agenda of either the Duma parliamentary or presidential elections. A conservative alternative to the liberal Strategy-2020 project was also launched in parallel. These were the programmes of the "All-Russian People's Front", which were being developed by a newly created Institute of Social Economic and Political Studies, and under the guidance of Senator Nikolai Fyodorov. In the end, this proved to be an unnecessary innovation, as instead it was declared that the United Russia programme would be built on the basis of speeches made by Putin and Medvedev at the United Russia Party Conference. Finally, there was the timing of the reshuffle announcement. We can surmise from late changes in the scheduling of the Valdai Discussion Club that it was planned for a much later date. The initial date of the meeting was the start of December, that is after the Parliamentary elections, but this has since been changed to mid-November. Vladimir Putin was personally very visible in the campaign, attending some eight regional United Russia conferences since April of last year, launching the "People's Front", and initiating work on various strands of possible strategy. And yet he blew the entire electoral strategy of "his" United Russia party, by declaring that it would not be Captain Putin driving the party steam engine, but instead Medvedev, up till now sitting in the passenger carriage. Every one of the above instances may well have an individual explanation for example, because Prokhorov became too independent, because he left his agreed electoral niche, because he decided to rebel against his Kremlin handlers. At the same time, it does seem to indicate the generally primitive picture of the nature of both campaign strategy and political organisation. Quite apart from all of this is the question of whether OBSE observers will be allowed to observe the ballot in any meaningful way. If, unlike the previous electoral cycle, we get to see long-term observers, this will mean that either the authorities no longer believe they need a high and OBSE-accepted result for United Russia, or that observers were initially factored into the previous, rejected electoral plan, and there was no time to cancel their plane tickets. What 'should' have happened With the usual reservations that accompany such reconstructions, we could suggest that the initial electoral model was conceived to be a lively and competitive one. There would have been a sprinkiling of intrigue from the free-market right, lead by Mikhail Prokhorov and his "Just Cause"; while Dmitry Rogozin, attaching himself to the People's Front, would have provided a flow of "moderate national-patriotic" voters. Of course, it is difficult to imagine that "Just Cause" would have been able to secure enough votes to get into the Duma parliament, but that is not so important. What is important is the fact that its very participation in the electoral campaign should have put the matter of liberal economic and political reforms developed by some 21 expert groups under the patronage of Kudrin on to the political agenda. It was initially planned that the working groups would present policy recommendations at the beginning of December. Their reform package, which was supposed have been carried out by a government lead by Alexei Kudrin, would have been presented before the presidential elections. In such a way, they would have become not only a vote for Putin, but also a vote to legitimise the cabinet programme and mobilise citizens in support. The six years of the new presidential term would begin harshly, with painful transformation, with all ending well at the end, at the peak of the president's popularity in time for the 2018 elections. Legitimacy and the presence of a proper mandate certainly played a significant role in the initial electoral plan. It is precisely for this reason not only a wish to look good in front of the West that the picture of the campaign became so complicated. The future As panic grows in the Eurozone, the increased risk of a second wave of crisis in Russia forced Vladimir Putin to reject any plans to carry out reforms immediately after the elections. To have reform and crisis going on at the same time would be too much. The experience of 2005, when the government's social welfare reforms brought many onto the streets, and the more recent experience of the Arab Spring is fresh in everyone's mind. A decision was, it seems, taken to hold out for a more certain economic times, and postpone reforms for a while. The government's remaining financial reserves offer the luxury of not having to force reforms for another year or two. Of course, this will not remove the need for reform once those reserves are empty these will have to be carried out regardless of the "global climate", and moreover without the kind of resources that would give comfortable room for manoeuvre. The decision to put reforms off until a sunny day and the clear deterioration in relations with the West (the American missile shield in Europe, the Justice for Magnitsky list) have made many components of the initial plan redundant, hence their absence in the actual election campaign. We are little over seven weeks away from the December vote, and neither the People's Front nor United Russia are particularly visible. But few in the Kremlin seem bothered: United Russia will get its fifty-something percent, and it will always be possible to get agreement with the other minority parties. The elections will now look a little like the economy version of an old Lada car: not too pretty, not too comfortable and not particularly good in extreme conditions ... but, on the other hand, relatively reliable and cheap. The choices and strategies that have been adopted for the campaign may well determine the entire political organisation of the next Russian government. It seems likely that that governent will be closer to the model of a Yeltsin presidency, with power concentrated on a single leader, relying neither on institutes nor an all-powerful party of power. At the same time, in rejecting an attempts to enact true reform and modernisation, Vladimir Putin and with him the whole country may well have missed out on an opportunity that may not repeat itself. [return to Contents] #13 BBC Monitoring Top Kremlin official says existence of new democratic Russia undeniable fact Text of report by state-controlled Russian Channel One TV on 19 October (Presenter) How the country has changed over 20 years? The History of New Russia conference has opened in Moscow. Sociologists, economists, historians, mathematicians have gathered to form an objective picture of the recent past and realize how unique Russia's path is or, on the contrary, how similar is it to development scenarios of other countries. Experts are convinced that the detailed analysis of past events will help to avoid mistakes in the future. (Sergey Naryshkin, head of the Russian presidential administration) In the beginning of 1990s our democracy was only about to stand on its feet and was far from being perfect in some instances. A parliamentary platform was used not only for defending the interests of voters and parties but also for attracting new followers to nascent political groups and associations. Under such conditions it was a strong presidential power who helped to preserve the country, pull it out of the crisis and, most importantly, ensure its purposeful movement on the planned track. Even if not everything was succeeded to be done consistently then, 20 years later we may state an undoubted and indisputable result: new democratic Russia indeed exists and succeeds. [return to Contents] #14 Report Sees 'Blow' to Liberal Hopes as 'Illusion' of Medvedev Dashed Gazeta.ru October 17, 2011 toward toward defense maneuver favor of society can really make the authorities go for changes. It is precisely in this direction that it is necessary to move, strengthening society as a full-fledged political entity [return to Contents] #15 Internet hit song puts Putin supporters in 'madhouse' By Anna Malpas (AFP) October 19, 2011 MOSCOW. [return to Contents] #16 Poll: Russian police approval rating on the rise Interfax October 20, 2011 Moscow - About two-thirds of Russians (61%) have a positive attitude toward the police, and 24% feel negative, the Russian Public Opinion Study Center (VTsIOM) said in a report received by Interfax on Thursday. "Although the number of positive opinions declined in the past year [from 64% to 51%], the indicator is rather high," the center said. It polled no less than 500 respondents in 83 regions of Russia this year. Some 41,500 respondents were asked which violations of law they had witnessed and how much they trusted and supported the police. Confidence in the police enlarged from 33% in 2009 to 52% in 2011 in the questions concerning personal and property security. About a third of the respondents voiced the opposite opinion. Their share was practically unchanged in the past two years, the sociologists said. Eighty-eight percent of Russians said that people should help the police fight crime this way or another. About 80% said they would inform the police about a crime and testify. About 50% are prepared for active moves, such as assistance to the provision of public order and to the detention of a criminal. More than a third of the respondents believe that their personal and property interests are protected (the indicator grew from 34% in 2009 to 39% in 2011). The number of people who are not sure of their security declined from 58% in 2009 to 54% in 2011. Thirty-four percent said they expected help from the police. On the whole, the respondents described the police as one of the most efficient bodies protecting people from criminal encroachments (44% expressed the opinion). Other bodies of the kind are the Federal Security Service, prosecutors, courts and the media. Some 12.5% of the Russians said they were victims of crimes in the past year. A total of 41.5% of them reported the crimes to the police. The most frequent crimes were theft, beating, assault and vehicle hijack, while computer crimes, extortion of a bribe and rape were less frequent. Persons harmed in the acts of terrorism and extremism (56%) and attempted murders (50%) were the most satisfied with the police work, the center said. About 40% of persons who reported pick-pocketing, car hijacks or extortion had the same opinion. Victims of computer crimes (25%), persons forced to give a bribe (32%) and victims of a fraud, a rape or a theft (33%) also approved of the police work. [return to Contents] #17 Teen Suicide is on the Rise Nezavisimaya Gazeta October 12, 2011 Article by Aleksandra Samarina and Aleksey Gorbachev: "Youth Between Revolt and Death. Russia Has Come Out Into First Place in the World in the Number of Suicides Among Adolescents" Yesterday the Public Chamber discussed the problem of youth extremism. The round table was to answer this question: Is there an ethnic underpinning to the recent street battles. Clashes between groups of young people, often on the grounds of ethnic hatred, take place against the backdrop of a difficult social situation. The country is in first place in the world with respect to childhood suicide. Experts associate both of these phenomena with an absence of favorable prospects for young people. At the Public Chamber round table, stormy disputes raged between Russian nationalists and representatives of North Caucasus republics. The latter rejected an interethnic underpinning of the youth street clashes, declaring that this was a question first and foremost of an inadequate family upbringing and domestic conflicts. No consensus was reached during the debate, and as a result, the blame for the inflammation of interethnic discord was habitually placed on the media and the Worldwide web. The leader of the Youth Committee of the Russian Congress of Peoples of the Caucasus, Sultan Togonidze, declared that interethnic conflicts arise from ordinary conflicts of daily living. The leader of the youth movement Union of Georgians in Russia, Tamta Pulariani, on the contrary, recognizes the presence of an ethnic underpinning in the conflicts: "At the youth level, they are difficult to prevent. This happens because a person of one ethnic group differs from a representative of another ethnic group." Pulariani complained to Nezavisimaya Gazeta about everyday nationalism: "Sometimes landlords do not want to rent an apartment to non-ethnic Russians for any amount of money." But, as another participant in the round table, Aleksey Mikhaylov, Chairman of the political council of the movement Ethnic Russian Representation, said in a conversation with Nezavisimaya Gazeta, he sees the problem of mutual enmity from another angle. He stresses, "The 'Ethnic Russian March' is a legal event, and people's attendance at it is based on corresponding sentiments. People see that in the power structure, in the parliament, there is no one to defend them, and they vote with their feet." Coming out to the march is associated with the fact that the moral climate of our society is unfavorable, Mikhaylov explains: "Young people have no confidence in the current power structure, and profoundly depressive sentiments predominate, which is also shown by the number of suicides. In recent years, the march has gotten significantly younger." As Mikhaylov notes, older secondary students and students in their first years at institutions of higher learning comprise a large segment of such actions, since they actively use the Internet. "Many young people are going toward nationalism, seeing that life is set up unfairly. Whereas ideologues and propagandists of nationalism tell them that the ones to blame are those who do not resemble them, without indicating the real cause for this injustice," human rights activist Nikolay Kavkazskiy says. "While the real cause is the disinclination on the part of the power structure to resolve interethnic problems, provoking nationalism with their social policy." As Nezavisimaya Gazeta was told by soccer fan Vladimir, who has taken part in such events, young people are moved by a common dissatisfaction with the political system, which is steeped in corruption and which resembles the Soviet system more and more. According to him, young people have only two ways left to express their dissatisfaction -- to go out onto the squares or out onto the balcony to jump off and leave this life: "The most active ones take the first path. The weak take the second." In 2010, specialists of the World Health Organization and the United Nations Children's Fund, UNICEF, reported that Russia had come out into first place in the world with respect to the number of suicides among adolescents, and it takes the l ead in the number of children and young people in Europe. According to the children's ombudsman, Pavel Astakhov, "In 2010, almost 4,000 incidents of suicide were recorded": "Of these, about 2,000 were carried out to the end. This is the official figure, which is made public by the Ministry of Health and Social Development. According to our data, these figures are much higher, because not all such incidents are recorded as suicides. Sometimes they are written up as death from everyday trauma or other external causes." In recent years, Nezavisimaya Gazeta's interlocutor notes, the frequency of suicides of children aged between 10 and 14 has fluctuated in the range of between three and four incidents per 100,000. And among adolescents between the ages of 15 and 19, the figure is 19-20 incidents per these same 100,000. Which exceeds the average world figure with respect to that age category of the population almost by a factor of three. The most difficult situation, says Astakhov, is in Kemerovo, Kurgan, Tomsk, Buryatia, Tuva, and the Transbaykal region. Lev Gudkov, head of the Levada Center, points out that children's suicide "is only a manifestation of the general, very high level of suicides in Russia": "This is associated with the general crisis and the collapse of social relations, ties, and people falling out of social interaction. For Russia, in addition, a very high level of violence is characteristic. In some measure, this is associated with a legacy of the totalitarian society, where state-sponsored violence was the norm. It encompasses not only state relations, but everything associated with human life." Moscow in our country today is an oasis of well-being: Eight suicides per 100,000, Gudkov noted: "Zones of trouble are the North, the Far East, Kamchatka, and Primorskiy Kray. There the suicide rate reaches up to 100-110 per 100,000. Including adolescent suicide." Dissatisfaction with life is manifested among young people in different ways. Some people jump off a balcony, some go out onto the streets of cities. The young people on Manezh Square last December were motivated first and foremost by a sense of absolute lack of prospects, believes the Director of the Institute for Problems of Globalization, Mikhail Delyagin: "Young people do not have the opportunity to receive an education, and they realize this. Even fee-based education is simply a scrap of paper, which does not mean anything. As a result, they find themselves not needed by anyone. Because there is no development, new jobs do not appear... on the other hand, they have no skills." If a talented person manages to struggle through, he "sees above him a glass ceiling," Delyagin says: "Since the system of upward mobility does not work, the ones who are set up in significant positions are the loved ones and acquaintances of officials. Talented people are not needed in principle. The main problem of young scholars is not even in an absence of basic training. Not even in that they are being taught out of 30-year-old textbooks. Not in poverty. The main problem of young scholars lies in the fact that if they remain in Russia, they will have to be subordinate to idiots, to be slaves to scientific bureaucrats who do not understand anything about anything. For this reason, some of them leave the country. Those who cannot do so choose other paths. Sometimes they find a tragic way out of the situation." Citizens experience ethnic aggression in their own lives, and in the young people's environment this is manifested especially acutely, the expert believes: "Young people see that if the attacker belongs to a diaspora, then he has someone to intercede for him." The going out onto Manezh Square, Delyagin is convinced, "is a manifestation of the instinct for self-preservation": "It is a manifestation that is monstrous and backward." [return to Contents] #19 Profile of FSB "Alfa" Spetsnaz Group Stresses its Independent Role Itogi No. 41 October 10, 2011 Article by Grigoriy Sanin entitled "Scalpel of the State" According to Sergey Goncharov, President of the Association of Veterans of the "Alfa" Antiterrorist Unit, "If we had stormed the White House, Yeltsin and his defenders would have, in the worst case, been killed, and, in the best case, been arrested." The "Alfa" special unit, created in July 1974 at the personal direction of KGB (Committee for State Security) Chairman Yuriy Andropov, has been and remains "the last resort of the state" in critical situations where negotiations with terrorists hit a dead end, and only seconds remain while the lives of hostages hang on a thread... This was the case in Beslan, Budennovsk, and Mineralnyye Vody. Unfortunately, there will be more such cases. The President of the Veterans Association of the "Alfa" Antiterrorist Unit, Sergey Goncharov, gave 15 years to this "dream team." By spetsnaz (special forces) standards, this is an entire lifetime. But only now can he share his memories of events about which he previously had to remain silent. Indeed, even now several operations remain Top Secret. For example, the events of 1991 and 1993. Nevertheless, we decided to initiate our conversation with him precisely with these topics. (Sanin) Sergey Alekseyevich, in August the country celebrated the twentieth anniversary of the 1991 coup. The question of why "Alfa" did not assault the White House at that time remains unanswered. After all, you were able to have changed the course of history. (Goncharov) Indeed, in August 1991 we found ourselves in a situation where both the GKChP (State Committee for the State of Emergency) and the people surrounding Yeltsin who opposed the GKChP understood that the problem could only be resolved by force accompanied by a bloody battle. I know this precisely, since after all we were monitoring (literally: "sitting on") the governmental communications. But the authorities vacillated. Some of the leaders of our republics had pledged allegiance to the GKChP before dinner, and to Yeltsin after dinner. Everyone wanted to bet on the horse most likely to win. But we had to make a decision immediately. If we had stormed the White House, Yeltsin and his defenders would have, in the worst case, been killed, and, in the best case, arrested. Everyone understood perfectly well that all hopes rested on us. The members of the GKChP believed that we would conduct the assault. Yeltsin and Korzhakov were thinking about ways to save their lives. It was suggested to Boris Nikolayevich (Yeltsin), and no one is concealing this now, that he hide in the American Embassy, but he decided otherwise because he knew that it was likely that he would win in this situation. (Sanin) So was an order given to assault the White House? (Goncharov) The order was given and the time of the assault was designated. Over the radio they even transmitted that "Alfa" would begin the assault at three o'clock in the morning. Practically all of the combat ready forces available at that time in the country were placed at our disposal. These included spetsnaz troops of the GRU (Main Intelligence Directorate), the VDV (Airborne Troops), and "Vympel." Even now, years later, I understand and can even justify the confusion that ensued at that time. After all, none of the leaders wanted to take responsibility for shedding first blood and no one wanted to go down in history as the person who fired upon his own people. The helicopter pilots who were ordered to support us from the air, stated that they could, of course, fire unguided rockets, but who would later take responsibility if civilian sites and people were injured? These were unguided rockets. And suppose they hit the American Embassy? As military people we understood that many simply ignored the order. When they started to bring up the armored units, some of the tires of the BTR's (armored personnel carriers) suddenly blew out, some ran out of fuel, some had some other problem. Candidly speaking, no one wanted to get involved. We could not get an answer from the GKChP as a whole or from (KGB Chairman) Kryuchkov in person to the question of who would make the decision about those to be killed and wounded. No one had an elementary understanding of how this would end. They put their hopes in the "Russian maybe": release "Alfa," Boris Nikolayevich will be killed, and then we will see what comes of this. But only civil war could come of this. We understood perfectly well the situation that we were in. Failure to carry out the order meant a trial, loss of rank, position, etc. Fulfilling the order would make us, in fact, the people who started a civil war in the country. The officers were ready to make this choice. Meetings had been held in the units in which one hundred percent of the personnel said that to proceed and carry out the order would mean to start a war in Russia with colossal casualties and the consequent destruction of the state. We reported the decision to refuse to storm the White House to the now deceased commander of the group, Major-General and Hero of the Soviet Union, Viktor Karpukhin. He understood everything perfectly well and agreed to what we wanted to do as a last resort. Our decision became quickly known. At that time it was impossible to conceal anything. Korzhakov knew us well and we knew Korzhakov well. And the officers who involuntarily turned out to be on one side or the other were friends. Everyone exchanged information among themselves concerning the fact that no one wanted this assault. I believe that in that situation the officers of "Alfa" behaved absolutely correctly, even though it turned out badly for us. After these events, the first and only attempt to abolish "Alfa" was undertaken. At that time the new commander of the group, Mikhail Golovatov, and I visited Korzhakov and told him that "Alfa" was the only unit that could defend both the country and Yeltsin personally. This was a clear signal to Boris Nikolayevich that if anything happened, there would be no one to protect him. And he paid attention to this signal and they left us alone. The entire correctness of this decision was proven in 1993. (Sanin) And what was the position of the officers of "Alfa" during the 1993 political crisis? (Goncharov) In 1993 the guys from "Alfa" also acted correctly and saved the lives of all of the participants of the events. We were given carte blanche and this was our decision. Both Baburin and Khasbulatov and the rest of their group remain good health, although we were fully capable of killing them all. On 4 October 1993 "Alfa" got the order to assault. The unit arrived at the White House and joined the negotiations with the leadership of the Supreme Soviet and its defenders. Our men promised to withdraw all of the people sitting in the Government Building intact and unharmed. And to the extent possible this is what they did. During the assault, group member Gennadiy Sergeyev, who was carrying one of the wounded from the building, was killed. A bullet struck him between his "Sphere" helmet and body armor. (Sanin) How do the "Alfa" members themselves feel about the fact that they are constantly getting entangled in the solution of political problems? (Goncharov) Candidly speaking, after the ascent to power of Mikhail Gorbachev and the collapse of the Soviet Union, unfortunately, there was no real capability to influence the situation, other than with the use of force. It is sufficient to recall the geography of our operations during those years: Vilnyus, Tbilisi, Stepanakert, Baku, Dushanbe. I can't say whether the political decisions were correct or not, but it is a fact that we executed the orders of the Homeland. And at that time we encountered treason for the first time. After the operation in Vilnyus, Gorbachev stated that he had no idea who sent us there, and that he was asleep when the decision was made. A fine President. He sends his officers on a mission and then disclaims them. But in general at that time there was a complete paralysis of authority, an unwillingness to execute decisions and assume responsibility for them. Gorbachev and those immediately surrounding him were genetically incapable of doing that. And this turned out badly for us. To this day we are reaping the fruits of the Vilnyus events. For example, not long ago they tried to arrest one of our former commanders, Mikhail Golovatov, in Vienna. (Sanin) How often do the leaders of the state try to pressure the decisions made by the commanders of "Alfa" Group? (Goncharov) We have never been afraid to disagree with decisions imposed from above. And when some kind of TsK (Central Committee) member, who has never held anything other than a hunting rifle, orders us to resolve a problem in a particular way, he needs to be politely sent away. And they have been sent away. The commander of a group almost always needs to be able to prove to the people above that this operations must be conducted in this manner, and in no other way. On 1 December 1988 in the city of Ordzhonikidze an armed gang of Yakshiyanets (who had been convicted three times) seized thirty students and their teacher as hostages. The criminals demanded to be given an aircraft to fly them outside the country. The representatives of the authorities who were conducting negotiations with them said that the Ordzhonikidze Airport did not have (aircraft) capable of such a flight, and they sent the children on a bus to Mineralnyye Vody. By that time, the decision to make the assault had already been made in Moscow, and we flew to Mineralnyye Vody. The terrorists asked for an aircraft to fly to Israel. Some of the country's leaders insisted that Yakshiyanets not be released, and we should show our force and power and start the assault. But the commander of the group at that time, Gennadiy Zaytsev, insisted that the criminals should be released. That's what they did, although the commander took a risk. At that time we did not have diplomatic relations with Israel. Then we flew to Israel and the criminals, who were arrested by the local forces, were brought to us. The main thing is that the lives of the children were saved. If we had made the assault anyway, I think that everything could have been much worse. (Sanin) Did you have the tactical capabilities to make the assault without endangering the lives of the hostages during their seizure in Budennovsk? (Goncharov) The tactical capabilities were there. But regardless of the expenses we incur to free the hostages, we always try to do everything to bring the operation to a logical conclusion and eliminate or capture the terrorists responsible. In Budennovsk, if we had made the assault there would have been losses, but the terrorists would have been 100 percent eliminated. (Sanin) But after all, (Prime Minister) Viktor Chernomyrdin was negotiating personally with Basayev... (Goncharov) With all due respect to Viktor Stepanovich and his reputation, the actions of the Prime Minister in that situation were fundamentally incorrect. This was a politically harmful decision for our entire country, and this was precisely the cause for giving encouragement to the development of terrorism in the North Caucasus. I don't know which one of Chernomyrdin's advisors put this idea in his head, but if we had made the assault in Budennovsk, the situation in the North Caucasus would have developed in a different manner. What happened during that time raised the banner of terror so high that taking it down later was very difficult. And we are still lowering it. (Sanin) How would you assess the activities of the "Alfa" officers in the operation to free the hostages in the Central Theater in Duborvka in 2002 and in Beslan in September 2004. (Goncharov) Both operations are black marks on both the unit and on the history of Russian antiterrorist efforts. Nonetheless, in the first one, in my opinion, the tactic that was selected was the only possible solution to avoid an enormous loss of life. Of course, it is a great pity that hostages were killed and died from (gas) poisoning, but the use of the so-called "laughing gas" was just about the only solution available at that time. Not only we, but also colleagues from many foreign special units, came to this conclusion. If the terrorists had activated the explosive devices that they had, everyone would have died, the hostages, the spetsnaz forces making the assault, and the residents of near-by homes. The use of the gas allowed us to enter the auditorium and with precise sniper fire neutralize the terrorists, without incurring huge losses. But at Beslan actually there was no assault. There the guys saved the children, and did not kill the terrorists. They drew fire on themselves as they covered the students with their own bodies. Our men who died in Beslan included Oleg Loskov, Aleksandr Perov and Vyacheslav Malyarov. Another seven men from "Vympel" died These are huge losses for special units, but I repeat again, at that time the matter at hand was primarily saving the children. We were not able to prepare and all of the decisions were taken on the spot, instantaneously. (Sanin) How effective do you consider the tactic of targeted elimination of terrorist leaders? (Goncharov) This is one of the most effective methods of combating terrorism under contemporary conditions. Using medical terminology, the "Alfa" group is a sharp scalpel, a direct action instrument, and the final argument when pills and enemas do not help. At the same time we understand perfectly well that metastasis of terrorist activities is so widely distributed throughout the entire world, that a single and rapid operation will hardly resolve the problem. If someone thinks that the elimination of a single leader will result in the destruction of an entire command, this is not correct. Terrorism is an enormous business, in which many countries are engaged. This business is passed on as a legacy, from one killed leader to another. Fighting in our North Caucasus has been going on so long not for an ideal, but only because combat operations are so lavishly financed. And by whom? One can only speculate. But I personally think this: no matter how hard we try to become friends with the Americans, we will never become friends with them. We can only be fellow travelers with them up until the time they use us for their own purposes. And then they will continue on their own way. And instability in the North Caucasus plays into their hands. (Sanin) Are the equipment, training and accoutrements of "Alfa" today appropriate for contemporary terrorist challenges and threats? (Goncharov) In regard to equipment, from our very first days we had all of the best. I remember how the people looked at us at, like aliens from another world, during one of the group's first operations in Sarapul. In December 1981 two conscript privates deserted from a unit with two assault rifles and seized 25 tenth-grade students and a teacher as hostages. We flew there during the night, and a huge crowd of distraught parents had already gathered around the school building. We were in our new uniforms, which no one had yet seen. We wore black clothing with cargo pockets and the "Sphere" helmets with armored glass. It seemed like the Sarapul residents who had gathered at the school were looking at emissaries from the Moon, judging from the expressions on their faces. And at that time they became one hundred percent convinced that we would be exactly the ones to save their children. And fortunately that's what happened. As soon as "Alfa" was formed the most modern weaponry was obtained for us from third countries through the channels of the First Chief Directorate of the USSR KGB. At that time our industry could not provide the spetsnaz with everything necessary. Today everything has changed. Several institutes are working for us and manufacturing capability exists where their developments are being implemented. The main requirement for accoutrements and equipment is to save the lives of our officers, and thereby the lives of hostages. It's somewhat immodest to praise ourselves, but without exaggeration I can say that by world spetsnaz standards we are one of the best. (Sanin) Not so long ago the President expressed the idea of conducting military operations abroad. How ready is "Alfa" for this? (Goncharov) Under current conditions these operations are possible and are justified. Citizens of our country should feel protected, just as the special unit officers who are conducting such operations. After all they are carrying out the orders of the President. For example, when in March 2001 two Chechen terrorists from the Arsayev group seized a Tu-154 aircraft on the Istanbul-Moscow flight, "Alfa" was ready to fly off and perform the special operation. Then, as the terrorists demanded, the aircraft was ferried to Saudi Arabia, where at the Medina Airport about 100 soldiers of the local spetsnaz supported by several BTR's assaulted the airliner. In my opinion, the operation was conducted unsatisfactorily. Two of the hostages were lost, including a Russian stewardess. Unfortunately, "Alfa" was never given the order to take off, but we were ready to do so. Today the unit is ready to fly to any place on earth and resolve a situation. And they are correct who say that if we shirk from protecting the interests of our own citizens any place on earth, our country will cease to be respected. (Sanin) There is much being said today about our absence of a national cause (literally: idea). What is the motivation of the soldiers while conducting special operations? After all, one has to have something to believe in. (Goncharov) I don't understand these conversations about the national cause. In my opinion, this is like faith in God. Either it exists or it does not. You can't write about the ideal and you can't reinforce it with some kind of edicts or orders. Unfortunately, today everything that was good, that was in the USSR, has been destroyed. One can relate to Stalin in different ways, but it is a fact that during the years of the Great Patriotic War the soldiers went into battle with the cry: "For the Homeland, for Stalin!" No one forced them to do that, they were completely sincere in this belief. If something happened today, it is hardly likely that somebody is going to rise from a foxhole with the cry "Forward for Abramovich!" No kind of national cause is going to emerge as long as the bureaucrats are operating in the country in shifts, and while they earn or steal their money in Russia and send their children to study abroad. Fortunately, all of the young men who come to "Alfa" today belong to that layer of young people who are not planning to leave Russia. We have unique examples of generational continuity. The father enlisted in "Alfa's" first recruitment, his son is now serving in the unit, and the grandson of the veteran is undergoing selection into the group. When we get together to play soccer it frequently happens that the veteran father plays for one team and his son, the active-duty officer, plays for another team. This is worth a lot. I can't tell you their names, but we are very proud of these dynasties. (Sanin) How did you personally end up in "Alfa?" (Goncharov) I finished school and then an automotive mechanics technical school in Moscow, and then left for the Army. I served in an athletics company near Moscow, where I became a candidate member of the KPSS (Communist Party of the Soviet Union). After demobilization they asked me to serve in the KGB. I studied for two years at the Leningrad school, and ended up in an operational unit. In 1974 my commanders did everything they could to stop my transfer to "Alfa," which had requested me. In 1978 the leadership of the special unit was sharply questioned about my transfer to "Alfa." And since 1978 I served in "Alfa" for 15 years, and completed my service in the position as deputy commander of the unit, and I believe that my best years were spent there. (Sanin) What are the criteria for selection into the ranks of "Alfa?" There are certain stereotypes about the soldiers of elite special units who are thought to be invulnerable soldiers, not unlike cyborgs. What are they really like? (Goncharov) Indeed, many people think that the soldiers who serve in special units are generally immortal. In our movies they show how after two hours of fighting the officer is cheerfully smoking, drinking his 100 grams (of vodka), and not the least disturbed by the wounds that he received. He is ready to run another 100 kilometers. In actuality the spetsnaz soldiers are the same sort of people of flesh and blood, and they feel the same pain and stress. But we get the best ones because we do not select them, we cull them. Do you sense the difference? We have to reject many for one reason or another. Once we culled out an officer from the border with Tajikistan, a splendid lad about 1.9 meters tall, who was a volleyball player and an overall handsome guy. He demonstrated excellent physical and shooting training, and the matter came down to assaulting by parachute. We ascended in the aircraft to a thousand and some odd meters, got ready for the jump, and saw his frenzied eyes. He braced his hands on the door, and none of our persuasions were successful in getting him to jump. We landed and started to talk, and in shock he yelled, "This can't be! I'll jump!" Three hours later we took off again and again he was not able to overcome his fear. After this, of course, we had to part with him. Someone who is unable to overcome the feeling of fear can not serve in the elite units. Not everyone can work in the command. There are rugged individualists who are answerable to themselves alone. They are psychologically unable to serve in such units, because if you are answerable to yourself alone, your life will be short and those of your comrades will be even shorter. (Sanin) Are there women in "Alfa" group? (Goncharov) At least there were some. One was even at the rank of colonel, although it is true that she worked in a technical department. If you are thinking about "shooters," however, thus far there have been none. (Sanin) Next year the Association of "Alfa" Veterans will be 20 years old. What goals has it set? (Goncharov) It was formed after the events in Vilnyus. In our state, alas, there are many who are inclined to care for you and cherishe you while you are alive and needed, but as soon as you fall out of the ranks, everyone forgets about you. This is especially the case when the subject is supporting the families of our 26 members who were killed. In essence they don't have to depend on help from the state, and we have assumed these functions. We started to earn some money. After all, we were not just "guys wearing helmets," as they say. Many know several foreign languages, have graduated from prestigious institutes of higher education, and after their service they went into business and became rather successful. Today the association unites more than 500 people, and its members are made up only of those who have served in "Alfa" at some point, and no one else. It is impossible to join us for money, bureaucrats of any level are also forbidden here. This is a narrow corporate organization, without any exceptions. Incidentally, I am very often called from the MVD (Ministry of Internal Affairs) or the FSB (Federal Security Service) and asked if some person or other is a member of the association. They confiscated an identification that the person had that was allegedly ours. In each instance we conduct a careful check, and I can say that to date not one of our identificat ions has gotten into the wrong hands, and none will. Thus far, knock on wood, we have not stained our honor in any way. [return to Contents] #20 Business New Europe October 20, 2011 Russia moves to 120th, from 124th, in the Doing Business ranking by World Bank VTB Capital --- now ahead of Brazil News: Russia's rank in the World Bank's Doing Business report has improved this year from 124th to 120th (out of 183 countries). The report's authors highlight that the procedure for registering companies has become easier and foreign trade operations simpler. In addition, it is now possible to submit paperwork to the courts in electronic form and there has been a reduction in the cost of connecting to the power grid (although of all the countries in question, that cost remains the highest in Russia). Brazil slipped from 120th to 126th. China is 91st (from 87th), India is 132nd (from 139th), Turkey 71th (from 73rd). The long-time holder of the #1 spot remains Singapore; at the bottom of the ranking is Chad. Our View: This is an independent and authoritative demonstration that, even if Russia is some distance from getting to the top third of the roster, and many problems remain, contrary to popular perceptions the interim momentum on the structural reform side has been tangibly positive over the past 12 months. [return to Contents] #21 October 20, 2011 'Russia may become WTO member in weeks' Even with Georgia still opposed to Russia's WTO accession, it may still become a member through a vote sooner than many expect, the head of Russia's WTO delegation, Maksim Medvedkov, has told RT. Russia is the only major economy still outside the WTO and has been attempting to join for almost two decades now (since 1994). But according to Russia's chief WTO negotiator, the wait is all but over. "We have concluded almost everything we were supposed to negotiate, but a few technical questions which are still outstanding, and we need not even a few months, but a few weeks or even days," Medvedkov said. "The timetable we currently have at our working party a part of our negotiation body is extremely tight. We will complete have four more discussions by October 27, and another four are to take place somewhere in mid-November. So we have a schedule and as soon as we implement it, we will be closer to the WTO than we were ever before," he added. At present Russia is striving to achieve the approval of the last of the 89 WTO members, Georgia, which has become the final stumbling block. The negotiations have failed time and time again, with the latest Switzerland-mediated solution also rejected by Tbilisi. Along with an up-to-date cargo monitoring system, Georgia wants international observers to monitor the borders of Abkhazia and the Tskhinval region. Medvedkov believes the latter demand is outside of WTO requirements. "The requests we receive from Georgia have nothing to do with the WTO. It's something else. We have proposed to negotiate trade issues with our Georgian colleagues just as we did with all other 88 WTO members, but unfortunately this doesn't seem to be their aim. And the requests we receive are far beyond the WTO rules," Medvedkov says not ruling out a WTO voting on Russia's membership. "WTO rules clearly state that, if there is no consensus in respect of accession, a voting takes place. That is the rule, but in practice it was used only once in WTO history. Whether or not it can be used in Russia's case is a decision that is up to members," Medvedkov says. "We had completed our negotiations for market access with all members by 2006. After that we dealt with many different things, and most of them had nothing to do with trade." This, however, hardly came as a surprise to Medvedkov, who sees little differences between Russia's accession and that of China, as "they faced more or less the same problems." "Accession of such a vast country as Russia is always a balance between trade and politics. WTO usually tries to isolate itself from politics, but in our case it wasn't always possible," he said, stressing that he was never forced to negotiate political issues, though many of those did affect his negotiations. When the WTO membership becomes a reality, exporting companies of course will thrive. But Medvedkov does not share the concerns that industries like agriculture and the automobile industry, which traditionally pin their hopes on government subsidies, will suffer. As Medvedkov notes, contrary to popular belief the WTO does not prohibit subsidizing, but merely regulates it. "And it is impossible to achieve a complete modernization without having a connection with other markets," Medvedkov observes. Overall he sees Russia's WTO membership as a win-win situation for both the country, which has a "huge interest to see its market based on WTO rules" and the organization members, though at the moment they are trying to get "as many concessions as possible" from Russia. [return to Contents] #22 Ousted Russian Finance Minister Kudrin Views Country's Budget Policy Risks Kommersant October 18, 2011 Article by former Russian Finance Minister Aleksey Kudrin: "Broadside to the Waves. Aleksey Kudrin on the Short- and Long-Term Risks of Budget Policy in the Russian Federation" Vice Premier Aleksey Kudrin is the only member of the government in the past decade to resign from his post because of disagreements with the cabinet's proposed future course. The finance minister's views of the current dilemmas in the economic course have always been expounded publicly. Nonetheless Aleksey Kudrin deemed it necessary, in an article for Kommersant 's readers, once again to set forth his vision of the current risks of Russia's budget policy in systemic form. (Introduction ends) A complex combination of domestic political motives and the as yet relatively favorable external economic situation are inclining the Russian Government toward pursuing a risky economic policy. However, it does possess the instruments necessary for adjusting this course; it is only necessary to define the priorities. But there is almost no time for that. Increasing pensions and wages, reequipping the Army, modernizing industry -- all of these are absolutely correct tasks that a responsible state power should set itself. By using the imagination one can even imagine what the conditions would look like in which all these tasks could be tackled simultaneously. Unfortunately the picture currently outside our windows is entirely different. The Crisis and Oil Today there are several serious local crises, including the eurozone crisis, and the expectation of a second wave of the global economic crisis. Moreover, the possible scale of the latter is currently difficult to assess, since it could be characterized -- for the first time in history -- by a crisis of sovereign debts, which will paralyze the borrowing market and close it, first and foremost for developing countries. An awareness of the seriousness of these threats is making the economically strongest countries of the world go over to a regime of constant and tough control of their spending. Basically, only the scale of the cuts is being discussed. "...The developed countries have committed to halve deficits by 2013 and stabilize or reduce government debt-to-GDP ratios by 2016" -- so says the declaration of the summit of leaders of the G20 states, adopted in Toronto in June last year. Let me remind you that Russia is also a member of the G20. Furthermore, outside our windows oil prices are at a historical maximum, which you might think could only delight us. However, optimism is moderated, first, by the well-known cyclical nature of the dynamics of these prices: In the past 10 years alone the average annual oil price was only $60 -- almost half the present level. And second, the current oil and gas "super-revenues" are being spent without leaving a residue, without creating any kind of "safety cushion" in case of a dramatic change in the situation. Whereas in 2008 the budget was balanced at a price of $57.5 a barrel, the 2011 budget was balanced at $109 and the 2012 budget only at a price of $117.2. Spending Or Taxes The dull bookkeeping term "balancing the budget" (in other words, the absence of a deficit) conceals an extremely dramatic story about "living within one's means." In 2008 the budget was planned in such a way that with a fall in oil prices from the predicted $60 to $30 the deficit would not exceed 3% of GDP. Theoretically that kind of deficit could have been tolerated for three or four years -- closing the gap through borrowings while waiting for the situation to improve. But for 2012, with a projected price of $100, a deficit of 1.5% of GDP is planned. This means that with a fall to that same figure of $60, a deficit of 5.5% is formed. In these conditions the preservation of the planned level of spending will consume the remains of the reserve fund in approximately a year, and after that, spending will still have to be cut (without this, it will certainly be impossible to obtain access to loans) -- by 2.5% of GDP, that is to say, 1.35 trillion rubles. For comparison: 1.35 trillion is the entire sum planned in next yea r's federal budget for education, health care, and culture, plus half the subsidies to the regions. Are there alternatives to cutting spending? Yes: increasing taxes and/or starting up the printing presses. In Russia's conditions both of these would mean putting back the formation of the necessary investment environment (including the achievement of a competitive credit interest rate in relation to the outside world) by at least five to seven years. And that would reduce or "nullify" the pace of the much desired modernization of the economy. In 2006 the very important strategic decision was adopted -- to lift the restrictions on the movement of capital in Russia, basically to ensure the convertibility of the ruble. This is a key condition in the contest for world investments, but it requires extremely careful behavior, not to say a tough macroeconomic policy, since in the absence of restrictions capital readily leaves an environment that it finds uncomfortable. This kind of speculative movement can easily be demonstrated by citing the example of the influx/exodus of capital in the past four years: In the precrisis year 2007 the influx totaled $81.7 billion, at the peak of the crisis in 2008 there was an exodus of $133.7 billion, and in the first nine months of this year the exodus amounted to nearly $50 billion. Analyzing our budget projections, investors can see very well the crossroads we are facing: It will be necessary either to reduce spending (and many of the decisions that have already been announced are hardly capable of being cut, for instance the increase in pensions and servicemen's pay) or to increase taxes (considering emission to be an inflationary -- the worst -- tax on the entire economy). Priorities and Prioritizing There may be several priorities, but not everything can be crammed into this category. Although we do try to prove otherwise... In the near future it is proposed to put teachers onto the average wage for the country's economy. By the end of the year the regions must determine the pattern for this transition: either immediately, or by 30% initially, with the rest next year. The bottom line is 100 billion rubles a year for secondary schools alone. Changes in remuneration for teachers in higher education are not yet being discussed but it would be strange to forget about them entirely. This is a very strong -- ideological and strategic -- decision, since it is geared, among other things, to wages in the commercial sector of the economy. Only a few countries in the world have ventured to adopt such a decision, thereby directly indicating that education is their main priority. From December 2009 through December 2010 -- that is to say, in the context of continuing crisis phenomena -- pensions in Russia were increased by 45%, which emphasizes the priority attached to pension provision. In this context, the law adopted in 2008 envisages an increase in pensions above the level of inflation, which in effect means preserving the deficit in the Pension Fund through index-linking. Next year this deficit will exceed 1 trillion rubles -- one-fourth of all payments. At the same time the decision that has been made on reducing the insurance contribution from 34% to 30% for two years -- in the interest of business -- is disorienting business itself, which is trying to find some way to increase its planning horizon: two years, but then what?... But both the educational and the pension priorities pale in comparison with the military priority. The arms program for the next 10 years, formulated by the government and agreed by all the departments, was initially valued at 13 trillion rubles, which would already mean an increase, in comparison with the preceding 10 years, by 50% at comparable prices. However, at a certain point it swelled to 20 trillion. This difference of 7 trillion could be compared, for instance, with the amount of all investments in fixed assets, which are expected to be at the level of 10.5 trillion rubles this year. The defense industry's ability to use this money effectively to any extent has not been properly investigated and prompts great doubts: The considerably more modest defense order last year and this year basically failed. Apart from the arms program (purchases of manufactured products), it is proposed to pour 3 trillion rubles into the defense industry in the form of the federal program for the development of the defense complex (investments in fixed assets), which basically means switching the entire defense sector back to state funding. Whereas at the moment the proportion of private capital in the defense complex is estimated at 60-70%. Decisions on increasing servicemen's pay also underwent significant metamorphoses en route. Initially it was proposed to increase the wage of a graduating lieutenant from the existing 29,000 rubles to 40,000. (Let us note that in the major developed countries lieutenants receive the average wage for the economy -- which in our country is 23,500 rubles -- or about 20% more.) Then this figure rose to 50,000 rubles a month. The increase from 40,000 rubles to 50,000 rubles in total -- that is, taking into account the entire "network" of siloviki (security services) -- requires 300 billion rubles a year. Let me remind you that all federal spending on health care in 2012 will total 400 billion rubles. The Art of the Possible In the light of the above I consider it necessary to assess realistically the risks of a new wave of crisis, and (I consider it) possible to undertake short- and medium-measures to prevent its exacerbation in Russia. First. It is necessary once again to set the goal of ensuring a deficit-free federal budget at a price of $90 a barrel in 2015. At the very least, in the light of the fact that decisions were adopted last year on major budget commitments that have their own inertia, an interim goal could be set: to achieve a balanced budget at $100 a barrel by 2015, postponing the main goal to 2017. Second. The rule for the expenditure of oil and gas revenue should be clearly defined, since this influences inflation, the rate of exchange, and the formation of government reserves and is very important to investors. Its fulfillment would substantially increase the stability of the macroeconomy. Basically the level of balance at a specific oil price provides the point of reference for this rule, but it should be enshrined in the Budget Code, as was the case before the crisis, and the government should not evade it when submitting the budget to the parliament, no matter what other important tasks may be set. Third. There should be a review of the increase in military spending both on equipment and on pay. In the existing military-political situation the objectives of rearming could be achieved not in 10 years but in 15. As a first stage pay could be increased not by 100% (with the doubling of pay, the total amount of pay and pensions for the military will increase by 12 trillion rubles in 10 years), but by 50%, returning to a further increase when the threat of crisis is past and accompanying this with additional decisions on the optimization of numerical strength. Fourth. The strategy on questions of social and pension provision should be decided as early as next year, in order to be able to calculate the use of all resources and make provision for the more active investment of funds in development programs. I do not rule out that it may be necessary to restrict the index-linking of pensions to inflation alone -- until the elimination of the Pension Fund deficit. Fifth. It is necessary to program as an objective the lowering of the budget load in relation to GDP, that is to say, the reduction of expenditure and the non-increase of the main taxes. (Practically all successful examples of catch-up development in the postindustrial world have happened in countries with a budget load lower than in the most advanced countries. ) And also the preservation of low inflation, with its subsequent reduction to 4-5% in 2014 and to 3% subsequently. Russia is currently facing the need to create a new model of economic growth -- not on the basis of increased demand whipped up by injections of "oil" resources, but on the basis of the growth of private investments backed up by a stable financial system with low inflation and a low interest rate, along with other institutional reforms. Only if these investments start wanting to come into all sectors and if this process becomes a mass process for both small and big business -- only then will it be possible seriously to expect the launch of the large-scale process of modernization. [return to Contents] #23 Moscow Times October 20, 2011 8 Tips for Expats to Get the Most Out of Russia By Luc Jones Luc Jones is a partner with Antal Russia, a British executive recruitment company working in Moscow since 1994. Two. [return to Contents] #24 October 20, 2011 Gaddafi's end is not the end of the war has dies. However, the news about Gaddafi's death was not immediately confirmed by independent sources. When journalists in Moscow asked Russian President Dmitry Medvedev to comment of Gaddafi's capture, the Russian leader said it was a very good news. At the same time, Medvedev said that the fate of the displaced Libyan leader must be decided by the Libyan people. "Libya must become a modern political state," Medvedev said on Thursday while holding a joint press conference with Dutch Prime Minister Mark Rutte. "And Libyans themselves must decide on Gaddafi's fate," the Russian President said. Also on Thursday, 'if' category, but in 'when'," 'human [return to Contents] #25 Nezavisimaya Gazeta October 20, 2011 SIGNALS FROM WASHINGTON, D.C. The rift between Russia and the United States over the future European missile shield remains wide Author: Victor Litovkin WASHINGTON SAYS THAT IT WANTS A MISSILE SHIELD COMPROMISE WITH RUSSIA WHEN IT REALLY DOES NOT Washington is signalling readiness for a compromise with Moscow in the matter of missile shields. Addressing the North-Atlantic Council, U.S. Missile Defense Agency Director Patrick O'Reilly invited the Russian military to come and see that deployment of the European missile shield could pose no threats to Russia. O'Reilly said that the Russian military could obtain all information on missile killers from its own radars. He added that Standard Missile-3s were fairly small (weighing only about two tons each) and therefore could not be used to intercept Russian ICBMs. O'Reilly said, "We offered all these technical arguments to the Russians. We even went so far as to offer them presence at our flight tests so that they bring their own gear and become convinced that our missiles are only good at countering regional missile threats and not against the Russian strategic forces." Ellen Tauscher, Under Secretary of State for Arms Control and International Security Affairs, said that Washington had been repeatedly telling Moscow that the ballistic missile defense system it was developing was no threat to the Russian strategic potential. "The missile shield we are developing in Europe is not aimed at Russia. We've been saying it at all levels, in public and at closed meetings. We are prepared to sign a document to this effect." Tauscher said, however, that signing of all and any legally binding documents was out of the question all the same and that the United States would never accept any restrictions on the future ballistic missile defense system. It is unwillingness on Washington's part to sign legally binding documents that disturbs Russia and generates doubts in the sincerity of the United States in connection with the true objectives of the missile shield installed along the Russian borders (in Romania, Bulgaria, Poland, Czech Republic, Turkey). "The system we mean to develop is supposed to counter missile launches from the Middle East," said Tauscher and added that there was no way for the future missile shield to develop the capacity to counter the Russian strategic potential. "That goes for all four phases of its development," she said. Russian experts fully agree with Tauscher as long as the matter concerns the first two phases of development of the ballistic missile defense system. They accept that the Aegis system with its SM-3s is only good against intermediate- and shorter-range missiles Russia does not even have. On the other hand, phases three and four of the planned development may actually elevate the missile shield to the level where it will start being a threat for the Russian strategic forces posted in European Russia. Particularly when the United States station its Aegis ships in the northern seas off the coast of Norway, its NATO ally. This is why the Russians - from the military to the powers- that-be - dismiss Washington's assurances that the missile shield will never be aimed at Russia. This is why they insist on a guarantees in the form of a legally binding document. Russian Representative to NATO Dmitry Rogozin said meanwhile that there was more to the matter than vague guarantees alone. "We want this document to include specific criteria - the number of missile killers, their positions, velocity, range... Five criteria at least." This is what become a true guarantee and what will allay Russia's fears that the European missile shield will weaken its strategic potential. Rogozin said, "It is NATO as well as the United States as such that ought to give these guarantees... And no, there can be no compromises. We ought to stand fast." Moscow's uncompromising stand is attributed to the fact that U.S. President Barack Obama desperately needs some foreign political success to bolster his positions on the eve of the presidential election in his country. Foreign politics is where Obama has been anything but successful. It is believed that he is even ready to come to Moscow before the end of the year and sign some sort of document. In fact, this signing will benefit President Dmitry Medvedev as well - but only on the terms outlined by Rogozin. Russian military specialists are somewhat skeptical of the offers made by O'Reilly and Tauscher. They say that the Russians do keep an eye on SM-3 tests even without a special invitation from the Americans. According to Rogozin, what the Americans suggest and offer comes down to a simple formula. "What they suggest is that we send our representatives over there to take a look and see whether or not their missiles hit the designated targets. Who do they think we are, tourists?" Same thing with Tauscher's offers. Indeed, why sign a document which is not even legally binding? [return to Contents] #26 Expert Views Russia's Possible Response To US Missile Defence System RIA-Novosti Moscow, 19 October: If the USA refuses to provide legal guarantees of a peaceful nature (as received) of the European missile defence system to Russia, it will do the same in the Asia-Pacific Region (APR), the head of the Centre for Military Forecasting at the Institute of Political and Military Analysis, Anatoliy Tsyganok, thinks. "If the USA refuses to provide legal guarantees for the missile defence system in Europe, this will also apply to the APR," he told RIA Novosti. Tsyganok was commenting on US Under Secretary of State for Arms Control and International Security Ellen Tauscher's statement, who said on Tuesday (18 October) that Washington was prepared to offer written assurances of a peaceful nature of the future missile defence system in Europe but could not provide legally binding guarantees demanded by Moscow. "If the Americans do not provide legal guarantees now, this presents Russia with a rather complicated problem," Tsyganok believes. According to him, if the USA refuses to recognize legally that the European missile defence system is not directed against Russia, there may be a response from Moscow. He explained that Russia was already "forming a battalion of Iskander (missile systems) in the Kaliningrad Special Military District and in the Leningrad (Military) District". In addition, means of radio-electronic suppression (REP) will be used to jam the missile defence navigation stations in Europe. "But both of these will be fairly difficult to implement," the head of the Centre for Military Forecasting thinks. According to him, "this is about not only the missile defence system in Europe. The USA is deploying a missile defence system in the Asia-Pacific Region as well". He added that he was talking about two joint groups of the USA (four ships with Japan and another four ships with South Korea equipped with the Aegis combat information and control systems). Tsyganok believes that it will be difficult for Russia to jam this navigation. He explained that "we still do not have the Glonass system, without which it will be difficult to accurately locate all these cruisers equipped with the Aegis systems". This applies to both the Asia-Pacific Region, the Black Sea and the Mediterranean Sea. At the same time, if Russia receives legal guarantees from the USA, it will save significantly on the military-industrial complex, Tsyganok noted. "We would spend less money on the production of missiles and radio-electronic suppression systems. During a crisis, it would be beneficial for Russia, but the Americans are not giving this opportunity to Russia," the expert concluded. [return to Contents] #27 Moscow Times October 20, 2011 Top Election Official 'Barred From U.S.' By Alexey Eremenko The country's top elections official said he has been "honored" to be included in the "Magnitsky list" of Russian officials blacklisted for U.S. entry over human rights violations. Vladimir Churov, chairman of the Central Elections Commission, said as a result he would not be able to travel to the United States to work as an observer at the U.S. presidential election in November 2012. "Of course, I don't have anything to do with [Sergei] Magnitsky," Churov said in an interview with Dozhd television aired Tuesday night. "I've never seen him, I don't know him, I had not heard [about him] before the story about his death." Hermitage Capital lawyer Magnitsky was detained in 2008 by law enforcement officials whom he accused of defrauding the government of millions of dollars. He died in pretrial detention 11 months later of health problems and, according to an independent, Kremlin-ordered investigation, a severe beating administered by prison guards just hours before his death. No one has been charged in connection with his death. U.S. Senator Benjamin Cardin introduced last year a bill proposing sanctions against 60 Russian officials implicated in Magnitsky's death. The bill has never been passed, but the State Department confirmed this summer that dozens of unspecified Russian officials had been blacklisted over the Magnitsky case. Churov told Dozhd that he was on "Cardin's list," but gave no details. He added that he would only travel to the United States at the personal invitation of Cardin, who did not comment Wednesday. A U.S. Embassy spokesman did not immediately reply to an e-mailed request for comment. Churov, who has bristled at requests from Western election observers to monitor State Duma elections in December, added that he thought being on the list was an honor because "it exposed the stupidity of those who make such lists." Churov, indeed, was never implicated in Magnitsky's case and was not on Cardin's list, which has been made public. He is, however, routinely accused by the political opposition of interfering with elections on behalf of the Kremlin and the ruling United Russia party. The allegations earned him a slot on a broader list of 308 Russian officials accused of violating human rights that opposition leader Garry Kasparov passed to the U.S. Congress in June. Other well-known names on that list included the Kremlin's propaganda mastermind Vladislav Surkov and Nashi founder Vasily Yakemenko, currently of the Federal Agency for Youth Affairs. [return to Contents] #28 Russia Beyond the Headlines October 19, 2011 Mitt Romney: The no-apology candidate The Republican front-runner has taken an aggressive stance on Russia in his campaign speeches, but will it translate into policy in a Romney administration? By Eugene Ivanov Eugene Ivanov is a Massachusetts-based political commentator who blogs at The Ivanov Report.. [return to Contents] #29 Russia Beyond the Headlines October 19, 2011 Getting the Congressional Russian Caucus off the ground By Alexander Gasyuk, Rossiyskaya Gazeta Since the Republican Party took over the U.S. House of Representatives almost a year ago, cooperation between American lawmakers and their Russian counterparts has stagnated. Capitol Hill proponents of proactive U.S.-Russian relations have put forward the idea of creating the Congressional Russia Caucus (CRC). The Caucus, focusing on trade and economic relations, will include both Democrats and Republicans. The bipartisan group said it will start working no later than November. Alexander Gasyuk, Washington, DC correspondent for Rossisyskaya Gazeta, spoke to the founder of this initiative, ranking member of the House Committee on Foreign Affairs, U.S. Rep. Gregory Meeks (Democrat-NY), for Russia Beyond the Headlines. RBTH: What was the idea behind this Caucus and who is going to participate? Gregory Meeks: My thought was that when you look the United States and Russia, there is great opportunity for us to do business together and understand one another. As for the participants, it will be both Democrats and Republicans. I already have Dan Burton, who is a ranking member of the House committee on Foreign Affairs and the leading Republican in this committee responsible for Europe and Eurasia. Congressman Burton has agreed to co-chair this caucus with me. What we are looking to do is to develop relationships with our various counterparts in Russia. Also I look forward to facilitating business-to-business contacts, and possibly I am looking to lead trade missions of U.S. companies over to Russia and vice-versa. We look at our economies and there is a growing opportunity for us to do much more trading together. We have indicated that we would love to get Russia into the WTO [World Trade Organization]. RBTH: What would be the first steps of the Russia caucus? GM: My hope is to try to connect various members of Congress. We will be sending letters inviting people to join, but we want this caucus up and running no later than November. RBTH: Why are there fewer Congressional delegations visiting Russia nowadays? GM: Unfortunately, we are still stuck in a post-Cold war mentality - I am talking about many individuals in the U.S. Congress and Russian Duma - and we have to free ourselves from that and look at the new world we're living in. And that is where we begin an understanding of one another that we have not had before. The "reset" idea the President Barack Obama has put forward is a good thing, and no matter who wins our elections as you know both countries have elections coming up those of us who will be in Congress working with those in the Duma have to forge ahead. I look at the accomplishments that the two nations have made in agreements as a result of "reset." Now it's time to get this to the next level. RBTH: What do the White House and State Department think of your idea to establish the Congressional Russian Caucus? GM: I spoke to both, and the State Department welcomed the idea as did the White House. The State Department likes trade and diplomacy. Of course, we have differences, but I would rather focus on what we can agree upon. RBTH: Do you have any feedback from the American business community? GM: American business people indicated that this is absolutely the right thing to do. They are very enthusiastic, and some have asked already to become participants in meeting and discussions of the caucus. For instance, the U.S.-Russia business Council and U.S.-Russia chamber of commerce expressed their interest in getting involved in this process. [return to Contents] #30 Russia Profile October 20, 2011 The Unwilling Emperor Despite the Success of Some Russian-Inspired Regional Economic Integration, Russia Says it Does Not Want to Recreate a Soviet-Type Economic Empire By Tai Adelaja When Russian Prime Minister Vladimir Putin returns to the Kremlin next year, he may have to micromanage not just Russia as a sovereign economic entity, but also part of the wider economies sprawled across the rugged post-Soviet space. Russia received a surprise boost on Tuesday as prime ministers from eight former Soviet states suddenly decided to sign a free economic zone agreement. Experts say the development would bring the Russian prime minister closer to his objective of re-uniting former Soviet states under a single economic umbrella and create an economic block similar to the European Union. The free-trade deal, which was announced in St. Petersburg late on Tuesday, was signed between Russia and seven ex-Soviet republics, RIA Novosti reported. Signatories to the agreement include Ukraine, Belarus, Kazakhstan, Armenia, Kyrgyzstan, Moldova and Tajikistan. The Central Asian nations of Uzbekistan, Azerbaijan and Turkmenistan are expected to join by the end of the year. But the real catch for Russia, analysts say, is Ukraine, which had previously sought closer trade ties with the European Union but whose ambition is now on shaky footing after the jailing of former Prime Minister Yulia Tymoshenko. The agreement, which must be ratified by the parliaments of the eight countries before becoming effective in 2012, would make the economies of the signatory nations more competitive, Putin said. "This is a fundamental agreement, which will serve as the basis of trade and economic relations between our countries," Interfax quoted Putin as saying. Russia is already locked with Kazakhstan and Belarus in a Customs Union, which eases trade among the three large former Soviet economies without fully abolishing all duties and tariffs. Earlier this month, Putin laid out his vision for a tighter integration into a "Eurasian Union" in an article published in the Izvestya newspaper. "We offer," Putin wrote, "a model of a powerful supranational body, which could turn into one of the modern-day world's major hubs and play an effective role in linking Europe to the thriving Asia-Pacific region." Even earlier, Putin peddled the same idea at a Business Customs Forum, stressing the necessity of creating the Eurasian Economic Community as early as in 2012. Despite such optimistic expectations, the Russian Prime Minister appeared to have been taken aback by a sudden breakthrough in talks on Tuesday. "I have to significantly modify my speech because we quite unexpectedly came to a decision after long, sometimes critical but meaningful negotiations," Putin said according to a transcript posted on the Russian government's Web site. Christened the "St. Petersburg treaty," the agreement would formally replace dozens of bilateral and multilateral trade agreements previously signed between the former Soviet republics. The latest agreement aims to scrap export and import tariffs on a number of goods and facilitate trade within the post-Soviet space. Details about what goods will be included are yet to be spelled out, but the conditions of the free-trade agreement closely resemble those of the World Trade Organization, said Andrei Kushnirenko, the head the Economic Department of the CIS Executive Committee and Russia's former deputy chief WTO negotiator. Such sentiments have prompted some analysts to suggest that Russia, the only major economy not included in the WTO, has been trying to put former Soviet states under a common currency and trade system to rival the world body. President Dmitry Medvedev appeared to give credence to such view on Wednesday when he said that Russia will live on even if the World Trade Organization (WTO) rejects its membership bid, despite 18 years of seeking membership. However, economists say there is too much at stake for Russia to abandon long-sought objectives in the eleventh hour. "Given all the achievements in the past year or so especially bilateral agreements with countries like the United States and the European Union I think Russia will certainly join the WTO, if not this year, then later," said Ivan Tchakarov, Renaissance Capital chief economist for Russia and the CIS. "The St. Petersburg agreement is by no means mutually exclusive to WTO ascension. I believe they are trying to raise the stake a little bit and put pressure on the Americans and Georgians to clear the way for Russia's WTO ascension." Meanwhile, Prime Minister Putin has said that while Russia seeks an economic alignment with former Soviet Republics, it has no ambitions to reintegrate them politically. "We are not talking about political integration, about the revival of the Soviet Union, Russia is not interested in that today," Putin told executives of three national TV channels in an interview. "It [Russia] is not interested in taking on excessive risks, taking excessive responsibility for the counties that for various reasons remain close to us." Putin also dismissed Western media reports ascribing imperial ambitions to his country, saying that Western experts who criticize Russia-CIS states integration policy should "mind their own business." "Tackle rising inflation, state debt or at least obesity. Mind your own business," Putin said. [return to Contents] #31 The Japan TImes October 20, 2011 What is in store for Russian Asia? By ANDREY BORODAEVSKIY Russian professor Andrey Borodaevskiy, an expert on international economic relations, is co-author of "Russia in the Diversity of Civilizations." MOSCOW When the Soviet Union disintegrated, a large number of ethnic Russians and other Russian-speaking and Russian-cultured peoples remained outside the borders of the Russian Federation creating, in the short run, many acute and complicated problems but, in the long run, eventually facilitating a revival of amenity and mutually profitable cooperation between the newborn nation-states in the future. Thus, not only complementarity of national resources and tight cohesion of economic structures will be at play, but also healthy elements of traditional cultural ties pushing toward a revival of centripetal forces bringing the "brother peoples" together again. Speculating about the future of Russia, one should not ignore the existing prerequisites for the emergence of an integration system including the three Slavic republics plus Kazakhstan, and the gradual "twinning" of their economic structures. On this path, the relatively most successful of the integration schemes in the former imperial area the Euro-Asian Economic Community with its Customs Union and Single Economic Space mechanisms can play an instrumental role (though none of them include Ukraine). Meanwhile, one is tempted to agree with the concept according to which innovative investment can bring steady profits only in a market with a sufficient "critical mass." In this particular case, that means a single market of Russia together at least with Ukraine and, still better, with some other fragments of the former Soviet empire. Unfortunately, there are only meager chances for such a development, while the idea of a "second historic re-union" of Russia and Ukraine is perceived as a delirious dream. In view of the acute domestic and international problems Russia is facing, some outstanding brains have been reflecting upon "deadly threats" to its near and more distant future. Usually the list of such threats begins with the ongoing demographic catastrophe: the speedy depopulation of the country especially its eastern regions on the one hand, and the diminishing stock of ethnic Russians on the other hand. The remedy is routinely seen in an eventual reorientation of economy toward the "outstripping development" of its consumer sector. This is a sound idea which deserves backing in every possible way. It remains unclear, though, exactly in what way such a historic radical turn can be achieved in a society in which political authoritarian monopoly reigns supreme, while economic state capitalist and oligarchic monopoly is in the making, a society in which there is no reliable law and order, and both creative public opinion and the private initiative of the common people are largely ignored and neglected. According to Standard and Poor's, by 2050 Russia's population will decline to 116 million people. Moreover, by 2035, Russia's credit rating may be reduced to "unfit for investment" all as a result of the catastrophic demographic trends (low birthrate, high mortality, rapidly graying population, etc.). However, it is important to emphasize that the "deadly threat" of depopulation is hardly one of a primary nature. Rather, it looks like a concentrated and summing-up result of faults inherent in the established social, economic and political order, which denies pluralism, competition and freedom of choice. The people's "body" remains puny and struggling for survival. The middle class is thin and hardly growing. It is only the "head" and some "organs" that are well-nourished and even getting excessively plump. To boot, the Russian leadership favors populism of a bad variety based on "siege moods" and on an actual denial of the potential of far-reaching international cooperation at least where the presence of foreign players and freedom of their actions on Russian territory are concerned. The prevailing geopolitical approach to international affairs turns out only slightly covered anti-American and anti-NATO sentiments, or hard feelings toward Europe because of criticism coming from Brussels, or rather irrational attempts to selectively manipulate gas supplies to put energy pressure on some trading partners, or jealous and preoccupied attitudes toward former Soviet republics. Thus, to make an adequate response to the "fatal threats" it faces, our society needs to enact far-reaching reforms to solve many interconnected problems: to destroy the political and economic monopoly, to democratize the social and political "rules of the game" and thus secure necessary consolidation of civil society, finally to achieve fully-fledged openness of the economy and the country in general and actively integrate it into the global system. In practice, it implies transition to political pluralism, safe-guarding of conditions necessary for competition, active backing of small and mid-size businesses and decisive steps toward integration into the global economy through the unequivocal acceptance of the WTO rules. A modern and adequate legislative base should be created albeit the present composition of the Russian parliament, the Duma as well as the current election rules that perpetuate the utter domination of one party on all levels of political life and will assure that Prime Minister Vladimir Putin safely returns to the presidency for an unforeseeably long time hardly favor enactment of the necessary political and economic reforms. Meanwhile, only a genuine parliamentarian democracy based on a division of powers can enable society to radically cut and streamline the state apparatus, to de-bureaucratize it and to free it of at least the worst manifestations of corruption. It can maintain law and order without recourse to Stalin-style terror, exclude cases of arbitrary rule and selective application of legislation, and guarantee fundamental liberties to the mass media as the main channels of public opinion. Only through such a radical evolution, will it be possible for Russia to create a favorable political and investment climate, and to survive as a great nation. It is also absolutely clear that standing alone, without attracting foreign funds and foreign people, will hardly make it feasible for Russia to secure the rapid development of Siberia and its Far East. Such a major endeavor requires a new geo-economic approach that can secure legal and well-organized inflows of economic migrants and long-term capital and modern entrepreneurship in contrast to the wild and inhumane, illegal and semi-legal, institution of "guest workers" that Russia has today. The concept of the Eurasian Union, put forward by Putin as one of the first elements of his presidential program, seems to be too narrow and thus hardly adequate to such a paramount undertaking either because it would, even with the highly improbable participation of Ukraine, embrace only basically poor countries with meager financial and labor resources, and no proper markets. The further industrialization of Russia's eastern regions should become a genuine multinational mega-project involving both Russia's Asian neighbors (China, Korea, Japan, etc.) and such major players as the United States and Europe. Otherwise, it seems it will be impossible to draw investors and migrants to this region, unbelievably vast but not so friendly from the point of weather and terrain. If the scenario for the re-colonization of Siberia, including its easternmost parts, is not written in Moscow and executed under its aegis, there surely will appear other scenarios compiled in other world capitals. It is well known that nature abhors vacuums. [return to Contents] #32 Moscow Times October 20, 2011 Trade Pact Draws Kiev Closer to Russia By Anatoly Medetsky Most former Soviet republics have signed a free-trade agreement that looks to increase mutual trade, especially between Russia and Ukraine, by removing some import and export duties. Eight members of the Commonwealth of Independent States, a loose group of 11 former Soviet republics, agreed to the deal at the meeting of their prime ministers in St. Petersburg that ended late Tuesday. Ukraine has backed the pact, pulling it closer to Russia, after fraying ties with the European Union by prosecuting former Prime Minister Yulia Tymoshenko, a political rival of its President Viktor Yanukovych. "We are mutually opening the markets for our goods," Prime Minister Vladimir Putin said. "It means that goods will come to our markets at lower prices. "This, in turn, means easier conditions for creating new cooperating enterprises. All this, no doubt ... increases the competitiveness of our economies." The members of the free-trade space are not planning to publish the full agreement or specify what goods will enjoy exemptions from duties "as yet," Putin's spokesman Dmitry Peskov said Wednesday. But the prime ministers broadly agreed on the goods, he said. The other signatories of the free-trade deal include Belarus and Kazakhstan, which had already joined a customs union with Russia, a tighter group with no customs clearance at their internal borders. Armenia, Moldova, Kyrgyzstan and Tajikistan comprise the rest of the new free-trade bloc that could start functioning next year, if ratified by the parliaments of the eight countries. While total trade among the commonwealth members reached $134 billion in the first half of this year, business between Russia and the rest of the group accounts for almost half of that number. Of the $60 billion in trade between Russia and the other 10 commonwealth members, $25 billion worth of goods traveled between Russia and Ukraine, according to the Federal Customs Service. Russia and Ukraine are the main beneficiaries of the free-trade deal, said Volodymyr Fesenko, director of the Kiev think tank Penta. Ukraine pushed the hardest of all the signatories for the agreement, he said. For Kiev, improving economic ties both with the European Union and Russia was an alluring goal, he said. Now that Kiev received a battering at the hands of the EU and other Western governments for its treatment of Tymoshenko, Russia is making a show of being an accomodating partner, Fesenko said. "There's a contrast effect to Ukraine's relations with the European Union," he said. Russia's longer-term goal remains to convince Ukraine to join the customs union, a prospect that Ukraine insisted would contradict its obligations as member of the World Trade Organization, the global trade arbiter, Fesenko said. Ukraine's Prime Minister Mykola Azarov, however, said Wednesday that he ordered the government to consider the possibility of observing the technical standards of the customs union. Vladimir Zharikhin, deputy director of the CIS Institute, a think tank that studies the commonwealth, described the free-trade zone as an "anteroom" for the customs union. The free-trade agreement complies with WTO rules, Putin said. In addition to Ukraine, the other WTO members of the free-trade agreement are Moldova, Kyrgyzstan and Armenia. Azarov said Tuesday that the agreement stipulates a time frame to remove all import and export duties within the free-trade space over time. Azerbaijan, Turkmenistan and Uzbekistan will consider joining the free-trade agreement before the end of the year, Putin said. [return to Contents] #33 Izvestia October 20, 2011 EXCUSE FOUND Both Ukraine and the European Union were glad to drop the pretense of rapprochement Author: Kirill Zubkov YULIA TIMOSHENKO'S TRIAL AND VERDICT PROVIDED AN EXCUSE TO STOP THE PRETENSE IN THE UKRAINIAN-EU RELATIONS European Commission's spokeswoman Pia Ahrenkilde-Hansen proclaimed the visit of Victor Yanukovich to Brussels postponed. "Pending a better moment in the bilateral relations between the European Union and Ukraine," she said. It was on this visit to Brussels that Yanukovich expected to finalize the agreement on association between the European Union and Ukraine. There is no saying now when the agreement might be signed, which appears to be just fine by official Kiev. "If Europe does not think that it is ready for the signing yet, let us put it off then," said Yanukovich. The president of Ukraine added, "There ought to be no connection between Ukrainian integration into the European Union and Timoshenko's criminal trial." Denis Kiryukhin of the Center of Political Studies and Conflicts (Kiev) said that completion of Timoshenko's trial last week did provide the European Union and Ukraine with an excuse to curtail contacts. According to the expert, this turn of events promoted the interests of both involved parties. Kiryukhin said, "What with the crisis looming so close, the European Union cannot afford the luxury of rapprochement with Ukraine. The visa-free regime specified by the agreement on association would have meant enormous labor immigration from Ukraine to Europe. Unable to cope with the unemployment that it already has to handle, the European labor market would have collapsed." The expert said that Timoshenko's trial became truly a Godsend for the European Union and gave it an excuse to curtail contacts with Kiev. "The European Union never uttered a word when charges were pressed against Timoshenko in the first place. When the sentence was passed, however, it all but declared Yanukovich a persona non grata," said Kiryukhin. Vladimir Zharikhin of the Institute of CIS Countries pointed out in his turn that rapprochement with Europe was the last thing Ukraine really needed at this point. "What has been happening between Ukraine and the European Union all these years might be termed as a stationary run. On the part of the former in the direction of the latter, that is. Yanukovich and his team know better than wish for genuine rapprochement with the European Union and the West in general. They cannot help remembering what happened to Pavel Lazarenko," said Zharikhin. Ukrainian ex-premier Lazarenko is under house arrest in the United States, in line with the ruling passed in 2006 in connection with illegal transactions from Ukraine to the United States. Yanukovich knows therefore that rapprochement with the European Union will compromise safety of his and his closest associates' assets. As for Brussels, it went through the motions of encouraging Ukrainian integration only in order to distract Kiev from betterment of its relations with Russia. Once Yanukovich became the president and the Orange Coalition finally crumbled, the need for pretense disappeared altogether. [return to Contents] #34 RIA Novosti October 20, 2011 Endgame in Ukraine By Fyodor Lukyanov Fyodor Lukyanov is Editor-in-Chief of the Russia in Global Affairs journal the most authoritative source of expertise on Russian foreign policy and global developments. The dramatic endgame has begun in Ukraine. As the Russian and Ukrainian presidents were meeting in Donetsk, the EU withdrew its invitation to Viktor Yanukovych to visit Brussels. The Ukrainian president has hardened his stance on jailed former prime minister Yulia Tymoshenko; the EU is unsure about signing a free trade agreement with Ukraine in December; and Dmitry Medvedev has said that it's not all about gas there are also other values at stake. But in all this complexity, some clarity has been achieved. At the very least, we know now that we are witnessing genuine and intense competition for Kiev, which has a choice between signing a free trade and association agreement with the EU and joining the three-nation Customs Union led by Russia, which has aspirations of expanding it into a Eurasian Union. Like it or not, Ukraine now finds itself in a zero-sum game. The rivalry over Kiev has escalated quite unexpectedly due to the insistent desire of the Ukrainian authorities or rather its industrial and energy lobbies to review the price of Russian gas. Kiev's position is neither consistent nor well thought-out, but rather a chaotic sequence of threats and promises that suggests the absence of a clear policy. Its goal, however, is clear, and the trial of Yulia Tymoshenko, who signed gas contracts with Russia as prime minister, is the means of achieving it. The harsh sentence she received has not only complicated Ukraine's relations with Moscow and Brussels, it has created a situation in which the impossible has become possible. The European Union is gripped by indecision. According to the values, rights and liberties it claims to uphold, it should cool relations with Ukraine. And indeed, the EU responded harshly to Tymoshenko's sentence. But considering Russia's integration ambitions, which Vladimir Putin has reaffirmed in his article on a Eurasian Union, Brussels fears that Kiev may turn east. Ukraine is consciously stoking these fears. Ukrainian Deputy Prime Minister Serhiy Tihipko has said openly that Ukraine will turn its attention elsewhere if Europe does not show it respect. Such statements should not be taken seriously, as the situation is far more complicated than that, but the fact that we are hearing such things from Ukrainian officials is surprising enough; usually Ukraine is trying to scare Russia with the prospect of its integration with the West. European officials, when asked why this glaring violation of democratic norms an opposition leader sentenced to seven years in prison has not stopped Europe from cooperating with Ukraine, they roll their eyes and say something along the lines of "you cannot punish the nation for the mistakes of its leaders." But some admit that the EU is driven by a desire to prevent Russia from benefitting from any deterioration in EU-Ukraine relations. This stance conflicts with the ideology of united Europe, but clearly this is of secondary importance at the moment. Moscow saw an anti-Russian subtext in the Tymoshenko trial and initially criticized the verdict. But in Donetsk, President Medvedev was pointedly neutral and avoided saying anything concrete. After all, Russia stands to gain if the Tymoshenko trial, whatever its objective, drives a wedge between Ukraine and the EU. The Kremlin is doing its best not to lose this slim chance. But can the Ukrainian authorities make a final decision? The answer was "no" until recently. Irrespective of the leadership's desire, Ukrainian society is objectively divided and sharp turns invariably provoke an outcry in one part of the nation or the other. Psychologically, Ukraine has become accustomed to being "the eternal bride" who is in no hurry to take the wedding vows. Even the election of a seemingly pro-Russian president, Viktor Yanukovych, was no guarantee that Russian-Ukrainian relations would improve dramatically. Furthermore, Ukrainian and Russian oligarchs have completely different financial and industrial interests. For these reasons, it is widely believed that joining a Russia-led association would provoke a political crisis in Ukraine. But the logic of Ukrainian politics has added several new elements to this picture. Yanukovych decided to go for broke, disregarding taboos of Ukrainian and post-Soviet politics. The Ukrainian taboos are rooted in the country's political culture, according to which confrontation should never reach its logical conclusion, with the sides retreating to their initial positions in order to start bargaining. But this was not the case with Tymoshenko. According to unspoken post-Soviet taboos, no political leaders have been tried or, worse still, imprisoned, although some have been toppled and forced into an exile. (Tymoshenko's mentor, former Prime Minister Pavlo Lazarenko, was imprisoned, but in the United States.) Tymoshenko's trial has created a precedent that does not please post-Soviet leaders one bit. By going for broke, Yanukovych has blocked his own escape route. He must either convince the nation that the rules of the game have changed, and they are dictated by the current authorities, or push back against the powerful internal resistance, which, combined with external factors, could lead to destructive results. In other words, the question is whether the second most important post-Soviet state can establish the same political system found in most post-Soviet states, i.e. authoritarian and centralized. It seemed until recently that this was impossible due to the high degree of diversity of Ukrainian society. But Yanukovych's Party of Regions has rather easily taken the political reins in the less than two years of its rule, encountering only weak resistance. Opposition forces have only their own leaders to blame: the slapstick comedy in which Viktor Yushchenko and Yulia Tymoshenko starred when they were in power has all but extinguished Ukrainians' desire to be politically active. We will know the outcome of this complex game between Kiev, Moscow and Brussels quite soon, and it will determine a great many things in Greater Euro
http://www.wikileaks.org/gifiles/docs/41/4108011_-os-2011-190-johnson-s-russia-list-.html
CC-MAIN-2014-52
refinedweb
27,883
59.23
A have been accessed by client programmers? This is also true with methods that are only part of the implementation of a class, and not meant to be used directly by the client programmer. But what if the library creator wants to rip out an old implementation and put in a new one? Changing any of those members might break a client, protected, “friendly” (which has no keyword),’s still the question of how the components are bundled together into a cohesive library unit. This is controlled with the package keyword in Java, and the access specifiers are affected by whether a class is in the same package or in a separate package. So to begin this chapter, you’ll learn how library components are placed into packages. Then you’ll be able to understand the complete meaning of the access specifiers. import java.util.*; This brings in the entire utility library that’s part of the standard Java distribution. Since, for example, the class ArrayList is in java.util, you can now either specify the full name java.util.ArrayList (which you can do without the import statement), or you can simply say ArrayList (because of the import). If you want to bring in a single class, you can name that class in the import statement import java.util.ArrayList; Now you can use ArrayList this book. However, if you’re planning to create libraries or programs that are friendly to other Java programs on the same machine,). There can be only one public class in each compilation unit, otherwise Java’s jar archiver). The Java interpreter is responsible for finding, loading, and interpreting these files[32]. (if you use a package statement, it must appear as the first noncomment package names one way that Java references the problem of clutter; you’ll see the other way later when the jar utility is introduced. Collecting the package files into a single subdirectory, sometimes by the installation program that installs Java or a Java-based tool on your or possibly something else, 2 so the entire package name is lowercase.) I can further subdivide this by deciding that I want to create a library named simple, so I’ll end up with a package name: package com.bruceeckel.simple; Now this package name can be used as an umbrella name space for the following two files: //: com:bruceeckel:simple:Vector.java // Creating a package. package com.bruceeckel.simple; public class Vector { public Vector() { System.out.println( "com.bruceeckel.util.Vector"); } } ///:~ When you create your own packages, you’ll discover that the package statement must be the first noncomment code in the file. The second file looks much the same: //: com:bruceeckel:simple:List.java // Creating a package. package com.bruceeckel.simple; public class List { public List() { System.out.println( "com.bruceeckel.util.List"); } } ///:~ Both of these files are placed in the subdirectory on my system: C:\DOC\JavaT\com\bruceeckel\simple If you walk back through this, you can see the package name com.bruceeckel.simple,: //: c05:LibTest.java // Uses the library. import com.bruceeckel.simple.*; public class LibTest { public static void main(String[] args) { Vector v = new Vector(); List l = new List(); } } ///:~ When the compiler encounters the import statement, it begins searching at the directories specified by CLASSPATH, looking for subdirectory com\bruceeckel\simple, then seeking the compiled files of the appropriate names (Vector.class for Vector and List.class for List). Note that both the classes and the desired methods in Vector and List must be public. Setting the CLASSPATH has been such a trial for beginning Java users (it was for me, when I started) that Sun made the JDK in Java 2 a bit smarter. You’ll find that, when you install it, even if you don’t set a CLASSPATH you’ll be able to compile and run basic Java programs. To compile and run the source-code package for this book (available on the CD ROM packaged with this book, or at), however, you will need to make some modifications to your CLASSPATH (these are explained in the source-code package). What happens if two libraries are imported via * and they include the same names? For example, suppose a program does this: import com.bruceeckel.simple.*; import java.util.*; Since java.util.* also contains a Vector class, this causes a potential collision. However, as long as you don’t write the code that actually causes the collision,. With this knowledge, you can now create your own libraries of tools to reduce or eliminate duplicate code. Consider, for example, creating an alias for System.out.println( ) to reduce typing. This can be part of a package called tools: //: com:bruceeckel:tools:P.java // The P.rint & P.rintln shorthand. package com.bruceeckel.tools; public class P { public static void rint(String s) { System.out.print(s); } public static void rintln(String s) { System.out.println(s); } } ///:~ You can use this shorthand to print a String: //: c05:ToolTest.java // Uses the tools library. import com.bruceeckel.tools.*; public class ToolTest { public static void main(String[] args) { P.rintln("Available from now on!"); P.rintln("" + 100); // Force it to be a String P.rintln("" + 100L); P.rintln("" + 3.14159); } } ///:~ Notice that all objects can easily be forced into String representations by putting them in a String expression; in the above case, starting the expression with an empty String does the trick. But this brings up an interesting observation. If you call System.out.println(100), it works without casting it to a String. With some extra overloading, you can get the P class to do this as well (this is an exercise at the end of this chapter). So from now on, whenever you come up with a useful new utility, you can add it to the tools directory. (Or to your own personal util or tools directory.) in: //: com:bruceeckel:tools:debug 10, you’ll learn about a more sophisticated tool for dealing with errors called exception handling, but the perr( ) method will work fine in the meantime. The output is printed to the console standard error stream by writing to System.err. When you want to use this class, you add a line in your program: import com.bruceeckel.tools.debug.*; To remove the assertions so you can ship the code, a second Assert class is created, but in a different package: //: com:bruceeckel:tools assertions. Here’s an example: //: c05:TestAssert.java // Demonstrating the assertion tool. //. When used, the Java access specifiers public, protected, and private are placed in front of each definition for each member in your class, whether it’s a field you own should have friendly access to other code. The class controls which code has access to its members. There’s no magic way to “break in.” Code from another package can’t show up and say, “Hi, I’m a friend of Bob’s!” and expect to see the protected, friendly,,: //: c05:Dinner.java // Uses the library. import c05.dessert.*; public class Dinner { public Dinner() { System.out.println("Dinner constructor"); } public static void main(String[] args) { Cookie x = new Cookie(); //! x.bite(); // Can't access } } ///:~ you can create a Cookie object, since its constructor is public and the class is public. (We’ll look more at the concept of a public class later.) However, the bite( ) member is inaccessible inside Dinner.java since bite( ) is friendly only within package dessert. You might be surprised to discover that the following code compiles, even though it would appear that it breaks the rules: //: c05:Cake.java // Accesses a class in a // separate compilation unit. class Cake { public static void main(String[] args) { Pie x = new Pie(); x ‘.’ in your CLASSPATH in order for the files to compile.). The private keyword means that often provides an adequate amount of hiding; remember, a “friendly” member is inaccessible to the user of the package. This is nice, since the default access is the one that you normally use (and the one that you’ll get if you forget to add any access control). example above, you cannot create a Sundae object via its constructor; instead you must call the makeASundae( ) method to do it for you[33]. Any method that you’re certain is only a “helper” method for that class can be made private, to ensure that you don’t accidentally use it elsewhere in the package and thus prohibit yourself from changing or removing the method. Making a method private guarantees that you retain this option. The same is true for a private field inside a class. Unless you must expose the underlying implementation (which is a much rarer situation than you might think), you should make all fields private. However, just because a reference to an object is private inside a class doesn't mean that some other object can't have a public reference to the same object. (See Appendix A for issues about aliasing.) The protected access specifier requires a jump ahead to understand. First, you should be aware that you don’t need to understand this section to continue through this book up through inheritance (Chapter 6)., the following class cannot access the “friendly” member: //: c05:ChocolateChip.java // Can't access friendly member // in another class. import c05.dessert.*; public class ChocolateChip extends Cookie { public ChocolateChip() { System.out.println( "ChocolateChip constructor"); } public static void main(String[] args) { ChocolateChip x = new ChocolateChip(); //! x.bite(); // Can't access bite } } ///:~ One of the interesting things about inheritance is that if a method bite( ) exists in class Cookie, then it also exists in any class inherited from Cookie. But since bite( ) bite() { System.out.println("bite"); } } then bite( ) still has “friendly” access within package dessert, but it is also accessible to anyone inheriting from Cookie. However, it is not public. Access control is often referred to as implementation hiding. Wrapping data and methods within classes in combination with implementation hiding is often called encapsulation[34]. The result is a data type with characteristics and behaviors. Access control puts boundaries within a data type for two important reasons. The first is to establish what the client programmers can and can’t use. You can build your internal mechanisms into the structure without worrying that the client programmers will accidentally treat the internals as part of the interface that they should be using. This feeds directly into the second reason, which is to separate the interface from the implementation. If the structure is used in a set of programs, but client programmers can’t do anything but send messages to the public interface, then you can change anything that’s not public (e.g., “friendly,” protected, or private) without requiring modifications to client code. We’re now in the world of object-oriented programming, where a class is actually describing “a class of objects,” as you would describe a class of fishes or a class of birds. Any object belonging to this class will share these characteristics and behaviors. The class is a description of the way all objects of this type will look and act. In the original OOP language, Simula-67, the keyword class was used to describe a new data type. The same keyword has been used for most object-oriented languages. This is the focal point of the whole language: the creation of new data types that are more than just boxes containing data and methods. The class is the fundamental OOP concept in Java. It is one of the keywords that will not be set in bold in this book: public class X { public void pub1( ) { /* . . . */ } public void pub2( ) { /* . . . */ } public void pub3( ) { /* . . . */ } private void priv1( ) { /* . . . */ } private void priv2( ) { /* . . . */ } private void priv3( ) { /* . . . */ } private int i; // . . . } This will make it only partially easier to read because the interface and implementation are still mixed together. That is, you still see the source code—the implementation—because it’s right there in the class. In addition, the comment documentation supported by javadoc (described in Chapter 2) lessens the importance of code readability by the client programmer., browsers should be an expected part of any good Java development tool., there’s an extra set of constraints:[35].[36]. Here is covered in Thinking in Patterns with Java, downloadable at.. Without rules, client programmers can do anything they want with all the members of a class, even if you might prefer they don’t directly manipulate some of the members. Everything’s naked to the world. This chapter looked at how classes are built to form libraries; first, the way a group of classes is packaged within a library, and second, the way the class controls access to its It is estimated that a C programming project begins to break down somewhere between 50K and 100K lines of code because C has a single “name space” so names begin to collide, causing an extra management overhead. In Java, the package keyword, the package naming scheme, and the import keyword give you complete control over names, so the issue of name collision is easily avoided. There are two reasons for controlling access to members. The first is to keep users’ hands off tools that they shouldn’t touch; tools that are necessary for the internal machinations of the data type, but not part of the interface that users need to solve their particular problems. So making methods and fields private is a service to users because they can easily see what’s important to them and what they can ignore. It simplifies their understanding of the class. The second and most important reason for access control is to allow the library designer to change the internal workings of the class without worrying about how it will affect the client programmer. You might build a class one way at first, and then discover that restructuring your code will provide much greater speed. If the interface and implementation are clearly separated and protected, you can accomplish this without forcing the user to rewrite their code. Access specifiers in Java give valuable control to the creator of a class. The users of the class can clearly see exactly what they can use and what to ignore. More important, though, is the ability to ensure that no user becomes dependent on any part of the underlying implementation of a class. If you know this as the creator of the class, you can change the underlying implementation with the knowledge that no client programmer will be affected by the changes because they can’t access that part of the class. When you have the ability to change the underlying implementation, you can not only improve your design later, but you also have the freedom to make mistakes. No matter how carefully you plan and design you’ll make mistakes. Knowing that it’s relatively safe to make these mistakes means you’ll be more experimental, you’ll learn faster, and you’ll finish your project sooner. The public interface to a class is what the user does see, so that is the most important part of the class to get “right” during analysis and design. Even that allows you some leeway for change. If you don’t get the interface right the first time, you can add more methods, as long as you don’t remove any that client programmers have already used in their code. Solutions to selected exercises can be found in the electronic document The Thinking in Java Annotated Solution Guide, available for a small fee from. ///: c05:local:PackagedClass.java package c05.local; class PackagedClass { public PackagedClass() { System.out.println( "Creating a packaged class"); } } ///:~ Then create the following file in a directory other than c05: ///: c05:foreign:Foreign.java package c05.foreign; import c05.local.*; public class Foreign { public static void main (String[] args) { PackagedClass pc = new PackagedClass(); } } ///:~ Explain why the compiler generates an error. Would making the Foreign class part of the c05.local package change anything? [32] There’s nothing in Java that forces the use of an interpreter. There exist native-code Java compilers that generate a single executable file. [33] There’s another effect in this case: Since the default constructor is the only one defined, and it’s private, it will prevent inheritance of this class. (A subject that will be introduced in Chapter 6.) [35] Actually, an inner class can be private or protected, but that’s a special case. These will be introduced in Chapter 7.
http://www.cs.uregina.ca/Links/class-info/115/ThinkingInJava/Chapter05.html
CC-MAIN-2017-43
refinedweb
2,746
64.2
Ever since I realized many years ago, that this doesn't produce an error by default, (in gcc at least) I've always wondered why? I understand that you can issue compiler flags to produce a warning, but shouldn't it always be an error? Why does it make sense for a non-void function not returning value to be valid? An example as requested in the comments: #include <stdio.h> int stringSize() { } int main() { char cstring[5]; printf( "the last char is: %c\n", cstring[stringSize()-1] ); return 0; } C99 and C++ standards don't require functions to return a value. The missing return statement in a value-returning function will be defined (to return 0) only in the main function. The rationale includes that checking if every code path returns a value is quite difficult, and a return value could be set with embedded assembler or other tricky methods. § 6.6.3/2 Flowing off the end of a function [...] results in undefined behavior in a value-returning function. § 3.6.1/5 If control reaches the end of mainwithout encountering a returnstatement, the effect is that of executing return 0; Note that the behaviour described in C++ 6.6.3/2 is not the same in C. gcc will give you a warning if you call it with -Wreturn-type option. -Wreturn-type. This warning is enabled by -Wall. Just as a curiosity, look what this code does: #include <iostream> int foo() { int a = 5; int b = a + 1; } int main() { std::cout << foo() << std::endl; } // may print 6 This code has formally undefined behaviour, and in practice it's calling convention and architecture dependent. On one particular system, with one particular compiler, the return value is the result of last expression evaluation, stored in the eax register of that system's processor.
https://codedump.io/share/GGOAvlJS3IRI/1/why-does-flowing-off-the-end-of-a-non-void-function-without-returning-a-value-not-produce-a-compiler-error
CC-MAIN-2018-22
refinedweb
306
61.06
Enabling Modelling 2.0 With Xtext Join the DZone community and get the full member experience.Join For Free With the Eclipse Helios release just around the corner, Xtext will be providing their 1.0 release of their highly successful framework for creating DSLs. I spoke with Sven Efftinge to find out more about this release. DZone: First, just in case anyone doesn't know about Xtext, could you explain it? Sven Efftinge: Of course. Xtext is what we call a language development framework. That is an open set of libraries and domain-specific languages (DSLs) used to implement a complete infrastructure for any kind of language, whether it's regular programming languages like Java or DSLs. It covers all aspects of a compiler or interpreter, such as parsing, validation and linking, and it provides you with a full-blown Eclipse-based IDE for your language. Xtext is an open-source project developed at Eclipse.org. It is driven by itemis, which is a strategic member at Eclipse. I have the pleasure to lead a fantastic team of highly motivated and skilled developers, and itemis is funding us to work almost full time on Xtext. DZone: So what are the highlight features of Xtext 1.0? Sven: Since the last release, we've implemented over 80 new features and fixed several hundreds of bugs. Besides greatly improved performance especially within the linker, we have introduced the possibility to bind and integrate with any JVM language. That means it is a matter of minutes to add references to Java elements such as types, fields, methods and even annotations. In the IDE this results in a tight integration with Eclipse's Java Development Tools (JDT) while at runtime Xtext uses Java reflection to look up referenced Java elements. That's pretty cool and something a lot of users now make use of. The most important addition in Xtext 1.0 is the indexing infrastructure. Based on a description of your project structure Xtext indexes all contained files and remembers the names and types of your elements as well as any cross references. As a result Xtext now lets you do namespace based linking of any element in any file in your project. In the IDE this information is used to provide a lot of new cool features, like a global "Open Model Element" dialog, where you can search for elements similar to the "Open Type" dialog in JDT. In fact, by default Xtext will leverage the Java classpath mechanism to describe your project structure. That is you can have your Xtext files in jars, class folders or even OSGi bundles and Xtext will reuse the Java classpath configuration to determine the boundaries of your project. Anyway, leveraging JDT is just a convenient default, you can use the index without JDT. DZone: What are the limitations of Xtext? Sven: You can implement almost any kind of programming language or DSL with Xtext. There is one exception, that is if you need to use so called 'Semantic Predicates' which is a rather complicated thing I don't think is worth being explained here. Very few languages really need this concept. However the prominent example is C/C++. We want to look into that topic for the next release. DZone: I see that Itemis are doing iPhone apps now. Is Xtext a basis for this? Sven: Yes, partly. We have developed a small domain-specific language to develop a very common type of data-driven mobile application. If you search the different app stores it is surprising how often you find this kind of application. With 'Applause', which is the name of that DSL, you can very easily describe such applications and generate an iPhone as well as an Android app from it. It's pretty impressive. In addition to that we do a lot of different things on modern mobile platforms. Mostly we use this new platform as a great new client technology for enterprise software systems. We already did a couple of cool projects and are currently working on a big one. DZone: We did a poll recently and it seems that about 66% of developers who answered, don't use model driven development. Can you convince them otherwise? Sven: I think the term model-driven is used in very different ways. I myself don't like riding that old horse anymore, because there is too much dogmatic stuff going on with it. Especially the ideas behind MDA seem very strange and impractical to me and the technologies and languages coming from the OMG are complicated and also not very well designed. I never use UML for programming nor do I use OCL or QVT. I also try to to avoid the typical modeling terminology but instead use simple and existing terminology from general programming and the language community. I try to focus on writing good software because that is what all this should be used for in the end. What I can say is, that being able to write languages and code generators or interpreters is a very valuable addition to every developer's toolbox. With Xtext we try to make these tasks as easy and as much fun as possible. And I think we made some progress here :-) Obviously, as part of Eclipse Modeling (EMP) we cannot and don't want to completely omit the term "Modeling", but I think that not only Xtext but also a lot of other technologies at EMP are very helpful and pragmatically designed technologies. They actually don't have that much to do with the general perception of "Modeling". That is why I call what we do "Modeling 2.0" from time to time. I hope this will give people a hint, that it doesn't fit into the old idea of "Modeling". DZone: So for anyone who is convinced, can you give us an easy three step plan to getting started with modelling? Sven: You mean Modeling 2.0? :-) There are two different very cool things you can do with EMF, which is the core framework at EMP. You can use EMF in any software system at runtime as your domain model technology, similar to how people use JavaBeans. EMF is just much nicer, has much richer semantics and comes with a lot of great additional technology. For instance CDO can really be seen as a superior replacement for any object-relational database mapper. It is highly scalable, flexible and gives you the deep semantics of EMF. If you are interested in that I suggest to watch the webinar on CDO. Xtext on the other hand uses EMF as the in-memory representation of languages. These models are usually called Abstract Syntax Trees (AST) but in Xtext they are implemented using EMF. These in- memory EMF models repesent the main data the different aspects of a language infrastructure work with and it is and was a very good decision to leverage EMF here. It turned out that the semantics and features EMF provides are a fantastic match to what we needed in Xtext. Also by implementing EMF API any EMF client can transparently use Xtext under the hood. Which for instance allows to combine Xtext with other existing EMF-based tools such as the Graphical Modeling Framework (GMF). If you want to learn how implementing programming languages feels like in 2010, I recommend to have a look at our website, watch the webinar or read the introductory examples in the documentation. You'll be surprised how easy language development can be. DZone: It seems that a lot of the focus for this release has been to improve the editor support, such as content assist and other useful editor features. Can you give us a rundown of these features? Which was the most difficult to implement? Sven: Yes, we have done a lot of UI features. An Xtext language IDE should really feel like Eclipse's JDT and the framework should come with great default semantics as well as easy to use API for all the different aspects. During the last year we vastly improved content assist, added support for quick fixes, rewrote the whole validation framework as well as the scoping framework. The editor now supports folding, bracket matching, and auto edit. We have support for semantic highlighting and quick outline. I'm sure I missed a couple of UI features, but we have a very nice new & noteworthy page which not only contains descriptions and screenshots but also small screencasts whenever appropriate. DZone: The index infrastructure seems to have some additions too. Could you explain these changes and their benefits? Sven: The index infrastructure was a tough one. Actually we implemented it three times before we got it right. For the last implementation Sebastian and I closed any communication tools and locked up the doors for three weeks, to get it done. We are very happy with the result, we like the core abstractions a lot, and the framework has become an important basis for other cool features we have implemented later. A very hard thing to solve was the computation of the transitive hull of all affected resources. Imagine you have a broken reference to something called 'MyBookingService' because in the declaration you misspelled the name ('MyBokingService'). In that case you of course get an error marker that the reference can not be resolved. If you now open the declaration and fix the typo, we need to know that the previously broken reference can be fixed but of course we cannot rebuild the whole workspace to find any possible occurrences. So we remember which elements have asked for which names and inform them as soon as such a name has changed. As a language designer you don't have to deal with this complex problem, the index infrastructure solves this for you. Another very cool thing is the "Dirty Editor State" support. That means, that the builder state is shadowed by the state of all editors containing unsaved changes. JDT tries to do the same but it doesn't work as reliable as in Xtext. :-) DZone: Also, the performance figures look impressive - linking is 40 times faster, and less builders invoked! How did you get those improvements? Sven: Actually we hadn't found the time to do comprehensive profiling for the previous 0.7 release. So there were a lot of unused opportunities to improve performance. The most compelling performance gain was done in the linker phase, which previously was also the most expensive phase. Now it's on par with parsing which is very fast. We accomplished this by introducing a generic caching utility for EMF models, which is based on EMF's adapters. The builder framework was introduced in M4 / M5. We optimized it in M6. I can proudly say, that scalability of Xtext 1.0 is in a pretty good shape. Opinions expressed by DZone contributors are their own.
https://dzone.com/articles/xtext
CC-MAIN-2021-17
refinedweb
1,820
63.49
Build. However, the source code is available on GitHub and I strongly recommend that you take a look. Introduction Express is one of the best frameworks for Node. It has great support and a bunch of helpful features. There are a lot of great articles out there, which cover all of the basics. However, this time I want to dig in a little bit deeper and share my workflow for creating a complete website. In general, this article is not only for Express, but for using it in combination with some other great tools that are available for Node developers. I assume that you are familiar with Nodejs, have it installed on your system, and that you have probably built some applications with it already. At the heart of Express is Connect. This is a middleware framework, which comes with a lot of useful stuff. If you're wondering what exactly a middleware is, here is a quick example: var connect = require('connect'), http = require('http'); var app = connect() .use(function(req, res, next) { console.log("That's my first middleware"); next(); }) .use(function(req, res, next) { console.log("That's my second middleware"); next(); }) .use(function(req, res, next) { console.log("end"); res.end("hello world"); }); http.createServer(app).listen(3000); Middleware is basically a function which accepts request and response objects and a next function. Each middleware can decide to respond by using a response object or pass the flow to the next function by calling the next callback. In the example above, if you remove the next() method call in the second middleware, the hello world string will never be sent to the browser. In general, that's how Express works. There are some predefined middlewares, which of course, save you a lot of time. Like for example, Body parser which parses request bodies and supports application/json, application/x-www-form-urlencoded, and multipart/form-data. Or the Cookie parser, which parses cookie headers and populates req.cookies with an object keyed by the cookie's name. Express actually wraps Connect and adds some new functionality around it. Like for example, routing logic, which makes the process much smoother. Here's an example of handling a GET request: app.get('/hello.txt', function(req, res){ var body = 'Hello World'; res.setHeader('Content-Type', 'text/plain'); res.setHeader('Content-Length', body.length); res.end(body); }); Setup There are two ways to setup Express. The first one is by placing it in your package.json file and running npm install (there's a joke that npm means no problem man :)). { "name": "MyWebSite", "description": "My website", "version": "0.0.1", "dependencies": { "express": "3.x" } } The framework's code will be placed in node_modules and you will be able to create an instance of it. However, I prefer an alternative option, by using the command line tool. Just install Express globally with npm install -g express. By doing this, you now have a brand new CLI instrument. For example if you run: express --sessions --css less --hogan app Express will create an application skeleton with a few things already configured for you. Here are the usage options for the express(1) command: Usage: express [options] Options: -h, --help output usage information -V, --version output the version number -s, --sessions add session support -e, --ejs add ejs engine support (defaults to jade) -J, --jshtml add jshtml engine support (defaults to jade) -H, --hogan add hogan.js engine support -c, --css add stylesheet support (less|stylus) (defaults to plain css) -f, --force force on non-empty directory As you can see, there are just a few options available, but for me they are enough. Normally I'm using less as the CSS preprocessor and hogan as the templating engine. In this example, we will also need session support, so the --sessions argument solves that problem. When the above command finishes, our project looks like the following: /public /images /javascripts /stylesheets /routes /index.js /user.js /views /index.hjs /app.js /package.json If you check out the package.json file, you will see that all the dependencies which we need are added here. Although they haven't been installed yet. To do so, just run npm install and then a node_modules folder will pop up. I realize that the above approach is not always appropriate. You may want to place your route handlers in another directory or something something similar. But, as you'll see in the next few chapters, I'll make changes to the already generated structure, which is pretty easy to do. So you should just think of the express(1) command as a boilerplate generator. FastDelivery For this tutorial, I designed a simple website of a fake company named FastDelivery. Here's a screenshot of the complete design: At the end of this tutorial, we will have a complete web application, with a working control panel. The idea is to manage every part of the site in separate restricted areas. The layout was created in Photoshop and sliced to CSS(less) and HTML(hogan) files. Now, I'm not going to be covering the slicing process, because it's not the subject of this article, but if you have any questions regarding this, don't hesitate to ask. After the slicing, we have the following files and app structure: Here is a list of the site's elements that we are going to administrate: - Home (the banner in the middle - title and text) - Blog (adding, removing and editing of articles) - Services page - Careers page - Contacts page Configuration There are a few things that we have to do before we can start the real implementation. The configuration setup is one of them. Let's imagine that our little site should be deployed to three different places - a local server, a staging server and a production server. Of course the settings for every environment are different and we should implement a mechanism which is flexible enough. As you know, every node script is run as a console program. So, we can easily send command line arguments which will define the current environment. I wrapped that part in a separate module in order to write a test for it later. Here is the /config/index.js file: var config = { local: { mode: 'local', port: 3000 }, staging: { mode: 'staging', port: 4000 }, production: { mode: 'production', port: 5000 } } module.exports = function(mode) { return config[mode || process.argv[2] || 'local'] || config.local; } There are only two settings (for now) - mode and port. As you may guess, the application uses different ports for the different servers. That's why we have to update the entry point of the site, in app.js. ... var config = require('./config')(); ... http.createServer(app).listen(config.port, function(){ console.log('Express server listening on port ' + config.port); }); To switch between the configurations, just add the environment at the end. For example: node app.js staging Will produce: Express server listening on port 4000 Now we have all our settings in one place and they are easily manageable. Tests I'm a big fan of TDD. I'll try to cover all the base classes used in this article. Of course, having tests for absolutely everything will make this writing too long, but in general, that's how you should proceed when creating your own apps. One of my favorite frameworks for testing is jasmine. Of course it's available in the npm registry: npm install -g jasmine-node Let's create a tests directory which will hold our tests. The first thing that we are going to check is our configuration setup. The spec files must end with .spec.js, so the file should be called config.spec.js. describe("Configuration setup", function() { it("should load local configurations", function(next) { var config = require('../config')(); expect(config.mode).toBe('local'); next(); }); it("should load staging configurations", function(next) { var config = require('../config')('staging'); expect(config.mode).toBe('staging'); next(); }); it("should load production configurations", function(next) { var config = require('../config')('production'); expect(config.mode).toBe('production'); next(); }); }); Run jasmine-node ./tests and you should see the following: Finished in 0.008 seconds 3 tests, 6 assertions, 0 failures, 0 skipped This time, I wrote the implementation first and the test second. That's not exactly the TDD way of doing things, but over the next few chapters I'll do the opposite. I strongly recommend spending a good amount of time writing tests. There is nothing better than a fully tested application. A couple of years ago I realized something very important, which may help you to produce better programs. Each time you start writing a new class, a new module, or just a new piece of logic, ask yourself: How can I test this? The answer to this question will help you to code much more efficiently, create better APIs, and put everything into nicely separated blocks. You can't write tests for spaghetti code. For example, in the configuration file above ( /config/index.js) I added the possibility to send the mode in the module's constructor. You may wonder, why do I do that when the main idea is to get the mode from the command line arguments? It's simple ... because I needed to test it. Let's imagine that one month later I need to check something in a production configuration, but the node script is run with a staging parameter. I won't be able to make this change without that little improvement. That one previous little step now actually prevents problems in the future. Database Since we are building a dynamic website, we need a database to store our data in. I chose to use mongodb for this tutorial. Mongo is a NoSQL document database. The installation instructions can be found here and because I'm a Windows user, I followed the Windows installation instead. Once you finish with the installation, run the MongoDB daemon, which by default listens on port 27017. So, in theory, we should be able to connect to this port and communicate with the mongodb server. To do this from a node script, we need a mongodb module/driver. If you downloaded the source files for this tutorial, the module is already added in the package.json file. If not, just add "mongodb": "1.3.10" to your dependencies and run npm install. Next, we are going to write a test, which checks if there is a mongodb server running. /tests/mongodb.spec.js file: describe("MongoDB", function() { it("is there a server running", function(next) { var MongoClient = require('mongodb').MongoClient; MongoClient.connect('mongodb://127.0.0.1:27017/fastdelivery', function(err, db) { expect(err).toBe(null); next(); }); }); }); The callback in the .connect method of the mongodb client receives a db object. We will use it later to manage our data, which means that we need access to it inside our models. It's not a good idea to create a new MongoClient object every time when we have to make a request to the database. That's why I moved the running of the express server inside the callback of the connect function: MongoClient.connect('mongodb://127.0.0.1:27017/fastdelivery', function(err, db) { if(err) { console.log('Sorry, there is no mongo db server running.'); } else { var attachDB = function(req, res, next) { req.db = db; next(); }; http.createServer(app).listen(config.port, function(){ console.log('Express server listening on port ' + config.port); }); } }); Even better, since we have a configuration setup, it would be a good idea to place the mongodb host and port in there and then change the connect URL to: 'mongodb://' + config.mongo.host + ':' + config.mongo.port + '/fastdelivery' Pay close attention to the middleware: attachDB, which I added just before the call to the http.createServer function. Thanks to this little addition, we will populate a .db property of the request object. The good news is that we can attach several functions during the route definition. For example: app.get('/', attachDB, function(req, res, next) { ... }) So with that, Express calls attachDB beforehand to reach our route handler. Once this happens, the request object will have the .db property and we can use it to access the database. MVC We all know the MVC pattern. The question is how this applies to Express. More or less, it's a matter of interpretation. In the next few chapters I'll create modules, which act as a model, view and controller. Model The model is what will be handling the data that's in our application. It should have access to a db object, returned by MongoClient. Our model should also have a method for extending it, because we may want to create different types of models. For example, we might want a BlogModel or a ContactsModel. So we need to write a new spec: /tests/base.model.spec.js, in order to test these two model features. And remember, by defining these functionalities before we start coding the implementation, we can guarantee that our module will do only what we want it to do. var Model = require("../models/Base"), dbMockup = {}; describe("Models", function() { it("should create a new model", function(next) { var model = new Model(dbMockup); expect(model.db).toBeDefined(); expect(model.extend).toBeDefined(); next(); }); it("should be extendable", function(next) { var model = new Model(dbMockup); var OtherTypeOfModel = model.extend({ myCustomModelMethod: function() { } }); var model2 = new OtherTypeOfModel(dbMockup); expect(model2.db).toBeDefined(); expect(model2.myCustomModelMethod).toBeDefined(); next(); }) }); Instead of a real db object, I decided to pass a mockup object. That's because later, I may want to test something specific, which depends on information coming from the database. It will be much easier to define this data manually. The implementation of the extend method is a little bit tricky, because we have to change the prototype of module.exports, but still keep the original constructor. Thankfully, we have a nice test already written, which proves that our code works. A version which passes the above, looks like this: module.exports = function(db) { this.db = db; }; module.exports.prototype = { extend: function(properties) { var Child = module.exports; Child.prototype = module.exports.prototype; for(var key in properties) { Child.prototype[key] = properties[key]; } return Child; }, setDB: function(db) { this.db = db; }, collection: function() { if(this._collection) return this._collection; return this._collection = this.db.collection('fastdelivery-content'); } } Here, there are two helper methods. A setter for the db object and a getter for our database collection. View The view will render information to the screen. Essentially, the view is a class which sends a response to the browser. Express provides a short way to do this: res.render('index', { title: 'Express' }); The response object is a wrapper, which has a nice API, making our life easier. However, I'd prefer to create a module which will encapsulate this functionality. The default views directory will be changed to templates and a new one will be created, which will host the Base view class. This little change now requires another change. We should notify Express that our template files are now placed in another directory: app.set('views', __dirname + '/templates'); First, I'll define what I need, write the test, and after that, write the implementation. We need a module matching the following rules: - Its constructor should receive a response object and a template name. - It should have a rendermethod which accepts a data object. - It should be extendable. You may wonder why I'm extending the View class. Isn't it just calling the response.render method? Well in practice, there are cases in which you will want to send a different header or maybe manipulate the response object somehow. Like for example, serving JSON data: var data = {"developer": "Krasimir Tsonev"}; response.contentType('application/json'); response.send(JSON.stringify(data)); Instead of doing this every time, it would be nice to have an HTMLView class and a JSONView class. Or even an XMLView class for sending XML data to the browser. It's just better, if you build a large website, to wrap such functionalities instead of copy-pasting the same code over and over again. Here is the spec for the /views/Base.js: var View = require("../views/Base"); describe("Base view", function() { it("create and render new view", function(next) { var responseMockup = { render: function(template, data) { expect(data.myProperty).toBe('value'); expect(template).toBe('template-file'); next(); } } var v = new View(responseMockup, 'template-file'); v.render({myProperty: 'value'}); }); it("should be extendable", function(next) { var v = new View(); var OtherView = v.extend({ render: function(data) { expect(data.prop).toBe('yes'); next(); } }); var otherViewInstance = new OtherView(); expect(otherViewInstance.render).toBeDefined(); otherViewInstance.render({prop: 'yes'}); }); }); In order to test the rendering, I had to create a mockup. In this case, I created an object which imitates the Express's response object. In the second part of the test, I created another View class which inherits the base one and applies a custom render method. Here is the /views/Base.js class. module.exports = function(response, template) { this.response = response; this.template = template; }; module.exports.prototype = { extend: function(properties) { var Child = module.exports; Child.prototype = module.exports.prototype; for(var key in properties) { Child.prototype[key] = properties[key]; } return Child; }, render: function(data) { if(this.response && this.template) { this.response.render(this.template, data); } } } Now we have three specs in our tests directory and if you run jasmine-node ./tests the result should be: Finished in 0.009 seconds 7 tests, 18 assertions, 0 failures, 0 skipped Controller Remember the routes and how they were defined? app.get('/', routes.index); The '/' after the route, which in the example above, is actually the controller. It's just a middleware function which accepts request, response and exports.index = function(req, res, next) { res.render('index', { title: 'Express' }); }; Above, is how your controller should look, in the context of Express. The express(1) command line tool creates a directory named routes, but in our case, it is better for it to be named controllers, so I changed it to reflect this naming scheme. Since we're not just building a teeny tiny application, it would be wise if we created a base class, which we can extend. If we ever need to pass some kind of functionality to all of our controllers, this base class would be the perfect place. Again, I'll write the test first, so let's define what we need: - it should have an extendmethod, which accepts an object and returns a new child instance - the child instance should have a runmethod, which is the old middleware function - there should be a nameproperty, which identifies the controller - we should be able to create independent objects, based on the class So just a few things for now, but we may add more functionality later. The test would look something like this: var BaseController = require("../controllers/Base"); describe("Base controller", function() { it("should have a method extend which returns a child instance", function(next) { expect(BaseController.extend).toBeDefined(); var child = BaseController.extend({ name: "my child controller" }); expect(child.run).toBeDefined(); expect(child.name).toBe("my child controller"); next(); }); it("should be able to create different childs", function(next) { var childA = BaseController.extend({ name: "child A", customProperty: 'value' }); var childB = BaseController.extend({ name: "child B" }); expect(childA.name).not.toBe(childB.name); expect(childB.customProperty).not.toBeDefined(); next(); }); }); And here is the implementation of /controllers/Base.js: var _ = require("underscore"); module.exports = { name: "base", extend: function(child) { return _.extend({}, this, child); }, run: function(req, res, next) { } } Of course, every child class should define its own run method, along with its own logic. FastDelivery Website Ok, we have a good set of classes for our MVC architecture and we've covered our newly created modules with tests. Now we are ready to continue with the site, of our fake company, FastDelivery. Let's imagine that the site has two parts - a front-end and an administration panel. The front-end will be used to display the information written in the database to our end users. The admin panel will be used to manage that data. Let's start with our admin (control) panel. Control Panel Let's first create a simple controller which will serve as the administration page. /controllers/Admin.js file: var BaseController = require("./Base"), View = require("../views/Base"); module.exports = BaseController.extend({ name: "Admin", run: function(req, res, next) { var v = new View(res, 'admin'); v.render({ title: 'Administration', content: 'Welcome to the control panel' }); } }); By using the pre-written base classes for our controllers and views, we can easily create the entry point for the control panel. The View class accepts a name of a template file. According to the code above, the file should be called admin.hjs and should be placed in /templates. The content would look something like this: <!DOCTYPE html> <html> <head> <title>{{ title }}</title> <link rel='stylesheet' href='/stylesheets/style.css' /> </head> <body> <div class="container"> <h1>{{ content }}</h1> </div> </body> </html> (In order to keep this tutorial fairly short and in an easy to read format, I'm not going to show every single view template. I strongly recommend that you download the source code from GitHub.) Now to make the controller visible, we have to add a route to it in app.js: var Admin = require('./controllers/Admin'); ... var attachDB = function(req, res, next) { req.db = db; next(); }; ... app.all('/admin*', attachDB, function(req, res, next) { Admin.run(req, res, next); }); Note that we are not sending the Admin.run method directly as middleware. That's because we want to keep the context. If we do this: app.all('/admin*', Admin.run); the word this in Admin will point to something else. Protecting the Administration Panel Every page which starts with /admin should be protected. To achieve this, we are going to use Express's middleware: Sessions. It simply attaches an object to the request called session. We should now change our Admin controller to do two additional things: - It should check if there is a session available. If not, then display a login form. - It should accept the data sent by the login form and authorize the user if the username and password match. Here is a little helper function we can use to accomplish this: authorize: function(req) { return ( req.session && req.session.fastdelivery && req.session.fastdelivery === true ) || ( req.body && req.body.username === this.username && req.body.password === this.password ); } First, we have a statement which tries to recognize the user via the session object. Secondly, we check if a form has been submitted. If so, the data from the form is available in the request.body object which is filled by the bodyParser middleware. Then we just check if the username and password matches. And now here is the run method of the controller, which uses our new helper. We check if the user is authorized, displaying either the control panel itself, otherwise we display the login page: run: function(req, res, next) { if(this.authorize(req)) { req.session.fastdelivery = true; req.session.save(function(err) { var v = new View(res, 'admin'); v.render({ title: 'Administration', content: 'Welcome to the control panel' }); }); } else { var v = new View(res, 'admin-login'); v.render({ title: 'Please login' }); } } Managing Content As I pointed out in the beginning of this article we have plenty of things to administrate. To simplify the process, let's keep all the data in one collection. Every record will have a title, text, picture and type property. The type property will determine the owner of the record. For example, the Contacts page will need only one record with type: 'contacts',; The model takes care of generating a unique ID for every record. We will need it in order to update the information later on. If we want to add a new record for our Contacts page, we can simply use: var model = new (require("../models/ContentModel")); model.insert({ title: "Contacts", text: "...", type: "contacts" }); So, we have a nice API to manage the data in our mongodb collection. Now we are ready to write the UI for using this functionality. For this part, the Admin. Having everything on one page means that we have to focus on the part which renders the page or to be more specific, on the data which we are sending to the template. That's why I created several helper functions which are combined, like so: var self = this; ... var v = new View(res, 'admin'); self.del(req, function() { self.form(req, res, function(formMarkup) { self.list(function(listMarkup) { v.render({ title: 'Administration', content: 'Welcome to the control panel', list: listMarkup, form: formMarkup }); }); }); }); It looks a little bit ugly, but it works as I wanted. The first helper is a del method which checks the current GET parameters and if it finds action=delete&id=[id of the record], it removes data from the collection. The second function is called form and it is responsible mainly for showing the form on the right side of the page. It checks if the form is submitted and properly updates or creates records in the database. At the end, the list method fetches the information and prepares an HTML table, which is later sent to the template. The implementation of these three helpers can be found in the source code for this tutorial. Here, I've decided to show you the function which handles the file upload:; } If a file is submitted, the node script .files property of the request object is filled with data. In our case, we have the following HTML element: <input type="file" name="picture" /> This means that we could access the submitted data via req.files.picture. In the code snippet above, req.files.picture.path is used to get the raw content of the file. Later, the same data is written in a newly created directory and at the end, a proper URL is returned. All of these operations are synchronous, but it's a good practice to use the asynchronous version of readFileSync, mkdirSync and writeFileSync. Front-End The hard work is now complete. The administration panel is working and we have a ContentModel class, which gives us access to the information stored in the database. What we have to do now, is to write the front-end controllers and bind them to the saved content. Here is the controller for the Home page - /controllers/Home.js' }); } }); The home page needs one record with a type of home and four records with a type of blog. Once the controller is done, we just have to add a route to it in app.js: app.all('/', attachDB, function(req, res, next) { Home.run(req, res, next); }); Again, we are attaching the db object to the request. Pretty much the same workflow as the one used in the administration panel.: app.all('/blog/:id', attachDB, function(req, res, next) { Blog.runArticle(req, res, next); }); app.all('/blog', attachDB, function(req, res, next) { Blog.run(req, res, next); }); They both use the same controller: Blog, but call different run methods. Pay attention to the /blog/:id string. This route will match URLs like /blog/4e3455635b4a6f6dccfaa1e50ee71f1cde75222b and the long hash will be available in req.params.id. In other words, we are able to define dynamic parameters. In our case, that's the ID of the record. Once we have this information, we are able to create a unique page for every article. type field. There is a better way to achieve this though, by having only one controller, which accepts the type in its run method. So here are the routes: app.all('/services', attachDB, function(req, res, next) { Page.run('services', req, res, next); }); app.all('/careers', attachDB, function(req, res, next) { Page.run('careers', req, res, next); }); app.all('/contacts', attachDB, function(req, res, next) { Page.run('contacts', req, res, next); }); And the controller would look like this: }); } }); Deployment Deploying an Express based website is actually the same as deploying any other Node.js application: - The files are placed on the server. - The node process should be stopped (if it is running). - An npm installcommand should be ran in order to install the new dependencies (if any). - The main script should then be run again. Keep in mind that Node is still fairly young, so not everything may work as you expected, but there are improvements being made all the time. For example, forever guarantees that your Nodejs program will run continuously. You can do this by issuing the following command: forever start yourapp.js This is what I'm using on my servers as well. It's a nice little tool, but it solves a big problem. If you run your app with just node yourapp.js, once your script exits unexpectedly, the server goes down. forever, simply restarts the application. Now I'm not a system administrator, but I wanted to share my experience integrating node apps with Apache or Nginx, because I think that this is somehow part of the development workflow. As you know, Apache normally runs on port 80, which means that if you open or expresscompletewebsite.dev address. The first thing that we have to do is to add our domain to the hosts file. 127.0.0.1 expresscompletewebsite.dev After that, we have to edit the httpd-vhosts.conf file under the Apache configuration directory and add # expresscompletewebsite.dev <VirtualHost *:80> ServerName expresscompletewebsite.dev ServerAlias ProxyRequests off <Proxy *> Order deny,allow Allow from all </Proxy> <Location /> ProxyPass ProxyPassReverse </Location> </VirtualHost> The server still accepts requests on port 80, but forwards them to port 3000, where node is listening. The Nginx setup is much much easier and to be honest, it's a better choice for hosting Nodejs based apps. You still have to add the domain name in your hosts file. After that, simply create a new file in the /sites-enabled directory under the Nginx installation. The content of the file would look something like this: server { listen 80; server_name expresscompletewebsite.dev location / { proxy_pass; proxy_set_header Host $http_host; } }. Conclusion. Source code The source code for this sample site that we built is available on GitHub -. Feel free to fork it and play with it. Here are the steps for running the site. Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this postPowered by
http://code.tutsplus.com/tutorials/build-a-complete-mvc-website-with-expressjs--net-34168
CC-MAIN-2015-40
refinedweb
5,077
58.69
Hey I'm required to look through an array of boolean values, and return True if they are all set to be true, and False if at least one is set to be false. Essentially, i need to do this: Code Java: boolean[] test = {true,true,false,true}; return (test[0] && test [1] && test[2] && test[3]); but i need to do it in a (for?) loop, because the size of the array is not known beforehand. The array is already initialized elsewhere in the program, i only included it for the example, I only need to return the value off the collective array (if any are false, return false). I have tried a couple various ways to accomplish it but none of them are working. Perhaps this is a problem someone is familiar with? Thanks! Edit: SOLVED IT. All i had to do was make a separate method that only handled the looping operation, and i was able to get the desired result.
http://www.javaprogrammingforums.com/%20collections-generics/22420-need-way-find-way-dermine-if-all-elements-boolean-array-true-false-printingthethread.html
CC-MAIN-2014-52
refinedweb
164
68.5
Odoo Help This community is for beginners and experts willing to share their Odoo knowledge. It's not a forum to discuss ideas, but a knowledge base of questions and their answers. How to get client order ref on delivery orders? I only find modules or answers for v6 and v8. Can someone help me on v7? class stock_picking_out(orm.Model): _inherit = 'stock.picking.out' def _get_sale_client_order_ref(self, cr, uid, ids, field_name, arg, context={}): res = {} for session in self.browse(cr,uid,ids,context=context): if (session.sale_id): res[session.id] = session.sale_id.client_order_ref or False return res _columns = { "client_order_reference": fields.function(_get_sale_client_order_ref, type='char', size=64, method=True, string="Sales Order Customer Reference" ) } Instead of using a function field, you could try with related field () class stock_picking_out(orm.Model): _inherit = 'stock.picking.out' _columns = { "client_order_reference": fields.related('sale_id', 'client_order_ref', type='char', size=64, string="Sales Order Customer Reference" ) } NOTE: If you try to store a related field at stock.picking.out by adding parameter store=True, then you need to define this column at stock.picking also.(This is a special case only applicable for stock.picking, stock.picking.out and stock.picking!
https://www.odoo.com/forum/help-1/question/how-to-get-client-order-ref-on-delivery-orders-76219
CC-MAIN-2016-50
refinedweb
194
53.27
vinodkone closed pull request #297: [WIP] Fix some typos in docs/nested-container-and-task-group.md b/docs/nested-container-and-task-group.md index 0026366603..3325ff8e3a 100644 --- a/docs/nested-container-and-task-group.md +++ b/docs/nested-container-and-task-group.md @@ -14,11 +14,11 @@ some resources (e.g., network namespace, volumes) but not others (e.g., container image, resource limits). Here are the use cases for pod: -* Run a side-car container (e.g., logger, backup) next the main +* Run a side-car container (e.g., logger, backup) next to the main application controller. * Run an adapter container (e.g., metrics endpoint, queue consumer) next to the main container. -* Run transient tasks inside a pod for a operations which are +* Run transient tasks inside a pod for operations which are short-lived and whose exit does not imply that a pod should exit (e.g., a task which backs up data in a persistent volume). * Provide performance isolation between latency-critical
https://mail-archives.eu.apache.org/mod_mbox/mesos-reviews/201808.mbox/%3C153332906186.10917.18130338772419670339.gitbox@gitbox.apache.org%3E
CC-MAIN-2021-25
refinedweb
166
53.88
Hello All, I am trying to create a very simple test algorithm which buys one share of "SPY" six trading periods after the price closes at 302.01 (this occurred on 7/26/2019). I am doing this just to try to understand the basics of coding in Python on QuantConnect. Here is my code: ---------------------------------------------------------------------------------- class OptimizedModulatedCoil(QCAlgorithm): def Initialize(self): self.SetStartDate(2019, 3, 20) # Set Start Date self.SetCash(100000) # Set Strategy Cash self.AddEquity("SPY", Resolution.Daily) def OnData(self, data): '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. Arguments: data: Slice object keyed by symbol containing the stock data ''' self.closeWindow = RollingWindow[float](10) self.closeWindow.Add(data["SPY"].Close) testParm = self.closeWindow[6] self.SetWarmUp(20, Resolution.Daily) if not self.Portfolio.Invested and testParm == 302.01: self.Buy("SPY", 1) ---------------------------------------------------------------------------------- ...and here is the error message I keep recieving when I perform a backtest: ---------------------------------------------------------------------------------- Runtime Error: ArgumentOutOfRangeException : Index must be between 0 and 0 (entry 6 does not exist yet) Parameter name: i Actual value was 6. ---------------------------------------------------------------------------------- Any help that the community can offer will be greatly appreciated. I have created algorithms with Trading View's Pine Script language, but I am completely new to Quantconnect and Python.
https://www.quantconnect.com/forum/discussion/6559/novice-struggling-to-use-rolling-window/
CC-MAIN-2020-05
refinedweb
215
51.44
I decided to write this article after days of coding and finding resources and information on this site, so here it is, a tool I'm using almost everyday in my system admin life. This article will present a tool coded in C# that will scan folders (UNC, local drive/path) and store data in a SQL Database the following informations : this data once stored is used to calculate a simple MS OLAP application (MS Analysis Services 2008) that will consolidate file number and filesize on multiple dimension, recreating the folder tree and then can be used in many way. Excel pivot-table connected to the is a greatway to access some of this data. Real life case, I'm using this soft to scan weekly the file servers where I'm working. There are 22 network share scanned for a grand total of 1.4 Milions folders and 15 Million files. The scan run in a command line on the server hosting the database for convenience purpose and take around 25-26 hours to run. (the scan is multithread and run on the 22 share simultaneously) Why remake a treesize when there are other treesize applications out there? First this project started about 6 years ago when I was confronted with a simple problem : there are too many files on our company file servers! what can we do ? Treesize just didn't cut it. it was the time I was playing with VB6 and implementing essbase servers so I was begining to understand what OLAP meant, and looked for MS solution. I found the filescan I was developping with a SQL DB was quite well suited for a OLAP Cube with parent-child dimension (which never worked on essbase...) That it allowed me to analyse in a much efficient way how files were stored by the users. since then the code evolved, changed, I integrated the ACLs in the scan, the code migrated to c#, then I implemented multi-threading due to the number of file servers growing, lastly I migrated to .NET 3.5, tasted LINQ-to-SQL and adopted it. to run this code, there quite a few things needed In the zip file, you should find a 'CreateDB.sql' script, edit it and change all the occurences of D:\MSSQL\MSSQL.1\MSSQL\DATA\ by the desired data Path (path must exists before running the script). then create the OLAP application by launching the file 'TreeAnalysis.xmla' You need to change the SQL Connection in the OLAP Application, go in the "Data Sources", and modify the connection string to connect to your SQL Server. you can compile and run the code Example of command line DiskAnalysis.exe -s:localhost -d:DiskReport -o:localhost -a:TreeAnalysis DiskAnalysis.exe -s:localhost -d:DiskReport -o:localhost -a:TreeAnalysis -l:3 -t:4 The Database is pretty simple that was basic info on the database, more fun stuff in the POI section The table TreeDetail store the rootFolders to be scanned, Exemple : You will need to insert the folders manually here as I did not make (yet) an admin interface This is the class linking the database to the code. Thanks to that I was able to remove about 200 lines of SQL query in the scanning process. Thanks to VS2008, I just drag and dropped my database object from the server explorer, and voila! I made this class a stand alone class library because there are multiple tools which are using this database, like a filesearcher and a "user manager for domain" showing which folder a domain user has access to, but that's another article. the stuff Right off the bat, I start with 2 public static members public static Semaphore _pool; public static System.Data.SqlClient.SqlConnectionStringBuilder sb; _pool is going to be the limiter of the multithread scansb is the easy way to give all my thread the same database information, there may be nicer way, but I felt it was weighting the code to give db connection information to the object running the thread. _pool sb Once the command line parameters are scanned I intialize the the SqlConnectionStringBuilder: sb = new System.Data.SqlClient.SqlConnectionStringBuilder(); sb.DataSource = servername; sb.InitialCatalog = database; sb.IntegratedSecurity = true; then the program will start the scan, once the scan is finished I do some clean up and translation in the ACLs and SIDs scanned, finally I launch a full process of the OLAP database. if(maxThread > 0) _pool = new Semaphore(maxThread, maxThread); if the maxThread var was not in the command line, or is set to 0, then there is no limit to the max thread allowed, I decided to not initialize the semaphore in this case, later I check if the semaphore is not null in order to wait. Next I initialize the data context for the LINQ-to-SQL Class with the string builder, I initialize the database then get the list of folders that will be scanned DiskReport.DiskReportDataContext dc = new DiskReport.DiskReportDataContext(sb.ConnectionString); if (!clearDB(dc)) return; var q = from t in dc.TreeDetails where t.Enabled == true select new { t.id, t.RootFolder }; if (q.Count() == 0) return; If the clearDB() function did not work, I abort the program, the scan will not work properly.if there is no folder to scan, then exit. Okay, once everything is ready, I initialize 4 arrays :Tree[] which will do the actual scanThreadStart[] which will contain the reference to the thread start function in the Tree objectThread[] which will be the actual threading objectManualResetEvent[] will be used to alert the main thread each sub thread are finished. Tree[] ThreadStart[] Thread[] ManualResetEvent[] Tree[] at = new Tree[q.Count()]; ThreadStart[] ats = new ThreadStart[q.Count()]; Thread[] ath = new Thread[q.Count()]; ManualResetEvent[] events = new ManualResetEvent[q.Count()]; int i=0; foreach (var root in q) { if(root.RootFolder!="") { events[i] = new ManualResetEvent(false); at[i] = new Tree(root.RootFolder, root.id, level, events[i]); ats[i] = new ThreadStart(at[i].startProcess); ath[i] = new Thread(ats[i]); ath[i].Name = root.RootFolder; ath[i].Start(); i++; Thread.Sleep(5000); } } WaitHandle.WaitAll(events); The important point is to initialize the "Tree" Object with all the parameters I need for the "StartProcess()" function.I also added a 5 seconds wait because of starting problems, I will talk about in a chapter below. private static void updateACL() { Console.WriteLine("- Update ACLs"); DiskReport.DiskReportDataContext dc = new DiskReport.DiskReportDataContext(sb.ConnectionString); dc.sp_ClearACLs(); var rights = (from r in dc.FoldersACLs select r.Rights).Distinct(); foreach (Int32 right in rights) { FileSystemRights fsr = (FileSystemRights)right; string str = fsr.ToString(); if (right.ToString() == str) str = fsr.ToString("X"); dc.sp_InsertRight(right, str); Console.WriteLine("insert {0} as {1}", right, str); } } This function goal is to translate numeric values like 0x001F01FF into readable, human friendly information, in this case "FullControl".In the case the right value scanned in the ACE is not translated to text, that can happen a lot with live data on old and long lived file servers, I translate the value into the hexadecimal string. A stored procedure in the SQL server "dc.sp_ClearACLs();" is there to make a bit of cleaning for most of this redundant and often not useful entries. dc.sp_ClearACLs(); private static void updateSID() { Console.WriteLine("- Update SIDs"); System.Security.Principal.SecurityIdentifier sid; DiskReport.DiskReportDataContext dc = new DiskReport.DiskReportDataContext(sb.ConnectionString); dc.CommandTimeout = 6000; dc.sp_UpdateSIDList(); var SSDLs = from s in dc.SIDs select s.SID1; foreach (string ssdl in SSDLs) { sid = new System.Security.Principal.SecurityIdentifier(ssdl); string ntAccount = ""; try { ntAccount = sid.Translate(typeof(System.Security.Principal.NTAccount)).Value; } catch (Exception ex) { Console.WriteLine("{0} {1}", ssdl, ex.Message); } if (ntAccount == "") ntAccount = "<Unknow>"; var s = (from a in dc.SIDs where a.SID1 == ssdl select a).Single(); s.Name = ntAccount; dc.SubmitChanges(); } } This function will translate SID string into readable NT Account name. (ex : "S-1-5-21-3872767328-3467091273-3605603707-1001" = "DESKTOP\Administrator" on my computer)The first thing this function does is call the stored procedure sp_UpdateSIDList() that will scan the list of SIDs in the tables Files and Foldersand extract all the unique SID and store them in the SID table : insert into SIDs (SID) select DISTINCT owner FROM files where owner not in (select SID from SIDs) Then it will try to translate with the function translate : ntAccount = sid.Translate(typeof(System.Security.Principal.NTAccount)).Value; ntAccount = sid.Translate(typeof(System.Security.Principal.NTAccount)).Value; The 2 update update function (sid and acl) are called after the scan for performance purpose, the scan would not be viable if these translations were to be made in each insert. This last function is really simple and can be resumed to : Server s = new Server(); s.Connect(olapServer); s.Databases[application].Process(ProcessType.ProcessFull); Server is a member of the Microsoft.AnalysisServices namespace. This class is where the work is done. The constructor initializes the members of tree that will be used in the scan process, a small note on this line : dc.ObjectTrackingEnabled = false; this will allow the datacontext to track less objects, and prevent inserting lines in the tables using this kind of syntax Table<T> newline = new Table<T>();I tried to do this, when changing the code from plain old 'INSERT INTO' sql queries to LINQ-to-SQL syntax, and it was a really bad idea.Lots of memory leaks and extremely bad performances (from 10 minutes, I was running up to 12 hours and more) I then switched to sql stored procedure to do the insert of files and folders in the database and I found I add the same performances as with the direct SQL command. This function is the one starting the thread, it starts by this line if(Program._pool!=null) Program._pool.WaitOne(); that will wait if the number of allowed running thread is reached.if the semaphore pool is null, I don't wait because there is no limit Then it calls the initProcess() function which will determine if the path to scan is a local drive or a UNC path. If it is a UNC path it will map the path to a letter.it will remove the last "\" of the path also for logging purpose. Next it insert in the database the rootfolder and start the recursive function, described next, that will do the scan it finally disconnect the network drive if needed and set the event telling the main thread it has finished. this function will do the following things : there is a point to make about the date of the files. I came across millions of files and some had really strange of creation (from 1701-xx-xx to 2400-xx-xx, I guess coming from old systems, or detached from lotus mail) after a time, I found out that the last access time was never wrong (almost never) so I decided that if the creation or modif date was under 1950, i'll set the it to the last access date. It's arbitrary, and can be changed to something else, but at least the files get to be inserted in the database, otherwise they're skipped, resulting in wrong data. this function will insert a new folder in the database and return the new database id. first I declare int? id=0; this will allow the parameter of type "OUTPUT" of the stored procedure to return the data, otherwise it will generate an error of incompatible type. then it tries to get the folder owner. I had a strange problem here : even with a try-catch block in the getFolderOwner function, I was required to add another try-catch. I still don't know why. the next test is here for the sake of the "first folder or not" to be inserted.In the desing of the DB, and to allow a good parent-child table to work, the root folder must have a parent ID set to null and its name representing the full pathie : \\Fileserve1\sharewhile the subfolder cannot have a parentID to null, they must not contain the fullpath in their name, just the short name. Here is the resultant assignement of the the value 'name' : string name = (idparent.HasValue) ? folder.Substring(folder.LastIndexOf(@"\") + 1) : folder; in the call to the stored procedure there is this line this.rootFolder + folder.Substring(2) that will always represent the full path of the current folder wether it is a mapped drive or a local drive, a root folder or a subfolder. private void StoreACL(Int32 idFolder, string folder) { DirectoryInfo dinfo = new DirectoryInfo(folder); DirectorySecurity dSecurity = dinfo.GetAccessControl(); AuthorizationRuleCollection returninfo = dSecurity.GetAccessRules(true, true, System.Type.GetType("System.Security.Principal.SecurityIdentifier")); foreach (FileSystemAccessRule fsa in returninfo) { try { dc.sp_InsertFolderACL(idFolder, fsa.IdentityReference.Value, (int)fsa.FileSystemRights, (fsa.IsInherited) ? 1 : 0, (int)fsa.InheritanceFlags, (int)fsa.PropagationFlags); }catch (Exception ex) {Console.WriteLine(ex.Message);} } } This function was a pain to convert from old VB6 and kernel32/advapi API calls to clean .NET code. There is not much documentation and finding how the various objects were related to each other and finally get a FileSystemAccessRule object, which is an ACE (access control entry) was a very long and difficult process. But there it is. You'll also notice the explicit conversion to (int) because these members of fsa are flag structures and will not be stored in the database as it is.The FileSystemRights value is the one that gets translated in the updateACL function private string getFileOwner(string filename) { FileSecurity tmp = new FileSecurity(filename, AccessControlSections.Owner); string owner = "<unknown>"; try { owner = tmp.GetOwner(System.Type.GetType("System.Security.Principal.SecurityIdentifier")).Value; }catch { } return owner; } This function also is the clean way of getting the owner of a file (or a folder) instead of calling win32 API through P/Invoke I need to find where I got this nice piece of code and add the credit to the original developer.I think I grabbed it from code-project, but I'm not sure, this will be updated when I find it. this class is pretty self explanatory, it will map a UNC path to a drive. I modify the code to make the function "nextFreeDrive" public so I could use it the Tree object. This software is the base of other tools I'm working on right now. There is a filefinder that allows me to search throught millions of folders where are the files I need (like all the .AVI and .MP3, forbidden on the network), looking for duplicate files, etc...(this is possible through sql query, but I wanted something other could user) I'm working on a Active directory user manager which allows admins to see wich folders a user has access to through groups There is also the reporting it is possible to make wich OLAP and MDX query. Right now I don't know how it really works, and my only way to query the olap application is through excel.I think more analysis can be done (example, all the home directory of the users stores the same folder for mail or other stuff, a well designed MDX query could show details for these folder only) Given your needs this soft can be the foundation of many useful stuff. here is the design of the cube, the fact table and dimensions are views in the SQL server here is an exemple of what it can look like on excel As said in the introduction, the database is pretty simple as for the data it stores. But there would be a problem of performances, DB file size, tuning if it was just created like that. For example, my real life DB (the one with the 15M files) is about 7GB big, there are lots of indexes I came up with as the number of files was growing and query performances got bad.I came up with really early in the development with the fact that some tables were not permanent data and just needed to be dropped and recreated at runtime, I could use truncate table, but it didn't satisfy me as data files were not clean enough, I kept getting lower performance as files were getting fragmented and all in all it required lots of maintenance for a tool that was running the week end on its own. I then redesigned database storage and finally got to where it is now. There is 1 stored procedure that will delete table, constraint and files and another one that will re-create the whole thing So the database is now made of 8 files, one data and one log file storing permanents data, then for the tables Files, Folders and ACLs one file for the data and one file for the indexes. My sql server is now happy, and query are running a tiny bit faster. In the next articles (or in this one) I'll add an administration interface, and try to come up with a packaged setup with all the possible options (database location, file size for the DB, schedule management and security, right now the account running the program must have access to the folders and the DB and does not allow multiple logins for the network shares ) v1 Initial release : please comment ! (any advice and critic will be well received, it is my first article) and forgive.
http://www.codeproject.com/Articles/35751/Implementing-a-TreeSize-like-application-with-C-SQ?fid=1539578&df=90&mpp=10&noise=1&prof=True&sort=Position&view=Expanded&spc=None
CC-MAIN-2016-44
refinedweb
2,899
61.26
The character pair ? : is called ternary operator in Java because it acts on three variables. This operator is also known as conditional operator. It is used to make conditional expression. It has the following syntax in java: Syntax: variable = exp1 ? exp2 : exp3; where exp1, exp2, and exp3 are expressions. Operator ? : works as follows: First of all, the expression exp1 is evaluated. If it is true, the expression exp2 will be evaluated and the value of exp2 will store in the variable. If exp1 is false, exp3 will be evaluated and its value will store in the variable. Consider the following example: int a = 40; int b = 30; int x = (a > b) ? a : b; Here, first (a > b) is evaluated. If it is true, the value of a is stored in the variable x. If it is false, the value of b is stored in the variable x. Here, (a > b) is true because the value of a is greater than value of b. Therefore, the value of a will assign in the variable x. That is, x = 40. In the above example, we have used 3 variables a, b, and x. That’s why it is called ternary operator in java. This example can also be achieved by using the if-else statement as follows: if(a > b) { x = a; } else { x = b; } Let’s create a program where we will find out the greatest number between the two numbers. Program source code 1: package operatorPrograms; public class Test { public static void main(String[] args) { int x = 20; int y = 10; int z = (x > y) ? x : y; System.out.println("Greatest number: " +z); } } Output: Greatest number: 20 Final words Hope that this tutorial has covered all important points related to the conditional (ternary) operator in java with example program. I hope that you will have understood the basic concept of ternary operator and enjoyed programming. Thanks for reading!!! Next ⇒ Bitwise Operator in Java⇐ PrevNext ⇒
https://www.scientecheasy.com/2020/05/conditional-ternary-operator-in-java.html/
CC-MAIN-2020-24
refinedweb
324
67.15
in python 2.7 i try this code to get data from Deadline software. Its return some data from server... import subprocess path = 'C:/Program Files/Thinkbox/Deadline7/bin/' p1 = subprocess.Popen([path + 'deadlinecommand.exe', 'pools'], stdout=subprocess.PIPE) p1.communicate() and see result: ('none\r\npool_01\r\npool_02\r\npool_03\r\npool_04\r\npool_05\r\npoolhalf\r\n', None) but when i copy that code to python in maya 2014 i get error: p1 = subprocess.Popen(['path + 'deadlinecommand.exe', 'pools'], stdout=subprocess.PIPE) # Error: WindowsError: file C:\PROGRA~1\Autodesk\maya2014\bin\python27.zip\subprocess.py line 826: 6 # run this exe file - is the only option dedline communication. but it pays to stdout data and how it is necessary to pull out. subprocess options except I have not found, but if there are other options will be glad to try them anyone else encountered this problem? strange that in pure Python 2.7 running in windows all works, and there is no Maya 2014 i use: Windows 7 + Python 2.7.9 Maya 2014 (Python 2.7.3)
http://www.howtobuildsoftware.com/index.php/how-do/676/python-27-subprocess-stdout-maya-maya-python-subprocess-error
CC-MAIN-2018-47
refinedweb
180
61.63
Thanks Norm. This code is full of mistakes, i'm finding out, but i've been fixing them one by one. I think I fixed the counts, but I broke some other stuff on the way :confused: Quick sort is now... Type: Posts; User: husain2213 Thanks Norm. This code is full of mistakes, i'm finding out, but i've been fixing them one by one. I think I fixed the counts, but I broke some other stuff on the way :confused: Quick sort is now... no, its not completely solved yet! here is what's wrong: 1- quick sort still takes forever for larger array sizes (I don't think it is supposed to). 2- comparison count returned by quicksort is... I think there was a problem in my swap() method, but its fixed now and the arrays are sorted. There are no infinite loops, but quicksort is.. well, not quick. It takes forever and doesn't return a... Hello everyone, I'm having trouble with my assignment and need you're help! I'm supposed to write the code for bubblesort and quicksort and test them under different array sizes while recording the... I understand what you guys are saying, its just that putting it in code is is a bit tough for me :confused: I have to search in preorder using recursion to compare the strings, and if a match is... Sorry, but this didn't really help. I understand where is my error, I just have no idea how to fix it. I tried making it look like the preorderPrint class, but it doesn't work because I have to... hello everyone! I'm have created a binary tree program where the tree is balanced(but not sorted). The Tree hold unique strings in each nodes. if the user enters a non unique string, the node... Thanks a lot,, its working now :-bd just needs some tweaking really appreciate the help :o customerQueue is null: false customerQueue.peek() is null: true Exception in thread "main" java.lang.NullPointerException at CustomerQueue.main(CustomerQueue.java:30) is this happening because... Exception in thread "main" java.lang.NullPointerException at CustomerQueue.main(CustomerQueue.java:28) that's the exact exception. it points to this line: customerQueue.peek().minutePassed(); oops! thanks for that. It compiles now but i get an exception when running it. could you take a look at the new code? import java.util.Queue; import java.util.LinkedList; import... Hi! so i'm trying to make a program with a customer class that keeps how many minutes each customer needs to be served. The driver class CustomerQueue is a queue of all customers that haven't been...
http://www.javaprogrammingforums.com/search.php?s=3d7f579a8236a9e9e925c19aa830bdeb&searchid=1203259
CC-MAIN-2014-49
refinedweb
449
84.88
The case for HOC vs The Composition API The new composition API is shaking up the Vue community and is taking it by storm. Everyone is making the case for it and how it makes for a better pattern to re-use logic. But would the higher-order components (HOC) still be viable after its introduction with Vue 3 release? Composition API PrimerComposition API Primer There is no shortage of videos and talks about the new Vue 3.0 composition API that's inspired by React hooks. I will assume you are already up to speed on that trend. Scoped slots are Vue's way to compose components logic together and it is very elegant and is underused by the majority of the Vue ecosystem. There are two reasons for that: - The template-based default approach of Vue.js and its ease of use doesn't force developers into advanced patterns like HOC. - Vue still has mixins which solve the problem albeit badly in most cases, I don't see it used a lot though. Here is an example of the famous mouse position example that started it all, first in the declarative approach where we use scoped slots (Vue's HOC): <template> <MousePosition v- <span>{{ x }}</span> <span>{{ y }}</span> </MousePosition> </template> <script> import MousePosition from '@/components/MousePosition'; export default { components: { MousePosition } }; </script> The implementation details are not our focus here. The MousePosition component exposes the mouse position using slot props. The composition API introduces a different approach, a more declarative one. <template> <div> <span>{{ x }}</span> <span>{{ y }}</span> </div> </template> <script> import { useMousePosition } from '@/maybeHooks/mouse-position'; export default { setup() { const { x, y } = useMousePosition(); return { x, y }; } }; </script> The composition API isn't less verbose than its HOC counterpart. But in that specific example, it moves some of the template verbosity into the script. In other words, it converts that logic from being declarative to being imperative. That might not mean a lot but this is the most crucial idea if we are going to find a case for HOCs. Let's explore some more examples to see if we can gather more insights. ExtendibilityExtendibility Let's start with something common for most of us, calling APIs. Assuming we have both a Fetch component and a useFetch composition function and we want to view a list of users sorted by their names. If we would go with the declarative style: <template> <Fetch endpoint="/api/users" v- <ul> <li v- {{ user.name }} </li> </ul> </Fetch> </template> <script> import Fetch from '@/components/Fetch'; export default { components: { Fetch } }; </script> That was ugly. first, we had to shallow clone the array of users because we don't want to mutate slot props. Also since we have no access to the data outside of the component scoped slot we needed to inline our sorting function. Thankfully, since we set our key attribute here it is efficient to some extent. What about the imperative style, is it any better? <template> <ul> <li v-{{ user.name }}</li> </ul> </template> <script> import { computed } from 'vue'; import { useFetch } from '@/maybeHooks/fetch'; export default { setup() { const { data } = useFetch('/api/users'); const users = computed(() => { if (!data.value) { return []; } return [...data.value.users].sort((a, b) => { // Sorting logic... }); }); return { users }; } }; </script> That is much better. We have the full force of JavaScript backing us up in the script tag, allowing us to do much more. For example if we would use lodash to refactor things a little bit, it would look like this: import { sortBy } from 'lodash-es'; export default { setup() { const { data } = useFetch('/api/users'); const users = computed(() => { if (!data.value) { return []; } return sortBy(data.value.users, ['name']); }); return { users }; } }; Declaratively it would be very annoying since we have to expose our imported sortBy function: <template> <Fetch endpoint="/api/users" v- <ul> <li v- {{ user.name }} </li> </ul> </Fetch> </template> <script> import Fetch from '@/components/Fetch'; import { sortBy } from 'lodash-es'; export default { components: { Fetch }, setup() { return { sortBy }; } }; </script> This is problematic and gives us a second insight. That the composition API gives us the full expressiveness of the JavaScript language. This has always been the argument for JSX over Templates. So using the composition API here has more value than the HOC approach, so let's phrase a rule for it. We could say, HOCs are viable if you are not going to modify/extend the exposed props. Reusability RevisedReusability Revised It's often argued that reusability for the composition functions are much higher than the HOC counterparts. Using the useMousePosition function as an example here, it is much simpler to import useMousePosition and use it throughout our components for example ComponentA and ComponentB and we would still have our flexibility intact. But allow me to present another scenario than the one that favors the composition API, let's say you want to use the useMousePosition function many times within the same template/component. Now it would look like this: <template> <div> <span>{{ x }}</span> <span>{{ y }}</span> <span>{{ x2 }}</span> <span>{{ y2 }}</span> <span>{{ x3 }}</span> <span>{{ y3 }}</span> </div> </template> <script> import { useMousePosition } from '@/maybeHooks/mouse-position'; export default { setup() { const { x, y } = useMousePosition(); const { x: x2, y: y2 } = useMousePosition(); const { x: x3, y: y3 } = useMousePosition(); return { x, y, x2, y2, x3, y3 }; } }; </script> We immediately run into one of the most common problems, naming things. Now we have many x coordinate to name and since they all have the same scope, they need to be unique from one another. Meanwhile, HOCs don't suffer from this problem: <template> <div> <MousePosition v- <span>{{ x }}</span> <span>{{ y }}</span> </MousePosition> <MousePosition v- <span>{{ x }}</span> <span>{{ y }}</span> </MousePosition> <MousePosition v- <span>{{ x }}</span> <span>{{ y }}</span> </MousePosition> </div> </template> <script> import MousePosition from '@/components/MousePosition'; export default { components: { MousePosition } }; </script> It's actually much better than the composition function approach. Since each scoped-slot has it's own isolated scope, they cannot conflict with one another. This gives us tiny namespaces in the template where we don't have to rename our stuff. Our takeaway here is that, while the composition API is very reusable, it's reusability can be questioned if the same function would be used multiple times within the same component/scope. Of course, you could refactor things a little bit to favor the composition API, like returning an array instead of an object: import { useMousePosition } from '@/maybeHooks/mouse-position'; export default { setup() { const [x, y] = useMousePosition(); const [x2, y2] = useMousePosition(); const [x3, y3] = useMousePosition(); return { x, y, x2, y2, x3, y3 }; } }; Which is slightly better, but I still think the HOC approach here is much easier to digest and maintain. This brings us to another conclusion about the composition API. The smaller and more specialized your components are, the better you would make use of the composition API. However if you have really big components, the composition API isn't any better than its counterpart. Case Study: VeeValidate v4Case Study: VeeValidate v4 I have been working on VeeValidate v4 for a while now, and while the progress is slow. I think vee-validate being one of the best representatives of the declarative style of things illustrates the contrast between using HOCs and composition functions best. So vee-validate v4 while not released yet, offers both options, allowing you to use whatever style you need. It exposes both a ValidationProvider component and useField composition function. Borrowing some insights from React's popular library Formik, I have noticed people still using the declarative approach over the imperative one. Even though both could achieve the same thing. Here is how to build a registration form using useField which is the imperative option: <template> <div> <form @submit. <input name="name" v- <span>{{ nameErrors[0] }}</span> <input name="email" v- <span>{{ emailErrors[0] }}</span> <input name="password" v- <span>{{ passwordErrors[0] }}</span> <button>Submit</button> </form> </div> </template> <script> import { useField, useForm } from 'vee-validate'; export default { setup() { const { form, handleSubmit } = useForm(); const { value: name, errors: nameErrors } = useField('name', 'required', { form }); const { value: password, errors: passwordErrors } = useField('password', 'required|min:8', { form }); const { value: email, errors: emailErrors } = useField('email', 'required|email', { form }); const onSubmit = handleSubmit(values => { // TODO: Send data to the API }); return { name, nameErrors, password, passwordErrors, email, emailErrors, onSubmit }; } }; </script> This isn't so bad, While useForm and useField save you the trouble of creating ref for your models, it's still too much to deal with in the setup function. If you were to have a very complicated form this will get much worse. Now here is how the declarative style fares: <template> <div> <ValidationObserver as="form" @ <ValidationProvider name="name" rules="required" as="input" /> <span>{{ errors.name }}</span> <ValidationProvider name="email" rules="required|email" as="input" type="email" /> <span>{{ errors.email }}</span> <ValidationProvider name="password" rules="required|min:8" as="input" type="password" /> <span>{{ errors.password }}</span> <button>Submit</button> </ValidationObserver> </div> </template> <script> import { ValidationProvider, ValidationObserver } from 'vee-validate'; export default { components: { ValidationProvider, ValidationObserver }, setup() { function onSubmit(values) { // TODO: Send stuff to API } return { onSubmit }; } }; </script> I could be biased, but in my opinion that is indeed much better. It's easier to follow, this is actually one of the new ways vee-validate v4 is making use of HOCs to provide better experience for building forms than v3. If you take a closer look, notice how much abstraction is being done with the components there. You no longer even have to specify a v-model or define them in your data/setup. You just declare "this is a field" and the submission handler automatically gives you access to those values which is what most of forms are. You could still have full control and use scoped slots just like v3: <template> <!-- ....... --> <ValidationProvider name="f2" rules="required" v- <input type="text" v- <span>{{ errors[0] }}</span> </ValidationProvider> <!-- ....... --> </template> I will be publishing another article shortly about the changes to v4. The takeaway here is that because HOCs live in the template, they can infer assumptions about your code and they would be better informed than otherwise with the imperative approach. So, when should you use useField since the HOC approach looks better here? Following some of the takeaways we highlighted earlier, instead of building an entire form with useField. Reducing the scope to a more specialized component pays dividends here, let's say we want to create a TextInput component that can be validated: <template> <div> <input type="text" v- <span>{{ errors[0] }}</span> </div> </template> <script> import { watch } from 'vue'; import { useField } from 'vee-validate'; export default { name: 'TextInput', setup(props, { emit }) { const { errors, value } = useField(props.name, props.rules); watch(value, val => { emit('modelUpdate', val); }); return { errors, value }; } }; </script> You can use this component to build up your complex form. This component now can do a lot more than its HOC counterpart. We were able to make better use of the composition API because we reduced our component scope. If this matches your use-case then useField is the better approach here. For example if you are building a component library/system, the imperative approach is suited more. You can think of the ValidationProvider as a high-level generic implementation of the useField functionality. Under the hood the ValidationProvider uses useField and abstracts away the rest. This is actually an observation that I didn't hear anyone say it, the composition API is the best API to build HOCs. They complement one another, not replace each other. ConclusionConclusion Let's summarize the takeaways we've discovered in this article. I argue that HOCs are still very much viable, but the composition API allows for more fine-grained control over many of the cases where HOCs were the only solution but not the best solution. You should use HOCs if: - If the slot props will not be modified/extended. - If you are going to use the same logic multiple times in the same component (Like forms). - If you are going to infer some information from the template. i.e: a11yand animations. Otherwise, If your components are specialized, you can make better use of the composition API which requires more discipline than HOCs but it will pay dividends. So instead of thinking "Composition API" is the new hip and should be always used, think of it as just a tool in your existing arsenal, in some areas it shines and in others its outshined by other tools like HOCs. And with an amazing framework like Vue.js you get to choose between them and mix and match in a very cohesive manner.
https://logaretm.com/blog/2020-05-06-the-case-for-hoc-vs-composition-api/
CC-MAIN-2020-34
refinedweb
2,089
50.77
>> Why not @people.debian.org ? It represents pretty good what thoses >> eventual "contributors" would: the _people_ who make Debian. > In fact, I've already argued in this thread that @whatever.debian.org > will need nevertheless to share the namespace with @debian.org > domain. (I.e., I don't want someone to steal "my" > zack@contributor.debian.org, nor a contributor probably won't to > change nickname if he eventually becomes full blown DD.) The idea for contributor.d.o includes either to reserve all existing debian.org UIDs within the @contributor.d.o namespace or activate them as forwarding or giving people the choice to activate or whatever. > As a consequence of that reasoning, why not giving plain @debian.org > mail addresses to voting contributors?. -- bye, Joerg <40293f1b.8130421@news.individual.de> Windows ME? Mit 13? Kann der nicht lieber Drogen nehmen wie andere Kinder in dem Alter?
http://lists.debian.org/debian-project/2008/10/msg00232.html
CC-MAIN-2013-48
refinedweb
148
54.49
Opened 2 years ago Last modified 21 months ago #9350 new feature request Consider using xchg instead of mfence for CS stores Description To get sequential consistency for atomicWriteIntArray# we use an mfence instruction. An alternative is to use an xchg instruction (which has an implicit lock prefix), which might have lower latency. We should check what other compilers do. Change History (3) comment:1 Changed 2 years ago by tibbe comment:2 Changed 2 years ago by tibbe GCC 4.9.1 does use mfence. This code #include <stdatomic.h> void f(atomic_int* obj, int val) { return atomic_store(obj, val); } generates this assembly .file "repro.c" .text .globl f .type f, @function f: .LFB0: .cfi_startproc movl %esi, (%rdi) mfence ret .cfi_endproc .LFE0: .size f, .-f .ident "GCC: (GNU) 4.9.1" .section .note.GNU-stack,"",@progbits comment:3 Changed 21 months ago by thomie - Cc simonmar added - Component changed from Compiler to Compiler (NCG) - Type of failure changed from None/Unknown to Runtime performance bug Note: See TracTickets for help on using tickets. Herb Sutter argues for using xchg over mfence in C++ and Beyond 2012: Herb Sutter - atomic<> Weapons, 2 of 2, around 0:38:20.
https://ghc.haskell.org/trac/ghc/ticket/9350
CC-MAIN-2016-30
refinedweb
198
64.61
Scanning (XAML) Learn here how to scan content from your Windows Store app using C# or C++, by using a flatbed, feeder, or auto-configured scan source. We assume that you already know how to write programs with C# or C++, and XAML, and that you have a scanner device installed on your computer. Overview To add the ability to scan from your Windows Store app in Windows 8.1, use the Windows.Devices.Scanners namespace. This namespace is built on top of the existing WIA APIs and is integrated with the Device Access API. Windows Store app scanning To scan from your Windows Store app, you must first list the available scanners by declaring a new DeviceInformation object and getting the DeviceClass type. Only scanners that are installed locally with WIA drivers are listed and available to your Windows Store app. After your app has listed available scanners, it can use the auto-configured scan settings based on the scanner type, or just scan using the available flatbed or feeder scan source. To use auto-configured settings, the scanner must be enabled for auto-configuration must not be equipped with both a flatbed and a feeder scanner. For more info, see Auto-Configured Scanning.
https://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn263143.aspx
CC-MAIN-2017-51
refinedweb
205
59.94
Its important to learn ES6 anyways, but for the patterns and structures used its especially useful for our favourite componentized frameworks. That being said, you can still use ES5 to get it to work, but for the sake of consistency ES6 is the way to go! Create websites with React.js! Stop living in the past and move with the times, bruh!! 😛 Don’t Mutate the State, Mate! Most of the time this isn’t a good idea anyways, but its especially true for building front end projects. Changing the original initiated state can cause a lot of problems when things go wrong, it can make it hard to keep track of where bugs are coming from. Here we got a shop, lets add an item… class App extends Component { constructor(props) { super(props); this.state = { shop:[] }; } ...// onAdd = (item) => { this.state.shop.push(item); }; To the untrained eye this is how you might think to do it. But this is a classic common situation in which we’re changing the original state which is a huge no-no in functional programming. onAdd = (item) => { let newList = this.state.shop; newList = newList.concat(item); this.setState({ shop: newList }) }; Concat is a method which combines two arrays into a new one. Here we grab the shop array (empty for now) and combine it with the item into a new array. Then we use React’s setState to modify the current state, instead of directly doing it ourselves. onAdd = (item) => { let newList = this.state.shop; newList = [...newList, item]; this.setState({ shop: newList }) Most of the time we use the ES6 ‘version’ of combining the arrays with the spread operator. The ‘…’ allows an existing array to be referenced but not modified, meaning we don’t mutate the original array. Making sure that we never directly mutate the state is great practice, and we want to get in the mindset of doing that all the time. Bind Off Your ‘This’ Problems with Arrow Functions As you may or may not have noticed, the functions written above seem to be in a strange format. Notice there is no function keywords and for more advanced coders therefore no bind methods either. this.[function] to refer to functions elsewhere, but because of the lexical scope the this isn’t referring to where we want it to. this keyword from being limited to within that function. class ParentComponent extends Component { render() { return ( <div>
https://coinerblog.com/es6sential-react-the-state-bait-this-problems-88090a73b8e3/
CC-MAIN-2020-29
refinedweb
403
73.58
Internet Research Task Force (IRTF) D. McGrew Request for Comments: 8554 M. Curcio Category: Informational S. Fluhrer ISSN: 2070-1721 Cisco Systems April 2019 Leighton-Micali Hash-Based Signatures Abstract. CFRG Note on Post-Quantum Cryptography . . . . . . . . . 5 1.2. Intellectual Property . . . . . . . . . . . . . . . . . . 6 1.2.1. Disclaimer . . . . . . . . . . . . . . . . . . . . . 6 1.3. Conventions Used in This Document . . . . . . . . . . . . 6 2. Interface . . . . . . . . . . . . . . . . . . . . . . . . . . 6 3. Notation . . . . . . . . . . . . . . . . . . . . . . . . . . 7 3.1. Data Types . . . . . . . . . . . . . . . . . . . . . . . 7 3.1.1. Operators . . . . . . . . . . . . . . . . . . . . . . 7 3.1.2. Functions . . . . . . . . . . . . . . . . . . . . . . 8 3.1.3. Strings of w-Bit Elements . . . . . . . . . . . . . . 8 3.2. Typecodes . . . . . . . . . . . . . . . . . . . . . . . . 9 3.3. Notation and Formats . . . . . . . . . . . . . . . . . . 9 4. LM-OTS One-Time Signatures . . . . . . . . . . . . . . . . . 12 4.1. Parameters . . . . . . . . . . . . . . . . . . . . . . . 13 4.2. Private Key . . . . . . . . . . . . . . . . . . . . . . . 14 4.3. Public Key . . . . . . . . . . . . . . . . . . . . . . . 15 4.4. Checksum . . . . . . . . . . . . . . . . . . . . . . . . 15 4.5. Signature Generation . . . . . . . . . . . . . . . . . . 16 4.6. Signature Verification . . . . . . . . . . . . . . . . . 17 5. Leighton-Micali Signatures . . . . . . . . . . . . . . . . . 19 5.1. Parameters . . . . . . . . . . . . . . . . . . . . . . . 19 5.2. LMS Private Key . . . . . . . . . . . . . . . . . . . . . 20 5.3. LMS Public Key . . . . . . . . . . . . . . . . . . . . . 21 5.4. LMS Signature . . . . . . . . . . . . . . . . . . . . . . 22 5.4.1. LMS Signature Generation . . . . . . . . . . . . . . 23 5.4.2. LMS Signature Verification . . . . . . . . . . . . . 24 6. Hierarchical Signatures . . . . . . . . . . . . . . . . . . . 26 6.1. Key Generation . . . . . . . . . . . . . . . . . . . . . 29 6.2. Signature Generation . . . . . . . . . . . . . . . . . . 30 6.3. Signature Verification . . . . . . . . . . . . . . . . . 32 6.4. Parameter Set Recommendations . . . . . . . . . . . . . . 32 7. Rationale . . . . . . . . . . . . . . . . . . . . . . . . . . 34 7.1. Security String . . . . . . . . . . . . . . . . . . . . . 35 8. IANA Considerations . . . . . . . . . . . . . . . . . . . . . 36 9. Security Considerations . . . . . . . . . . . . . . . . . . . 38 9.1. Hash Formats . . . . . . . . . . . . . . . . . . . . . . 39 9.2. Stateful Signature Algorithm . . . . . . . . . . . . . . 40 9.3. Security of LM-OTS Checksum . . . . . . . . . . . . . . . 41 10. Comparison with Other Work . . . . . . . . . . . . . . . . . 42 11. References . . . . . . . . . . . . . . . . . . . . . . . . . 43 11.1. Normative References . . . . . . . . . . . . . . . . . . 43 11.2. Informative References . . . . . . . . . . . . . . . . . 43 Appendix A. Pseudorandom Key Generation . . . . . . . . . . . . 45 Appendix B. LM-OTS Parameter Options . . . . . . . . . . . . . . 45 Appendix C. An Iterative Algorithm for Computing an LMS Public Key . . . . . . . . . . . . . . . . . . . . . . . . 47 Appendix D. Method for Deriving Authentication Path for a Signature . . . . . . . . . . . . . . . . . . . . . 48 Appendix E. Example Implementation . . . . . . . . . . . . . . . 49 Appendix F. Test Cases . . . . . . . . . . . . . . . . . . . . . 49 Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . . 60 Authors' Addresses . . . . . . . . . . . . . . . . . . . . . . . 61 1. Introduction One-time signature systems, and general-purpose signature systems built out of one-time signature systems, have been known since 1979 [Merkle79], were well studied in the 1990s [USPTO5432852], and have benefited from renewed attention in the last decade. The characteristics of these signature systems are small private and public keys and fast signature generation and verification, but large signatures and moderately slow key generation (in comparison with RSA and ECDSA (Elliptic Curve Digital Signature Algorithm)). Private keys can be made very small by appropriate key generation, for example, as described in Appendix A. In recent years, there has been interest in these systems because of their post-quantum security and their suitability for compact verifier implementations. This note describes the Leighton and Micali adaptation [USPTO5432852] of the original Lamport-Diffie-Winternitz-Merkle one-time signature system [Merkle79] [C:Merkle87] [C:Merkle89a] [C:Merkle89b] and general signature system [Merkle79] with enough specificity to ensure interoperability between implementations. A signature system provides asymmetric message authentication. The key-generation algorithm produces a public/private key pair. A message is signed by a private key, producing a signature, and a message/signature pair can be verified by a public key. A One-Time Signature (OTS) system can be used to sign one message securely but will become insecure if more than one is signed with the same public/ private key pair. An N-time signature system can be used to sign N or fewer messages securely. A Merkle-tree signature scheme is an N-time signature system that uses an OTS system as a component. In the Merkle scheme, a binary tree of height h is used to hold 2^h OTS key pairs. Each interior node of the tree holds a value that is the hash of the values of its two child nodes. The public key of the tree is the value of the root node (a recursive hash of the OTS public keys), while the private key of the tree is the collection of all the OTS private keys, together with the index of the next OTS private key to sign the next message with. In this note, we describe the Leighton-Micali Signature (LMS) system (a variant of the Merkle scheme) with the Hierarchical Signature System (HSS) built on top of it that allows it to efficiently scale to larger numbers of signatures. In order to support signing a large number of messages on resource-constrained systems, the Merkle tree can be subdivided into a number of smaller trees. Only the bottommost tree is used to sign messages, while trees above that are used to sign the public keys of their children. For example, in the simplest case with two levels with both levels consisting of height h trees, the root tree is used to sign 2^h trees with 2^h OTS key pairs, and each second-level tree has 2^h OTS key pairs, for a total of 2^(2h) bottom-level key pairs, and so can sign 2^(2h) messages. The advantage of this scheme is that only the active trees need to be instantiated, which saves both time (for key generation) and space (for key storage). On the other hand, using a multilevel signature scheme increases the size of the signature as well as the signature verification time. This note is structured as follows. Notes on post-quantum cryptography are discussed in Section 1.1. Intellectual property issues are discussed in Section 1.2. The notation used within this note is defined in Section 3, and the public formats are described in Section 3.3. The Leighton-Micali One-Time Signature (LM-OTS) system is described in Section 4, and the LMS and HSS N-time signature systems are described in Sections 5 and 6, respectively. Sufficient detail is provided to ensure interoperability. The rationale for the design decisions is given in Section 7. The IANA registry for these signature systems is described in Section 8. Security considerations are presented in Section 9. Comparison with another hash-based signature algorithm (eXtended Merkle Signature Scheme (XMSS)) is in Section 10. This document represents the rough consensus of the CFRG. 1.1. CFRG Note on Post-Quantum Cryptography All post-quantum algorithms documented by the Crypto Forum Research Group (CFRG) are today considered ready for experimentation and further engineering development (e.g., to establish the impact of performance and sizes on IETF protocols). However, at the time of writing, we do not have significant deployment experience with such algorithms. Many of these algorithms come with specific restrictions, e.g., change of classical interface or less cryptanalysis of proposed parameters than established schemes. The CFRG has consensus that all documents describing post-quantum technologies include the above paragraph and a clear additional warning about any specific restrictions, especially as those might affect use or deployment of the specific scheme. That guidance may be changed over time via document updates. Additionally, for LMS: CFRG consensus is that we are confident in the cryptographic security of the signature schemes described in this document against quantum computers, given the current state of the research community's knowledge about quantum algorithms. Indeed, we are confident that the security of a significant part of the Internet could be made dependent on the signature schemes defined in this document, if developers take care of the following. In contrast to traditional signature schemes, the signature schemes described in this document are stateful, meaning the secret key changes over time. If a secret key state is used twice, no cryptographic security guarantees remain. In consequence, it becomes feasible to forge a signature on a new message. This is a new property that most developers will not be familiar with and requires careful handling of secret keys. Developers should not use the schemes described here except in systems that prevent the reuse of secret key states. Note that the fact that the schemes described in this document are stateful also implies that classical APIs for digital signatures cannot be used without modification. The API MUST be able to handle a dynamic secret key state; that is, the API MUST allow the signature-generation algorithm to update the secret key state. 1.2. Intellectual Property This document is based on U.S. Patent 5,432,852, which was issued over twenty years ago and is thus expired. 1.2.1. Disclaimer This document is not intended as legal advice. Readers are advised to consult with their own legal advisers if they would like a legal interpretation of their rights. The IETF policies and processes regarding intellectual property and patents are outlined in [RFC8179] and at <>. The LMS signing algorithm is stateful; it modifies and updates the private key as a side effect of generating a signature. Once a particular value of the private key is used to sign one message, it MUST NOT be used to sign another. The key-generation algorithm takes as input an indication of the parameters for the signature system. If it is successful, it returns both a private key and a public key. Otherwise, it returns an indication of failure. The signing algorithm takes as input the message to be signed and the current value of the private key. If successful, it returns a signature and the next value of the private key, if there is such a value. After the private key of an N-time signature system has signed N messages, the signing algorithm returns the signature and an indication that there is no next value of the private key that can be used for signing. If unsuccessful, it returns an indication of failure. The verification algorithm takes as input the public key, a message, and a signature; it returns an indication of whether or not the signature-and-message pair is valid. A message/signature pair is valid if the signature was returned by the signing algorithm upon input of the message and the private key corresponding to the public key; otherwise, the signature and message pair is not valid with probability very close to one. 3. Notation 3.1. Data Types Bytes and byte strings are the fundamental data types. with a length of three. An array of byte strings is an ordered set, indexed starting at zero, in which all strings have the same length. Unsigned integers are converted into byte strings by representing them in network byte order. To make the number of bytes in the representation explicit, we define the functions u8str(X), u16str(X), and u32str(X), which take a nonnegative integer X as input and return one-, two-, and four-byte strings, respectively. We also make use of the function strTou32(S), which takes a four-byte string S as input and returns a nonnegative integer; the identity u32str(strTou32(S)) = S holds for any four-byte string S. 3.1.1. Operators When a and b are real numbers, mathematical operators are defined as follows: ^ : a ^ b denotes the result of a raised to the power of b * : a * b denotes the product of a multiplied by b / : a / b denotes the quotient of a divided by b % : a % b denotes the remainder of the integer division of a by b (with a and b being restricted to integers in this case) + : a + b denotes the sum of a and b - : a - b denotes the difference of a and b AND : a AND b denotes the bitwise AND of the two nonnegative integers a and b (represented in binary notation) The standard order of operations is used when evaluating arithmetic expressions. When B is a byte and i is an integer, then B >> i denotes the logical right-shift operation by i bit positions. Similarly, B << i denotes the logical left-shift operation. If S and T are byte strings, then S || T denotes the concatenation of S and T. If S and T are equal-length byte strings, then S AND T denotes the bitwise logical and operation. The i-th element in an array A is denoted as A[i]. 3.1.2. Functions If r is a nonnegative real number, then we define the following functions: ceil(r) : returns the smallest integer greater than or equal to r floor(r) : returns the largest integer less than or equal to r lg(r) : returns the base-2 logarithm of r 3.1.3. Strings of w-Bit Elements If S is a byte string, then byte(S, i) denotes its i-th byte, where the index starts at 0 at the left. Hence, byte(S, 0) is the leftmost byte of S, byte(S, 1) is the second byte from the left, and (assuming S is n bytes long) byte(S, n-1) is the rightmost byte of S. In addition, bytes(S, i, j) denotes the range of bytes from the i-th to the j-th byte, inclusive. For example, if S = 0x02040608, then byte(S, 0) is 0x02 and bytes(S, 1, 2) is 0x0406. A byte string can be considered to be a string of w-bit unsigned integers; the correspondence is defined by the function coef(S, i, w) as follows: If S is a string, i is a positive integer, and w is a member of the set { 1, 2, 4, 8 }, then coef(S, i, w) is the i-th, w-bit value, if S is interpreted as a sequence of w-bit values. That is, coef(S, i, w) = (2^w - 1) AND ( byte(S, floor(i * w / 8)) >> (8 - (w * (i % (8 / w)) + w)) ) For example, if S is the string 0x1234, then coef(S, 7, 1) is 0 and coef(S, 0, 4) is 1. S (represented as bits) +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | 0| 0| 0| 1| 0| 0| 1| 0| 0| 0| 1| 1| 0| 1| 0| 0| +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ ^ | coef(S, 7, 1) S (represented as four-bit values) +-----------+-----------+-----------+-----------+ | 1 | 2 | 3 | 4 | +-----------+-----------+-----------+-----------+ ^ | coef(S, 0, 4) The return value of coef is an unsigned integer. If i is larger than the number of w-bit values in S, then coef(S, i, w) is undefined, and an attempt to compute that value MUST raise an error. 3.2. Typecodes A typecode is an unsigned integer that is associated with a particular data format. The format of the LM-OTS, LMS, and HSS signatures and public keys all begin with a typecode that indicates the precise details used in that format. These typecodes are represented as four-byte unsigned integers in network byte order; equivalently, they are External Data Representation (XDR) enumerations (see Section 3.3). 3.3. Notation and Formats The signature and public key formats are formally defined in XDR to provide an unambiguous, machine-readable definition [RFC4506]. The private key format is not included as it is not needed for interoperability and an implementation MAY use any private key format. However, for clarity, we include an example of private key data in Test Case 2 of Appendix F. Though XDR is used, these formats are simple and easy to parse without any special tools. An illustration of the layout of data in these objects is provided below. The definitions are as follows: /* one-time signatures */ enum lmots_algorithm_type { lmots_reserved = 0, lmots_sha256_n32_w1 = 1, lmots_sha256_n32_w2 = 2, lmots_sha256_n32_w4 = 3, lmots_sha256_n32_w8 = 4 }; typedef opaque bytestring32[32]; struct lmots_signature_n32_p265 { bytestring32 C; bytestring32 y[265]; }; struct lmots_signature_n32_p133 { bytestring32 C; bytestring32 y[133]; }; struct lmots_signature_n32_p67 { bytestring32 C; bytestring32 y[67]; }; struct lmots_signature_n32_p34 { bytestring32 C; bytestring32 y[34]; }; union lmots_signature switch (lmots_algorithm_type type) { case lmots_sha256_n32_w1: lmots_signature_n32_p265 sig_n32_p265; case lmots_sha256_n32_w2: lmots_signature_n32_p133 sig_n32_p133; case lmots_sha256_n32_w4: lmots_signature_n32_p67 sig_n32_p67; case lmots_sha256_n32_w8: lmots_signature_n32_p34 sig_n32_p34; default: void; /* error condition */ }; /* hash-based signatures (hbs) */ enum lms_algorithm_type { lms_reserved = 0, lms_sha256_n32_h5 = 5, lms_sha256_n32_h10 = 6, lms_sha256_n32_h15 = 7, lms_sha256_n32_h20 = 8, lms_sha256_n32_h25 = 9 }; /* leighton-micali signatures (lms) */ union lms_path switch (lms_algorithm_type type) { case lms_sha256_n32_h5: bytestring32 path_n32_h5[5]; case lms_sha256_n32_h10: bytestring32 path_n32_h10[10]; case lms_sha256_n32_h15: bytestring32 path_n32_h15[15]; case lms_sha256_n32_h20: bytestring32 path_n32_h20[20]; case lms_sha256_n32_h25: bytestring32 path_n32_h25[25]; default: void; /* error condition */ }; struct lms_signature { unsigned int q; lmots_signature lmots_sig; lms_path nodes; }; struct lms_key_n32 { lmots_algorithm_type ots_alg_type; opaque I[16]; opaque K[32]; }; union lms_public_key switch (lms_algorithm_type type) { case lms_sha256_n32_h5: case lms_sha256_n32_h10: case lms_sha256_n32_h15: case lms_sha256_n32_h20: case lms_sha256_n32_h25: lms_key_n32 z_n32; default: void; /* error condition */ }; /* hierarchical signature system (hss) */ struct hss_public_key { unsigned int L; lms_public_key pub; }; struct signed_public_key { lms_signature sig; lms_public_key pub; }; struct hss_signature { signed_public_key signed_keys<7>; lms_signature sig_of_message; }; 4. LM-OTS One-Time Signatures This section defines LM-OTS signatures. The signature is used to validate the authenticity of a message by associating a secret private key with a shared public key. These are one-time signatures; each private key MUST be used at most one time to sign any given As part of the signing process, a digest of the original message is computed using the cryptographic hash function H (see Section 4.1), and the resulting digest is signed. In order to facilitate its use in an N-time signature system, the LM-OTS key generation, signing, and verification algorithms all take as input parameters I and q. The parameter I is a 16-byte string that indicates which Merkle tree this LM-OTS is used with. The parameter q is a 32-bit integer that indicates the leaf of the Merkle tree where the OTS public key appears. These parameters are used as part of the security string, as listed in Section 7.1. When the LM-OTS signature system is used outside of an N-time signature system, the value I MAY be used to differentiate this one-time signature from others; however, the value q MUST be set to the all- zero value. 4.1. Parameters The signature system uses the parameters n and w, which are both positive integers. The algorithm description also makes use of the internal parameters p and ls, which are dependent on n and w. These parameters are summarized as follows: n : the number of bytes of the output of the hash function. w : the width (in bits) of the Winternitz coefficients; that is, the number of bits from the hash or checksum that is used with a single Winternitz chain. It is a member of the set { 1, 2, 4, 8 }. p : the number of n-byte string elements that make up the LM-OTS signature. This is a function of n and w; the values for the defined parameter sets are listed in Table 1; it can also be computed by the algorithm given in Appendix B. ls : the number of left-shift bits used in the checksum function Cksm (defined in Section 4.4). H : a second-preimage-resistant cryptographic hash function that accepts byte strings of any length and returns an n-byte string. For more background on the cryptographic security requirements for H, see Section 9. The value of n is determined by the hash function selected for use as part of the LM-OTS algorithm; the choice of this value has a strong effect on the security of the system. The parameter w determines the length of the Winternitz chains computed as a part of the OTS signature (which involve 2^w - 1 invocations of the hash function); it has little effect on security. Increasing w will shorten the signature, but at a cost of a larger computation to generate and verify a signature. The values of p and ls are dependent on the choices of the parameters n and w, as described in Appendix B. Table 1 illustrates various combinations of n, w, p and ls, along with the resulting signature length. The value of w describes a space/time trade-off; increasing the value of w will cause the signature to shrink (by decreasing the value of p) while increasing the amount of time needed to perform operations with it: generate the public key and generate and verify the signature. In general, the LM-OTS signature is 4+n*(p+1) bytes long, and public key generation will take p*(2^w - 1) + 1 hash computations (and signature generation and verification will take approximately half that on average). +---------------------+--------+----+---+-----+----+---------+ | Parameter Set Name | H | n | w | p | ls | sig_len | +---------------------+--------+----+---+-----+----+---------+ | LMOTS_SHA256_N32_W1 | SHA256 | 32 | 1 | 265 | 7 | 8516 | | | | | | | | | | LMOTS_SHA256_N32_W2 | SHA256 | 32 | 2 | 133 | 6 | 4292 | | | | | | | | | | LMOTS_SHA256_N32_W4 | SHA256 | 32 | 4 | 67 | 4 | 2180 | | | | | | | | | | LMOTS_SHA256_N32_W8 | SHA256 | 32 | 8 | 34 | 0 | 1124 | +---------------------+--------+----+---+-----+----+---------+ Table 1 Here SHA256 denotes the SHA-256 hash function defined in NIST standard [FIPS180]. 4.2. Private Key The format of the LM-OTS private key is an internal matter to the implementation, and this document does not attempt to define it. One possibility is that the private key may consist of a typecode indicating the particular LM-OTS algorithm, an array x[] containing p n-byte strings, and the 16-byte string I and the 4-byte string q. This private key MUST be used to sign (at most) one message. The following algorithm shows pseudocode for generating a private key. Algorithm 0: Generating a Private Key 1. Retrieve the values of q and I (the 16-byte identifier of the LMS public/private key pair) from the LMS tree that this LM-OTS private key will be used with 2. Set type to the typecode of the algorithm 3. Set n and p according to the typecode and Table 1 4. Compute the array x as follows: for ( i = 0; i < p; i = i + 1 ) { set x[i] to a uniformly random n-byte string } 5. Return u32str(type) || I || u32str(q) || x[0] || x[1] || ... || x[p-1] An implementation MAY use a pseudorandom method to compute x[i], as suggested in [Merkle79], page 46. The details of the pseudorandom method do not affect interoperability, but the cryptographic strength MUST match that of the LM-OTS algorithm. Appendix A provides an example of a pseudorandom method for computing the LM-OTS private key. 4.3. Public Key The LM-OTS public key is generated from the private key by iteratively applying the function H to each individual element of x, for 2^w - 1 iterations, then hashing all of the resulting values. The public key is generated from the private key using the following algorithm, or any equivalent process. Algorithm 1: Generating a One-Time Signature Public Key From a Private Key 1. Set type to the typecode of the algorithm 2. Set the integers n, p, and w according to the typecode and Table 1 3. Determine x, I, and q from the private key 4. Compute the string K as follows: for ( i = 0; i < p; i = i + 1 ) { tmp = x[i] for ( j = 0; j < 2^w - 1; j = j + 1 ) { tmp = H(I || u32str(q) || u16str(i) || u8str(j) || tmp) } y[i] = tmp } K = H(I || u32str(q) || u16str(D_PBLC) || y[0] || ... || y[p-1]) 5. Return u32str(type) || I || u32str(q) || K where D_PBLC is the fixed two-byte value 0x8080, which is used to distinguish the last hash from every other hash in this system. The public key is the value returned by Algorithm 1. 4.4. Checksum A checksum is used to ensure that any forgery attempt that manipulates the elements of an existing signature will be detected. This checksum is needed because an attacker can freely advance any of the Winternitz chains. That is, if this checksum were not present, then an attacker who could find a hash that has every digit larger than the valid hash could replace it (and adjust the Winternitz chains). The security property that the checksum provides is detailed in Section 9. The checksum function Cksm is defined as follows, where S denotes the n-byte string that is input to that function, and the value sum is a 16-bit unsigned integer: Algorithm 2: Checksum Calculation sum = 0 for ( i = 0; i < (n*8/w); i = i + 1 ) { sum = sum + (2^w - 1) - coef(S, i, w) } return (sum << ls) ls is the parameter that shifts the significant bits of the checksum into the positions that will actually be used by the coef function when encoding the digits of the checksum. The actual ls parameter is a function of the n and w parameters; the values for the currently defined parameter sets are shown in Table 1. It is calculated by the algorithm given in Appendix B. Because of the left-shift operation, the rightmost bits of the result of Cksm will often be zeros. Due to the value of p, these bits will not be used during signature generation or verification. 4.5. Signature Generation The LM-OTS signature of a message is generated by doing the following in sequence: prepending the LMS key identifier I, the LMS leaf identifier q, the value D_MESG (0x8181), and the randomizer C to the message; computing the hash; concatenating the checksum of the hash to the hash itself; considering the resulting value as a sequence of w-bit values; and using each of the w-bit values to determine the number of times to apply the function H to the corresponding element of the private key. The outputs of the function H are concatenated together and returned as the signature. The pseudocode for this procedure is shown below. Algorithm 3: Generating a One-Time Signature From a Private Key and a 1. Set type to the typecode of the algorithm 2. Set n, p, and w according to the typecode and Table 1 3. Determine x, I, and q from the private key 4. Set C to a uniformly random n-byte string 5. Compute the array y as follows: Q = H(I || u32str(q) || u16str(D_MESG) || C || message) for ( i = 0; i < p; i = i + 1 ) { a = coef(Q || Cksm(Q), i, w) tmp = x[i] for ( j = 0; j < a; j = j + 1 ) { tmp = H(I || u32str(q) || u16str(i) || u8str(j) || tmp) } y[i] = tmp } 6. Return u32str(type) || C || y[0] || ... || y[p-1] Note that this algorithm results in a signature whose elements are intermediate values of the elements computed by the public key algorithm in Section 4.3. The signature is the string returned by Algorithm 3. Section 3.3 formally defines the structure of the string as the lmots_signature union. 4.6. Signature Verification In order to verify a message with its signature (an array of n-byte strings, denoted as y), the receiver must "complete" the chain of iterations of H using the w-bit coefficients of the string resulting from the concatenation of the message hash and its checksum. This computation should result in a value that matches the provided public key. Algorithm 4a: Verifying a Signature and Message Using a Public Key 1. If the public key is not at least four bytes long, return INVALID. 2. Parse pubtype, I, q, and K from the public key as follows: a. pubtype = strTou32(first 4 bytes of public key) b. Set n according to the pubkey and Table 1; if the public key is not exactly 24 + n bytes long, return INVALID. c. I = next 16 bytes of public key d. q = strTou32(next 4 bytes of public key) e. K = next n bytes of public key 3. Compute the public key candidate Kc from the signature, message, pubtype, and the identifiers I and q obtained from the public key, using Algorithm 4b. If Algorithm 4b returns INVALID, then return INVALID. 4. If Kc is equal to K, return VALID; otherwise, return INVALID. Algorithm 4b: Computing a Public Key Candidate Kc from a Signature, Message, Signature Typecode pubtype, and Identifiers I, q 1. If the signature is not at least four bytes long, return INVALID. 2. Parse sigtype, C, and y from the signature as follows: a. sigtype = strTou32(first 4 bytes of signature) b. If sigtype is not equal to pubtype, return INVALID. c. Set n and p according to the pubtype and Table 1; if the signature is not exactly 4 + n * (p+1) bytes long, return INVALID. d. C = next n bytes of signature e. y[0] = next n bytes of signature y[1] = next n bytes of signature ... y[p-1] = next n bytes of signature 3. Compute the string Kc as follows: Q = H(I || u32str(q) || u16str(D_MESG) || C || message) for ( i = 0; i < p; i = i + 1 ) { a = coef(Q || Cksm(Q), i, w) tmp = y[i] for ( j = a; j < 2^w - 1; j = j + 1 ) { tmp = H(I || u32str(q) || u16str(i) || u8str(j) || tmp) } z[i] = tmp } Kc = H(I || u32str(q) || u16str(D_PBLC) || z[0] || z[1] || ... || z[p-1]) 4. Return Kc. 5. Leighton-Micali Signatures The Leighton-Micali Signature (LMS) method can sign a potentially large but fixed number of messages. An LMS system uses two cryptographic components: a one-time signature method and a hash function. Each LMS public/private key pair is associated with a perfect binary tree, each node of which contains an m-byte value, where m is the output length of the hash function. Each leaf of the tree contains the value of the public key of an LM-OTS public/private key pair. The value contained by the root of the tree is the LMS public key. Each interior node is computed by applying the hash function to the concatenation of the values of its children nodes. Each node of the tree is associated with a node number, an unsigned integer that is denoted as node_num in the algorithms below, which is computed as follows. The root node has node number 1; for each node with node number N < 2^h (where h is the height of the tree), its left child has node number 2*N, while its right child has node number 2*N + 1. The result of this is that each node within the tree will have a unique node number, and the leaves will have node numbers 2^h, (2^h)+1, (2^h)+2, ..., (2^h)+(2^h)-1. In general, the j-th node at level i has node number 2^i + j. The node number can conveniently be computed when it is needed in the LMS algorithms, as described in those algorithms. 5.1. Parameters An LMS system has the following parameters: h : the height of the tree m : the number of bytes associated with each node H : a second-preimage-resistant cryptographic hash function that accepts byte strings of any length and returns an m-byte string. There are 2^h leaves in the tree. The overall strength of LMS signatures is governed by the weaker of the hash function used within the LM-OTS and the hash function used within the LMS system. In order to minimize the risk, these two hash functions SHOULD be the same (so that an attacker could not take advantage of the weaker hash function choice). +--------------------+--------+----+----+ | Name | H | m | h | +--------------------+--------+----+----+ | LMS_SHA256_M32_H5 | SHA256 | 32 | 5 | | | | | | | LMS_SHA256_M32_H10 | SHA256 | 32 | 10 | | | | | | | LMS_SHA256_M32_H15 | SHA256 | 32 | 15 | | | | | | | LMS_SHA256_M32_H20 | SHA256 | 32 | 20 | | | | | | | LMS_SHA256_M32_H25 | SHA256 | 32 | 25 | +--------------------+--------+----+----+ Table 2 5.2. LMS Private Key The format of the LMS private key is an internal matter to the implementation, and this document does not attempt to define it. One possibility is that it may consist of an array OTS_PRIV[] of 2^h LM-OTS private keys and the leaf number q of the next LM-OTS private key that has not yet been used. The q-th element of OTS_PRIV[] is generated using Algorithm 0 with the identifiers I, q. The leaf number q is initialized to zero when the LMS private key is created. The process is as follows: Algorithm 5: Computing an LMS Private Key. 1. Determine h and m from the typecode and Table 2. 2. Set I to a uniformly random 16-byte string. 3. Compute the array OTS_PRIV[] as follows: for ( q = 0; q < 2^h; q = q + 1) { OTS_PRIV[q] = LM-OTS private key with identifiers I, q } 4. q = 0 An LMS private key MAY be generated pseudorandomly from a secret value; in this case, the secret value MUST be at least m bytes long and uniformly random and MUST NOT be used for any other purpose than the generation of the LMS private key. The details of how this process is done do not affect interoperability; that is, the public key verification operation is independent of these details. Appendix A provides an example of a pseudorandom method for computing an LMS private key. The signature-generation logic uses q as the next leaf to use; hence, step 4 starts it off at the leftmost leaf. Because the signature process increments q after the signature operation, the first signature will have q=0. 5.3. LMS Public Key An LMS public key is defined as follows, where we denote the public key final hash value (namely, the K value computed in Algorithm 1) associated with the i-th LM-OTS private key as OTS_PUB_HASH[i], with i ranging from 0 to (2^h)-1. Each instance of an LMS public/private key pair is associated with a balanced binary tree, and the nodes of that tree are indexed from 1 to 2^(h+1)-1. Each node is associated with an m-byte string. The string for the r-th node is denoted as T[r] and defined as if r >= 2^h: H(I||u32str(r)||u16str(D_LEAF)||OTS_PUB_HASH[r-2^h]) else H(I||u32str(r)||u16str(D_INTR)||T[2*r]||T[2*r+1]) where D_LEAF is the fixed two-byte value 0x8282 and D_INTR is the fixed two-byte value 0x8383, both of which are used to distinguish this hash from every other hash in this system. When we have r >= 2^h, then we are processing a leaf node (and thus hashing only a single LM-OTS public key). When we have r < 2^h, then we are processing an internal node -- that is, a node with two child nodes that we need to combine. The LMS public key can be represented as the byte string u32str(type) || u32str(otstype) || I || T[1] Section 3.3 specifies the format of the type variable. The value otstype is the parameter set for the LM-OTS public/private key pairs used. The value I is the private key identifier and is the value used for all computations for the same LMS tree. The value T[1] can be computed via recursive application of the above equation or by any equivalent method. An iterative procedure is outlined in Appendix C. 5.4. LMS Signature An LMS signature consists of the number q of the leaf associated with the LM-OTS signature, as a four-byte unsigned integer in network byte order, an LM-OTS signature, a typecode indicating the particular LMS algorithm, an array of h m-byte values that is associated with the path through the tree from the leaf associated with the LM-OTS signature to the root. Symbolically, the signature can be represented as u32str(q) || lmots_signature || u32str(type) || path[0] || path[1] || path[2] || ... || path[h-1] Section 3.3 formally defines the format of the signature as the lms_signature structure. The array for a tree with height h will have h values and contains the values of the siblings of (that is, is adjacent to) the nodes on the path from the leaf to the root, where the sibling to node A is the other node that shares node A's parent. In the signature, 0 is counted from the bottom level of the tree, and so path[0] is the value of the node adjacent to leaf node q; path[1] is the second-level node that is adjacent to leaf node q's parent, and so on up the tree until we get to path[h-1], which is the value of the next-to-the-top-level node whose branch the leaf node q does not reside in. Below is a simple example of the authentication path for h=3 and q=2. The leaf marked OTS is the one-time signature that is used to sign the actual message. The nodes on the path from the OTS public key to the root are marked with a *, while the nodes that are used within the path array are marked with **. The values in the path array are those nodes that are siblings of the nodes on the path; path[0] is the leaf** node that is adjacent to the OTS public key (which is the start of the path); path[1] is the T[4]** node that is the sibling of the second node T[5]* on the path, and path[2] is the T[3]** node that is the sibling of the third node T[2]* on the path. Root | --------------------------------- | | T[2]* T[3]** | | ------------------ ----------------- | | | | T[4]** T[5]* T[6] T[7] | | | | --------- ---------- -------- --------- | | | | | | | | leaf leaf OTS leaf** leaf leaf leaf leaf The idea behind this authentication path is that it allows us to validate the OTS hash with using h path array values and hash computations. What the verifier does is recompute the hashes up the path; first, it hashes the given OTS and path[0] value, giving a tentative T[5]' value. Then, it hashes its path[1] and tentative T[5]' value to get a tentative T[2]' value. Then, it hashes that and the path[2] value to get a tentative Root' value. If that value is the known public key of the Merkle tree, then we can assume that the value T[2]' it got was the correct T[2] value in the original tree, and so the T[5]' value it got was the correct T[5] value in the original tree, and so the OTS public key is the same as in the original and, hence, is correct. 5.4.1. LMS Signature Generation To compute the LMS signature of a message with an LMS private key, the signer first computes the LM-OTS signature of the message using the leaf number of the next unused LM-OTS private key. The leaf number q in the signature is set to the leaf number of the LMS private key that was used in the signature. Before releasing the signature, the leaf number q in the LMS private key MUST be incremented to prevent the LM-OTS private key from being used again. If the LMS private key is maintained in nonvolatile memory, then the implementation MUST ensure that the incremented value has been stored before releasing the signature. The issue this tries to prevent is a scenario where a) we generate a signature using one LM-OTS private key and release it to the application, b) before we update the nonvolatile memory, we crash, and c) we reboot and generate a second signature using the same LM-OTS private key. With two different signatures using the same LM-OTS private key, an attacker could potentially generate a forged signature of a third message. The array of node values in the signature MAY be computed in any way. There are many potential time/storage trade-offs that can be applied. The fastest alternative is to store all of the nodes of the tree and set the array in the signature by copying them; pseudocode to do so appears in Appendix D. The least storage-intensive alternative is to recompute all of the nodes for each signature. Note that the details of this procedure are not important for interoperability; it is not necessary to know any of these details in order to perform the signature-verification operation. The internal nodes of the tree need not be kept secret, and thus a node-caching scheme that stores only internal nodes can sidestep the need for strong protections. Several useful time/storage trade-offs are described in the "Small- Memory LM Schemes" section of [USPTO5432852]. 5.4.2. LMS Signature Verification An LMS signature is verified by first using the LM-OTS signature verification algorithm (Algorithm 4b) to compute the LM-OTS public key from the LM-OTS signature and the message. The value of that public key is then assigned to the associated leaf of the LMS tree, and then the root of the tree is computed from the leaf value and the array path[] as described in Algorithm 6 below. If the root value matches the public key, then the signature is valid; otherwise, the signature verification fails. Algorithm 6: LMS Signature Verification 1. If the public key is not at least eight bytes long, return INVALID. 2. Parse pubtype, I, and T[1] from the public key as follows: a. pubtype = strTou32(first 4 bytes of public key) b. ots_typecode = strTou32(next 4 bytes of public key) c. Set m according to pubtype, based on Table 2. d. If the public key is not exactly 24 + m bytes long, return INVALID. e. I = next 16 bytes of the public key f. T[1] = next m bytes of the public key 3. Compute the LMS Public Key Candidate Tc from the signature, message, identifier, pubtype, and ots_typecode, using Algorithm 6a. 4. If Tc is equal to T[1], return VALID; otherwise, return INVALID. Algorithm 6a: Computing an LMS Public Key Candidate from a Signature, Message, Identifier, and Algorithm Typecodes 1. If the signature is not at least eight bytes long, return INVALID. 2. Parse sigtype, q, lmots_signature, and path from the signature as follows: a. q = strTou32(first 4 bytes of signature) b. otssigtype = strTou32(next 4 bytes of signature) c. If otssigtype is not the OTS typecode from the public key, return INVALID. d. Set n, p according to otssigtype and Table 1; if the signature is not at least 12 + n * (p + 1) bytes long, return INVALID. e. lmots_signature = bytes 4 through 7 + n * (p + 1) of signature f. sigtype = strTou32(bytes 8 + n * (p + 1)) through 11 + n * (p + 1) of signature) g. If sigtype is not the LM typecode from the public key, return INVALID. h. Set m, h according to sigtype and Table 2. i. If q >= 2^h or the signature is not exactly 12 + n * (p + 1) + m * h bytes long, return INVALID. j. Set path as follows: path[0] = next m bytes of signature path[1] = next m bytes of signature ... path[h-1] = next m bytes of signature 3. Kc = candidate public key computed by applying Algorithm 4b to the signature lmots_signature, the message, and the identifiers I, q 4. Compute the candidate LMS root value Tc as follows: node_num = 2^h + q tmp = H(I || u32str(node_num) || u16str(D_LEAF) || Kc) i = 0 while (node_num > 1) { if (node_num is odd): tmp = H(I||u32str(node_num/2)||u16str(D_INTR)||path[i]||tmp) else: tmp = H(I||u32str(node_num/2)||u16str(D_INTR)||tmp||path[i]) node_num = node_num/2 i = i + 1 } Tc = tmp 5. Return Tc. 6. Hierarchical Signatures In scenarios where it is necessary to minimize the time taken by the public key generation process, the Hierarchical Signature System (HSS) can be used. This hierarchical scheme, which we describe in this section, uses the LMS scheme as a component. In HSS, we have a sequence of L LMS trees, where the public key for the first LMS tree is included in the public key of the HSS system, each LMS private key signs the next LMS public key, and the last LMS private key signs the actual message. For example, if we have a three-level hierarchy (L=3), then to sign a message, we would have: The first LMS private key (level 0) signs a level 1 LMS public key. The second LMS private key (level 1) signs a level 2 LMS public key. The third LMS private key (level 2) signs the message. The root of the level 0 LMS tree is contained in the HSS public key. To verify the LMS signature, we would verify all the signatures: We would verify that the level 1 LMS public key is correctly signed by the level 0 signature. We would verify that the level 2 LMS public key is correctly signed by the level 1 signature. We would verify that the message is correctly signed by the level 2 signature. We would accept the HSS signature only if all the signatures validated. During the signature-generation process, we sign messages with the lowest (level L-1) LMS tree. Once we have used all the leafs in that tree to sign messages, we would discard it, generate a fresh LMS tree, and sign it with the next (level L-2) LMS tree (and when that is used up, recursively generate and sign a fresh level L-2 LMS tree). HSS, in essence, utilizes a tree of LMS trees. There is a single LMS tree at level 0 (the root). Each LMS tree (actually, the private key corresponding to the LMS tree) at level i is used to sign 2^h objects (where h is the height of trees at level i). If i < L-1, then each object will be another LMS tree (actually, the public key) at level i+1; if i = L-1, we've reached the bottom of the HSS tree, and so each object will be a message from the application. The HSS public key contains the public key of the LMS tree at the root, and an HSS signature is associated with a path from the root of the HSS tree to the leaf. Compared to LMS, HSS has a much reduced public key generation time, as only the root tree needs to be generated prior to the distribution of the HSS public key. For example, an L=3 tree (with h=10 at each level) would have one level 0 LMS tree, 2^10 level 1 LMS trees (with each such level 1 public key signed by one of the 1024 level 0 OTS public keys), and 2^20 level 2 LMS trees. Only 1024 OTS public keys need to be computed to generate the HSS public key (as you need to compute only the level 0 LMS tree to compute that value; you can, of course, decide to compute the initial level 1 and level 2 LMS trees). In addition, the 2^20 level 2 LMS trees can jointly sign a total of over a billion messages. In contrast, a single LMS tree that could sign a billion messages would require a billion OTS public keys to be computed first (if h=30 were allowed in a supported parameter set). Each LMS tree within the hierarchy is associated with a distinct LMS public key, private key, signature, and identifier. The number of levels is denoted as L and is between one and eight, inclusive. The following notation is used, where i is an integer between 0 and L-1 inclusive, and the root of the hierarchy is level 0: prv[i] is the current LMS private key of the i-th level. pub[i] is the current LMS public key of the i-th level, as described in Section 5.3. sig[i] is the LMS signature of public key pub[i+1] generated using the private key prv[i]. It is expected that the above arrays are maintained for the course of the HSS key. The contents of the prv[] array MUST be kept private; the pub[] and sig[] array may be revealed should the implementation find that convenient. In this section, we say that an N-time private key is exhausted when it has generated N signatures; thus, it can no longer be used for For i > 0, the values prv[i], pub[i], and (for all values of i) sig[i] will be updated over time as private keys are exhausted and replaced by newer keys. When these key pairs are updated (or initially generated before the first message is signed), then the LMS key generation processes outlined in Sections 5.2 and 5.3 are performed. If the generated key pairs are for level i of the HSS hierarchy, then we store the public key in pub[i] and the private key in prv[i]. In addition, if i > 0, then we sign the generated public key with the LMS private key at level i-1, placing the signature into sig[i-1]. When the LMS key pair is generated, the key pair and the corresponding identifier MUST be generated independently of all other key pairs. HSS allows L=1, in which case the HSS public key and signature formats are essentially the LMS public key and signature formats, prepended by a fixed field. Since HSS with L=1 has very little overhead compared to LMS, all implementations MUST support HSS in order to maximize interoperability. We specifically allow different LMS levels to use different parameter sets. For example, the 0-th LMS public key (the root) may use the LMS_SHA256_M32_H15 parameter set, while the 1-th public key may use LMS_SHA256_M32_H10. There are practical reasons to allow this; for one, the signer may decide to store parts of the 0-th LMS tree (that it needs to construct while computing the public key) to accelerate later operations. As the 0-th tree is never updated, these internal nodes will never need to be recomputed. In addition, during the signature-generation operation, almost all the operations involved with updating the authentication path occur with the bottom (L-1th) LMS public key; hence, it may be useful to select the parameter set for that public key to have a shorter LMS tree. A close reading of the HSS verification pseudocode shows that it would allow the parameters of the nontop LMS public keys to change over time; for example, the signer might initially have the 1-th LMS public key use the LMS_SHA256_M32_H10 parameter set, but when that tree is exhausted, the signer might replace it with an LMS public key that uses the LMS_SHA256_M32_H15 parameter set. While this would work with the example verification pseudocode, the signer MUST NOT change the parameter sets for a specific level. This prohibition is to support verifiers that may keep state over the course of several signature verifications. 6.1. Key Generation The public key of the HSS scheme consists of the number of levels L, followed by pub[0], the public key of the top level. The HSS private key consists of prv[0], ... , prv[L-1], along with the associated pub[0], ... pub[L-1] and sig[0], ..., sig[L-2] values. As stated earlier, the values of the pub[] and sig[] arrays need not be kept secret and may be revealed. The value of pub[0] does not change (and, except for the index q, the value of prv[0] need not change); however, the values of pub[i] and prv[i] are dynamic for i > 0 and are changed by the signature-generation algorithm. During the key generation, the public and private keys are initialized. Here is some pseudocode that explains the key- generation logic: Algorithm 7: Generating an HSS Key Pair 1. Generate an LMS key pair, as specified in Sections 5.2 and 5.3, placing the private key into priv[0], and the public key into pub[0] 2. For i = 1 to L-1 do { generate an LMS key pair, placing the private key into priv[i] and the public key into pub[i] sig[i-1] = lms_signature( pub[i], priv[i-1] ) } 3. Return u32str(L) || pub[0] as the public key and the priv[], pub[], and sig[] arrays as the private key In the above algorithm, each LMS public/private key pair generated MUST be generated independently. Note that the value of the public key does not depend on the execution of step 2. As a result, an implementation may decide to delay step 2 until later -- for example, during the initial signature-generation operation. 6.2. Signature Generation To sign a message using an HSS key pair, the following steps are performed: If prv[L-1] is exhausted, then determine the smallest integer d such that all of the private keys prv[d], prv[d+1], ... , prv[L-1] are exhausted. If d is equal to zero, then the HSS key pair is exhausted, and it MUST NOT generate any more signatures. Otherwise, the key pairs for levels d through L-1 must be regenerated during the signature-generation process, as follows. For i from d to L-1, a new LMS public and private key pair with a new identifier is generated, pub[i] and prv[i] are set to those values, then the public key pub[i] is signed with prv[i-1], and sig[i-1] is set to the resulting value. The message is signed with prv[L-1], and the value sig[L-1] is set to that result. The value of the HSS signature is set as follows. We let signed_pub_key denote an array of octet strings, where signed_pub_key[i] = sig[i] || pub[i+1], for i between 0 and Nspk-1, inclusive, where Nspk = L-1 denotes the number of signed public keys. Then the HSS signature is u32str(Nspk) || signed_pub_key[0] || ... || signed_pub_key[Nspk-1] || sig[Nspk]. Note that the number of signed_pub_key elements in the signature is indicated by the value Nspk that appears in the initial four bytes of the signature. Here is some pseudocode of the above logic: Algorithm 8: Generating an HSS signature 1. If the message-signing key prv[L-1] is exhausted, regenerate that key pair, together with any parent key pairs that might be necessary. If the root key pair is exhausted, then the HSS key pair is exhausted and MUST NOT generate any more signatures. d = L while (prv[d-1].q == 2^(prv[d-1].h)) { d = d - 1 if (d == 0) return FAILURE } while (d < L) { create lms key pair pub[d], prv[d] sig[d-1] = lms_signature( pub[d], prv[d-1] ) d = d + 1 } 2. Sign the message. sig[L-1] = lms_signature( msg, prv[L-1] ) 3. Create the list of signed public keys. i = 0; while (i < L-1) { signed_pub_key[i] = sig[i] || pub[i+1] i = i + 1 } 4. Return u32str(L-1) || signed_pub_key[0] || ... || signed_pub_key[L-2] || sig[L-1] In the specific case of L=1, the format of an HSS signature is u32str(0) || sig[0] In the general case, the format of an HSS signature is u32str(Nspk) || signed_pub_key[0] || ... || signed_pub_key[Nspk-1] || sig[Nspk] which is equivalent to u32str(Nspk) || sig[0] || pub[1] || ... || sig[Nspk-1] || pub[Nspk] || sig[Nspk] 6.3. Signature Verification To verify a signature S and message using the public key pub, perform the following steps: The signature S is parsed into its components as follows: Nspk = strTou32(first four bytes of S) if Nspk+1 is not equal to the number of levels L in pub: return INVALID for (i = 0; i < Nspk; i = i + 1) { siglist[i] = next LMS signature parsed from S publist[i] = next LMS public key parsed from S } siglist[Nspk] = next LMS signature parsed from S key = pub for (i = 0; i < Nspk; i = i + 1) { sig = siglist[i] msg = publist[i] if (lms_verify(msg, key, sig) != VALID): return INVALID key = msg } return lms_verify(message, key, siglist[Nspk]) Since the length of an LMS signature cannot be known without parsing it, the HSS signature verification algorithm makes use of an LMS signature parsing routine that takes as input a string consisting of an LMS signature with an arbitrary string appended to it and returns both the LMS signature and the appended string. The latter is passed on for further processing. 6.4. Parameter Set Recommendations As for guidance as to the number of LMS levels and the size of each, any discussion of performance is implementation specific. In general, the sole drawback for a single LMS tree is the time it takes to generate the public key; as every LM-OTS public key needs to be generated, the time this takes can be substantial. For a two-level tree, only the top-level LMS tree and the initial bottom-level LMS tree need to be generated initially (before the first signature is generated); this will in general be significantly quicker. To give a general idea of the trade-offs available, we include some measurements taken with the LMS implementation available at <>, taken on a 3.3 GHz Xeon processor with threading enabled. We tried various parameter sets, all with W=8 (which minimizes signature size, while increasing time). These are here to give a guideline as to what's possible; for the computational time, your mileage may vary, depending on the computing resources you have. The machine these tests were performed on does not have the SHA-256 extensions; you could possibly do significantly better. +---------+------------+---------+-------------+ | ParmSet | KeyGenTime | SigSize | KeyLifetime | +---------+------------+---------+-------------+ | 15 | 6 sec | 1616 | 30 seconds | | | | | | | 20 | 3 min | 1776 | 16 minutes | | | | | | | 25 | 1.5 hour | 1936 | 9 hours | | | | | | | 15/10 | 6 sec | 3172 | 9 hours | | | | | | | 15/15 | 6 sec | 3332 | 12 days | | | | | | | 20/10 | 3 min | 3332 | 12 days | | | | | | | 20/15 | 3 min | 3492 | 1 year | | | | | | | 25/10 | 1.5 hour | 3492 | 1 year | | | | | | | 25/15 | 1.5 hour | 3652 | 34 years | +---------+------------+---------+-------------+ Table 3 ParmSet: this is the height of the Merkle tree(s); parameter sets listed as a single integer have L=1 and consist of a single Merkle tree of that height; parameter sets with L=2 are listed as x/y, with x being the height of the top-level Merkle tree and y being the bottom level. KeyGenTime: the measured key-generation time; that is, the time needed to generate the public/private key pair. SigSize: the size of a signature (in bytes) KeyLifetime: the lifetime of a key, assuming we generated 1000 signatures per second. In practice, we're not likely to get anywhere close to 1000 signatures per second sustained; if you have a more appropriate figure for your scenario, this column is easy to recompute. As for signature generation or verification times, those are moderately insensitive to the above parameter settings (except for the Winternitz setting and the number of Merkle trees for verification). Tests on the same machine (without multithreading) gave approximately 4 msec to sign a short message, 2.6 msec to verify; these tests used a two-level ParmSet; a single level would approximately halve the verification time. All times can be significantly improved (by perhaps a factor of 8) by using a parameter set with W=4; however, that also about doubles the signature size. 7. Rationale The goal of this note is to describe the LM-OTS, LMS, and HSS algorithms following the original references and present the modern security analysis of those algorithms. Other signature methods are out of scope and may be interesting follow-on work. We adopt the techniques described by Leighton and Micali to mitigate attacks that amortize their work over multiple invocations of the hash function. The values taken by the identifier I across different LMS public/ private key pairs are chosen randomly in order to improve security. The analysis of this method in [Fluhrer17] shows that we do not need uniqueness to ensure security; we do need to ensure that we don't have a large number of private keys that use the same I value. By randomly selecting 16-byte I values, the chance that, out of 2^64 private keys, 4 or more of them will use the same I value is negligible (that is, has probability less than 2^-128). The reason 16-byte I values were selected was to optimize the Winternitz hash-chain operation. With the current settings, the value being hashed is exactly 55 bytes long (for a 32-byte hash function), which SHA-256 can hash in a single hash-compression operation. Other hash functions may be used in future specifications; all the ones that we will be likely to support (SHA-512/256 and the various SHA-3 hashes) would work well with a 16-byte I value. The signature and public key formats are designed so that they are relatively easy to parse. Each format starts with a 32-bit enumeration value that indicates the details of the signature algorithm and provides all of the information that is needed in order to parse the format. The Checksum (Section 4.4) is calculated using a nonnegative integer "sum" whose width was chosen to be an integer number of w-bit fields such that it is capable of holding the difference of the total possible number of applications of the function H (as defined in the signing algorithm of Section 4.5) and the total actual number. In the case that the number of times H is applied is 0, the sum is (2^w - 1) * (8*n/w). Thus, for the purposes of this document, which describes signature methods based on H = SHA256 (n = 32 bytes) and w = { 1, 2, 4, 8 }, the sum variable is a 16-bit nonnegative integer for all combinations of n and w. The calculation uses the parameter ls defined in Section 4.1 and calculated in Appendix B, which indicates the number of bits used in the left-shift operation. 7.1. Security String To improve security against attacks that amortize their effort against multiple invocations of the hash function, Leighton and Micali introduced a "security string" that is distinct for each invocation of that function. Whenever this process computes a hash, the string being hashed will start with a string formed from the fields below. These fields will appear in fixed locations in the value we compute the hash of, and so we list where in the hash these fields would be present. The fields that make up this string are as follows: I A 16-byte identifier for the LMS public/private key pair. It MUST be chosen uniformly at random, or via a pseudorandom process, at the time that a key pair is generated, in order to minimize the probability that any specific value of I be used for a large number of different LMS private keys. This is always bytes 0-15 of the value being hashed. r In the LMS N-time signature scheme, the node number r associated with a particular node of a hash tree is used as an input to the hash used to compute that node. This value is represented as a 32-bit (four byte) unsigned integer in network byte order. Either r or q (depending on the domain-separation parameter) will be bytes 16-19 of the value being hashed. q In the LMS N-time signature scheme, each LM-OTS signature is associated with the leaf of a hash tree, and q is set to the leaf number. This ensures that a distinct value of q is used for each distinct LM-OTS public/private key pair. This value is represented as a 32-bit (four byte) unsigned integer in network byte order. Either r or q (depending on the domain- separation parameter) will be bytes 16-19 of the value being hashed. D A domain-separation parameter, which is a two-byte identifier that takes on different values in the different contexts in which the hash function is invoked. D occurs in bytes 20 and 21 of the value being hashed and takes on the following values: D_PBLC = 0x8080 when computing the hash of all of the iterates in the LM-OTS algorithm D_MESG = 0x8181 when computing the hash of the message in the LM-OTS algorithms D_LEAF = 0x8282 when computing the hash of the leaf of an LMS tree D_INTR = 0x8383 when computing the hash of an interior node of an LMS tree i A value between 0 and 264; this is used in the LM-OTS scheme when either computing the iterations of the Winternitz chain or using the suggested LM-OTS private key generation process. It is represented as a 16-bit (two-byte) unsigned integer in network byte order. If present, it occurs at bytes 20 and 21 of the value being hashed. j In the LM-OTS scheme, j is the iteration number used when the private key element is being iteratively hashed. It is represented as an 8-bit (one byte) unsigned integer and is present if i is a value between 0 and 264. If present, it occurs at bytes 22 to 21+n of the value being hashed. C An n-byte randomizer that is included with the message whenever it is being hashed to improve security. C MUST be chosen uniformly at random or via another unpredictable process. It is present if D=D_MESG, and it occurs at bytes 22 to 21+n of the value being hashed. 8. IANA Considerations IANA has created two registries: "LM-OTS Signatures", which includes all of the LM-OTS signatures as defined in Section 4, and "Leighton- Micali Signatures (LMS)" for LMS as defined in Section 5. Additions to these registries require that a specification be documented in an RFC or another permanent and readily available reference in sufficient detail that interoperability between independent implementations is possible [RFC8126]. IANA MUST verify that all applications for additions to these registries have first been reviewed by the IRTF Crypto Forum Research Group (CFRG). Each entry in either of the registries contains the following elements: a short name (Name), such as "LMS_SHA256_M32_H10", a positive number (Numeric Identifier), and a Reference to a specification that completely defines the signature-method test cases that can be used to verify the correctness of an implementation.8126]. The initial contents of the "LM-OTS Signatures" registry are as follows. +--------------------------+-----------+--------------------------+ | Name | Reference | Numeric Identifier | +--------------------------+-----------+--------------------------+ | Reserved | | 0x00000000 | | | | | | LMOTS_SHA256_N32_W1 | Section 4 | 0x00000001 | | | | | | LMOTS_SHA256_N32_W2 | Section 4 | 0x00000002 | | | | | | LMOTS_SHA256_N32_W4 | Section 4 | 0x00000003 | | | | | | LMOTS_SHA256_N32_W8 | Section 4 | 0x00000004 | | | | | | Unassigned | | 0x00000005 - 0xDDDDDDDC | | | | | | Reserved for Private Use | | 0xDDDDDDDD - 0xFFFFFFFF | +--------------------------+-----------+--------------------------+ Table 4 The initial contents of the "Leighton Micali Signatures (LMS)" registry are as follows. +--------------------------+-----------+--------------------------+ | Name | Reference | Numeric Identifier | +--------------------------+-----------+--------------------------+ | Reserved | | 0x0 - 0x4 | | | | | | LMS_SHA256_M32_H5 | Section 5 | 0x00000005 | | | | | | LMS_SHA256_M32_H10 | Section 5 | 0x00000006 | | | | | | LMS_SHA256_M32_H15 | Section 5 | 0x00000007 | | | | | | LMS_SHA256_M32_H20 | Section 5 | 0x00000008 | | | | | | LMS_SHA256_M32_H25 | Section 5 | 0x00000009 | | | | | | Unassigned | | 0x0000000A - 0xDDDDDDDC | | | | | | Reserved for Private Use | | 0xDDDDDDDD - 0xFFFFFFFF | +--------------------------+-----------+--------------------------+ Table 5 An IANA registration of a signature system does not constitute an endorsement of that system or its security. Currently, the two registries assign a disjoint set of values to the defined parameter sets. This coincidence is a historical accident; the correctness of the system does not depend on this. IANA is not required to maintain this situation. 9. Security Considerations The hash function H MUST have second preimage resistance: it must be computationally infeasible for an attacker that is given one message M to be able to find a second message M' such that H(M) = H(M'). The security goal of a signature system is to prevent forgeries. A successful forgery occurs when an attacker who does not know the private key associated with a public key can find a message (distinct from all previously signed ones) and signature that is valid with that public key (that is, the Signature Verification algorithm applied to that signature and message and public key will return VALID). Such an attacker, in the strongest case, may have the ability to forge valid signatures for an arbitrary number of other messages. LMS is provably secure in the random oracle model, as shown by [Katz16]. In addition, further analysis is done by [Fluhrer17], where the hash compression function (rather than the entire hash function) is considered to be a random oracle. Corollary 1 of the latter paper states: If we have no more than 2^64 randomly chosen LMS private keys, allow the attacker access to a signing oracle and a SHA-256 hash compression oracle, and allow a maximum of 2^120 hash compression computations, then the probability of an attacker being able to generate a single forgery against any of those LMS keys is less than 2^-129. Many of the objects within the public key and the signature start with a typecode. A verifier MUST check each of these typecodes, and a verification operation on a signature with an unknown type, or a type that does not correspond to the type within the public key, MUST return INVALID. The expected length of a variable-length object can be determined from its typecode; if an object has a different length, then any signature computed from the object is INVALID. 9.1. Hash Formats The format of the inputs to the hash function H has the property that each invocation of that function has an input that is repeated by a small bounded number of other inputs (due to potential repeats of the I value). In particular, it will vary somewhere in the first 23 bytes of the value being hashed. This property is important for a proof of security in the random oracle model. The formats used during key generation and signing (including the recommended pseudorandom key-generation procedure in Appendix A) are as follows: I || u32str(q) || u16str(i) || u8str(j) || tmp I || u32str(q) || u16str(D_PBLC) || y[0] || ... || y[p-1] I || u32str(q) || u16str(D_MESG) || C || message I || u32str(r) || u16str(D_LEAF) || OTS_PUB_HASH[r-2^h] I || u32str(r) || u16str(D_INTR) || T[2*r] || T[2*r+1] I || u32str(q) || u16str(i) || u8str(0xff) || SEED Each hash type listed is distinct; at locations 20 and 21 of the value being hashed, there exists either a fixed value D_PBLC, D_MESG, D_LEAF, D_INTR, or a 16-bit value i. These fixed values are distinct from each other and are large (over 32768), while the 16-bit values of i are small (currently no more than 265; possibly being slightly larger if larger hash functions are supported); hence, the range of possible values of i will not collide any of the D_PBLC, D_MESG, D_LEAF, D_INTR identifiers. The only other collision possibility is the Winternitz chain hash colliding with the recommended pseudorandom key-generation process; here, at location 22 of the value being hashed, the Winternitz chain function has the value u8str(j), where j is a value between 0 and 254, while location 22 of the recommended pseudorandom key-generation process has value 255. For the Winternitz chaining function, D_PBLC, and D_MESG, the value of I || u32str(q) is distinct for each LMS leaf (or equivalently, for each q value). For the Winternitz chaining function, the value of u16str(i) || u8str(j) is distinct for each invocation of H for a given leaf. For D_PBLC and D_MESG, the input format is used only once for each value of q and, thus, distinctness is assured. The formats for D_INTR and D_LEAF are used exactly once for each value of r, which ensures their distinctness. For the recommended pseudorandom key-generation process, for a given value of I, q and j are distinct for each invocation of H. The value of I is chosen uniformly at random from the set of all 128-bit strings. If 2^64 public keys are generated (and, hence, 2^64 random I values), there is a nontrivial probability of a duplicate (which would imply duplicate prefixes). However, there will be an extremely high probability there will not be a four-way collision (that is, any I value used for four distinct LMS keys; probability < 2^-132), and, hence, the number of repeats for any specific prefix will be limited to at most three. This is shown (in [Fluhrer17]) to have only a limited effect on the security of the system. 9.2. Stateful Signature Algorithm The LMS signature system, like all N-time signature systems, requires that the signer maintain state across different invocations of the signature systems are used more than once. This section calls out some important practical considerations around this statefulness. These issues are discussed in greater detail in [STMGMT]. In a typical computing environment, a private key will be stored in nonvolatile media such as on a hard drive. Before it is used to sign a message, it will be read into an application's Random-Access Memory (RAM). After a signature is generated, the value of the private key will need to be updated by writing the new value of the private key into nonvolatile storage. It is essential for security that the application ensures that this value is actually written into that storage, yet there may be one or more memory caches between it and the application. Memory caching is commonly done in the file system and in a physical memory unit on the hard disk that is dedicated to that purpose. To ensure that the updated value is written to physical media, the application may need to take several special steps. In a POSIX environment, for instance, the O_SYNC flag (for the open() system call) will cause invocations of the write() system call to block the calling process until the data has been written to the underlying hardware. However, if that hardware has its own memory cache, it must be separately dealt with using an operating system or device-specific tool such as hdparm to flush the on-drive cache or turn off write caching for that drive. Because these details vary across different operating systems and devices, this note does not attempt to provide complete guidance; instead, we call the implementer's attention to these issues. When hierarchical signatures are used, an easy way to minimize the private key synchronization issues is to have the private key for the second-level resident in RAM only and never write that value into nonvolatile memory. A new second-level public/private key pair will be generated whenever the application (re)starts; thus, failures such as a power outage or application crash are automatically accommodated. Implementations SHOULD use this approach wherever possible. 9.3. Security of LM-OTS Checksum To show the security of LM-OTS checksum, we consider the signature y of a message with a private key x and let h = H(message) and c = Cksm(H(message)) (see Section 4.5). To attempt a forgery, an attacker may try to change the values of h and c. Let h' and c' denote the values used in the forgery attempt. If for some integer j in the range 0 to u, where u = ceil(8*n/w) is the size of the range that the checksum value can cover, inclusive, a' = coef(h', j, w), a = coef(h, j, w), and a' > a then the attacker can compute F^a'(x[j]) from F^a(x[j]) = y[j] by iteratively applying function F to the j-th term of the signature an additional (a' - a) times. However, as a result of the increased number of hashing iterations, the checksum value c' will decrease from its original value of c. Thus, a valid signature's checksum will have, for some number k in the range u to (p-1), inclusive, b' = coef(c', k, w), b = coef(c, k, w), and b' < b Due to the one-way property of F, the attacker cannot easily compute F^b'(x[k]) from F^b(x[k]) = y[k]. 10. Comparison with Other Work The eXtended Merkle Signature Scheme (XMSS) is similar to HSS in several ways [XMSS][RFC8391]. Both are stateful hash-based signature schemes, and both use a hierarchical approach, with a Merkle tree at each level of the hierarchy. XMSS signatures are slightly shorter than HSS signatures, for equivalent security and an equal number of signatures. HSS has several advantages over XMSS. HSS operations are roughly four times faster than the comparable XMSS ones, when SHA256 is used as the underlying hash. This occurs because the hash operation done as a part of the Winternitz iterations dominates performance, and XMSS performs four compression-function invocations (two for the PRF, two for the F function) where HSS only needs to perform one. Additionally, HSS is somewhat simpler (as each hash invocation is just a prefix followed by the data being hashed). 11. References 11.1. Normative References [FIPS180] National Institute of Standards and Technology, "Secure Hash Standard (SHS)", FIPS PUB 180-4, DOI 10.6028/NIST.FIPS.180-4, March 2012. , <>. [USPTO5432852] Leighton, T. and S. Micali, "Large provably fast and secure digital signature schemes based on secure hash functions", U.S. Patent 5,432,852, July 1995. 11.2. Informative References [C:Merkle87] Merkle, R., "A Digital Signature Based on a Conventional Encryption Function", in Advances in Cryptology -- CRYPTO '87 Proceedings, Lecture Notes in Computer Science Vol. 293, DOI 10.1007/3-540-48184-2_32, 1988. [C:Merkle89a] Merkle, R., "A Certified Digital Signature", in Advances in Cryptology -- CRYPTO '89 Proceedings, Lecture Notes in Computer Science Vol. 435, DOI 10.1007/0-387-34805-0_21, 1990. [C:Merkle89b] Merkle, R., "One Way Hash Functions and DES", in Advances in Cryptology -- CRYPTO '89 Proceedings, Lecture Notes in Computer Science Vol. 435, DOI 10.1007/0-387-34805-0_40, 1990. [Fluhrer17] Fluhrer, S., "Further Analysis of a Proposed Hash-Based Signature Standard", Cryptology ePrint Archive Report 2017/553, 2017, <>. [Katz16] Katz, J., "Analysis of a Proposed Hash-Based Signature Standard", in SSR 2016: Security Standardisation Research (SSR) pp. 261-273, Lecture Notes in Computer Science Vol. 10074, DOI 10.1007/978-3-319-49100-4_12, 2016. [Merkle79] Merkle, R., "Secrecy, Authentication, and Public Key Systems", Technical Report No. 1979-1, Information Systems Laboratory, Stanford University, 1979, <>. [RFC8391] Huelsing, A., Butin, D., Gazdag, S., Rijneveld, J., and A. Mohaisen, "XMSS: eXtended Merkle Signature Scheme", RFC 8391, DOI 10.17487/RFC8391, May 2018, <>. [STMGMT] McGrew, D., Kampanakis, P., Fluhrer, S., Gazdag, S., Butin, D., and J. Buchmann, "State Management for Hash- Based Signatures.", in SSR 2016: Security Standardisation Research (SSR) pp. 244-260, Lecture Notes in Computer Science Vol. 10074, DOI 10.1007/978-3-319-49100-4_11, 2016. [XMSS] Buchmann, J., Dahmen, E., and , "XMSS -- A Practical Forward Secure Signature Scheme Based on Minimal Security Assumptions.", in PQCrypto 2011: Post-Quantum Cryptography pp. 117-129, Lecture Notes in Computer Science Vol. 7071, DOI 10.1007/978-3-642-25405-5_8, 2011. Appendix A. Pseudorandom Key Generation An implementation MAY use the following pseudorandom process for generating an LMS private key. SEED is an m-byte value that is generated uniformly at random at the start of the process, I is the LMS key pair identifier, q denotes the LMS leaf number of an LM-OTS private key, x_q denotes the x array of private elements in the LM-OTS private key with leaf number q, i is the index of the private key element, and H is the hash function used in LM-OTS. The elements of the LM-OTS private keys are computed as: x_q[i] = H(I || u32str(q) || u16str(i) || u8str(0xff) || SEED). This process stretches the m-byte random value SEED into a (much larger) set of pseudorandom values, using a unique counter in each invocation of H. The format of the inputs to H are chosen so that they are distinct from all other uses of H in LMS and LM-OTS. A careful reader will note that this is similar to the hash we perform when iterating through the Winternitz chain; however, in that chain, the iteration index will vary between 0 and 254 maximum (for W=8), while the corresponding value in this formula is 255. This algorithm is included in the proof of security in [Fluhrer17] and hence this method is safe when used within the LMS system; however, any other cryptographically secure method of generating private keys would also be safe. Appendix B. LM-OTS Parameter Options The LM-OTS one-time signature method uses several internal parameters, which are a function of the selected parameter set. These internal parameters include the following: p This is the number of independent Winternitz chains used in the signature; it will be the number of w-bit digits needed to hold the n-bit hash (u in the below equations), along with the number of digits needed to hold the checksum (v in the below equations) ls This is the size of the shift needed to move the checksum so that it appears in the checksum digits ls is needed because, while we express the checksum internally as a 16-bit value, we don't always express all 16 bits in the signature; for example, if w=4, we might use only the top 12 bits. Because we read the checksum in network order, this means that, without the shift, we'll use the higher-order bits (which may be always 0) and omit the lower-order bits (where the checksum value actually resides). This shift is here to ensure that the parts of the checksum we need to express (for security) actually contribute to the signature; when multiple such shifts are possible, we take the minimal value. The parameters ls and p are computed as follows: u = ceil(8*n/w) v = ceil((floor(lg((2^w - 1) * u)) + 1) / w) ls = 16 - (v * w) p = u + v Here, u and v represent the number of w-bit fields required to contain the hash of the message and the checksum byte strings, respectively. And as the value of p is the number of w-bit elements of ( H(message) || Cksm(H(message)) ), it is also equivalently the number of byte strings that form the private key and the number of byte strings in the signature. The value 16 in the ls computation of ls corresponds to the 16-bit value used for the sum variable in Algorithm 2 in Section 4.4 A table illustrating various combinations of n and w with the associated values of u, v, ls, and p is provided in Table 6. +---------+------------+-----------+-----------+-------+------------+ | Hash | Winternitz | w-bit | w-bit | Left | Total | | Length | Parameter | Elements | Elements | Shift | Number of | | in | (w) | in Hash | in | (ls) | w-bit | | Bytes | | (u) | Checksum | | Elements | | (n) | | | (v) | | (p) | +---------+------------+-----------+-----------+-------+------------+ | 32 | 1 | 256 | 9 | 7 | 265 | | | | | | | | | 32 | 2 | 128 | 5 | 6 | 133 | | | | | | | | | 32 | 4 | 64 | 3 | 4 | 67 | | | | | | | | | 32 | 8 | 32 | 2 | 0 | 34 | +---------+------------+-----------+-----------+-------+------------+ Table 6 Appendix C. An Iterative Algorithm for Computing an LMS Public Key The LMS public key can be computed using the following algorithm or any equivalent method. The algorithm uses a stack of hashes for data. It also makes use of a hash function with the typical init/update/final interface to hash functions; the result of the invocations hash_init(), hash_update(N[1]), hash_update(N[2]), ... , hash_update(N[n]), v = hash_final(), in that order, is identical to that of the invocation of H(N[1] || N[2] || ... || N[n]). Generating an LMS Public Key from an LMS Private Key for ( i = 0; i < 2^h; i = i + 1 ) { r = i + num_lmots_keys; temp = H(I || u32str(r) || u16str(D_LEAF) || OTS_PUB_HASH[i]) j = i; while (j % 2 == 1) { r = (r - 1)/2; j = (j-1) / 2; left_side = pop(data stack); temp = H(I || u32str(r) || u16str(D_INTR) || left_side || temp) } push temp onto the data stack } public_key = pop(data stack) Note that this pseudocode expects that all 2^h leaves of the tree have equal depth -- that is, it expects num_lmots_keys to be a power of 2. The maximum depth of the stack will be h-1 elements -- that is, a total of (h-1)*n bytes; for the currently defined parameter sets, this will never be more than 768 bytes of data. Appendix D. Method for Deriving Authentication Path for a Signature The LMS signature consists of u32str(q) || lmots_signature || u32str(type) || path[0] || path[1] || ... || path[h-1]. This appendix shows one method of constructing this signature, assuming that the implementation has stored the T[] array that was used to construct the public key. Note that this is not the only possible method; other methods exist that don't assume that you have the entire T[] array in memory. To construct a signature, you perform the following algorithm: Generating an LMS Signature 1. Set type to the typecode of the LMS algorithm. 2. Extract h from the typecode, according to Table 2. 3. Create the LM-OTS signature for the message: ots_signature = lmots_sign(message, LMS_PRIV[q]) 4. Compute the array path as follows: i = 0 r = 2^h + q while (i < h) { temp = (r / 2^i) xor 1 path[i] = T[temp] i = i + 1 } 5. S = u32str(q) || ots_signature || u32str(type) || path[0] || path[1] || ... || path[h-1] 6. q = q + 1 7. Return S. Here "xor" is the bitwise exclusive-or operation, and / is integer division (that is, rounded down to an integer value). Appendix E. Example Implementation An example implementation can be found online at <>. Appendix F. Test Cases This section provides test cases that can be used to verify or debug an implementation. This data is formatted with the name of the elements on the left and the hexadecimal value of the elements on the right. The concatenation of all of the values within a public key or signature produces that public key or signature, and values that do not fit within a single line are listed across successive lines. Test Case 1 Public Key -------------------------------------------- HSS public key levels 00000002 -------------------------------------------- LMS type 00000005 # LM_SHA256_M32_H5 LMOTS type 00000004 # LMOTS_SHA256_N32_W8 I 61a5d57d37f5e46bfb7520806b07a1b8 K 50650e3b31fe4a773ea29a07f09cf2ea 30e579f0df58ef8e298da0434cb2b878 -------------------------------------------- -------------------------------------------- Test Case 1 Message -------------------------------------------- Message 54686520706f77657273206e6f742064 |The powers not d| 656c65676174656420746f2074686520 |elegated to the | 556e6974656420537461746573206279 |United States by| 2074686520436f6e737469747574696f | the Constitutio| 6e2c206e6f722070726f686962697465 |n, nor prohibite| 6420627920697420746f207468652053 |d by it to the S| 74617465732c20617265207265736572 |tates, are reser| 76656420746f20746865205374617465 |ved to the State| 7320726573706563746976656c792c20 |s respectively, | 6f7220746f207468652070656f706c65 |or to the people| 2e0a |..| -------------------------------------------- Test Case 1 Signature -------------------------------------------- HSS signature Nspk 00000001 sig[0]: -------------------------------------------- LMS signature q 00000005 -------------------------------------------- LMOTS signature LMOTS type 00000004 # LMOTS_SHA256_N32_W8 C d32b56671d7eb98833c49b433c272586 bc4a1c8a8970528ffa04b966f9426eb9 y[0] 965a25bfd37f196b9073f3d4a232feb6 9128ec45146f86292f9dff9610a7bf95 y[1] a64c7f60f6261a62043f86c70324b770 7f5b4a8a6e19c114c7be866d488778a0 y[2] e05fd5c6509a6e61d559cf1a77a970de 927d60c70d3de31a7fa0100994e162a2 y[3] 582e8ff1b10cd99d4e8e413ef469559f 7d7ed12c838342f9b9c96b83a4943d16 y[4] 81d84b15357ff48ca579f19f5e71f184 66f2bbef4bf660c2518eb20de2f66e3b y[5] 14784269d7d876f5d35d3fbfc7039a46 2c716bb9f6891a7f41ad133e9e1f6d95 y[6] 60b960e7777c52f060492f2d7c660e14 71e07e72655562035abc9a701b473ecb y[7] c3943c6b9c4f2405a3cb8bf8a691ca51 d3f6ad2f428bab6f3a30f55dd9625563 y[8] f0a75ee390e385e3ae0b906961ecf41a e073a0590c2eb6204f44831c26dd768c y[9] 35b167b28ce8dc988a3748255230cef9 9ebf14e730632f27414489808afab1d1 y[10] e783ed04516de012498682212b078105 79b250365941bcc98142da13609e9768 y[11] aaf65de7620dabec29eb82a17fde35af 15ad238c73f81bdb8dec2fc0e7f93270 y[12] 1099762b37f43c4a3c20010a3d72e2f6 06be108d310e639f09ce7286800d9ef8 y[13] a1a40281cc5a7ea98d2adc7c7400c2fe 5a101552df4e3cccfd0cbf2ddf5dc677 y[14] 9cbbc68fee0c3efe4ec22b83a2caa3e4 8e0809a0a750b73ccdcf3c79e6580c15 y[15] 4f8a58f7f24335eec5c5eb5e0cf01dcf 4439424095fceb077f66ded5bec73b27 y[16] c5b9f64a2a9af2f07c05e99e5cf80f00 252e39db32f6c19674f190c9fbc506d8 y[17] 26857713afd2ca6bb85cd8c107347552 f30575a5417816ab4db3f603f2df56fb y[18] c413e7d0acd8bdd81352b2471fc1bc4f 1ef296fea1220403466b1afe78b94f7e y[19] cf7cc62fb92be14f18c2192384ebceaf 8801afdf947f698ce9c6ceb696ed70e9 y[20] e87b0144417e8d7baf25eb5f70f09f01 6fc925b4db048ab8d8cb2a661ce3b57a y[21] da67571f5dd546fc22cb1f97e0ebd1a6 5926b1234fd04f171cf469c76b884cf3 y[22] 115cce6f792cc84e36da58960c5f1d76 0f32c12faef477e94c92eb75625b6a37 y[23] 1efc72d60ca5e908b3a7dd69fef02491 50e3eebdfed39cbdc3ce9704882a2072 y[24] c75e13527b7a581a556168783dc1e975 45e31865ddc46b3c957835da252bb732 y[25] 8d3ee2062445dfb85ef8c35f8e1f3371 af34023cef626e0af1e0bc017351aae2 y[26] ab8f5c612ead0b729a1d059d02bfe18e fa971b7300e882360a93b025ff97e9e0 y[27] eec0f3f3f13039a17f88b0cf808f4884 31606cb13f9241f40f44e537d302c64a y[28] 4f1f4ab949b9feefadcb71ab50ef27d6 d6ca8510f150c85fb525bf25703df720 y[29] 9b6066f09c37280d59128d2f0f637c7d 7d7fad4ed1c1ea04e628d221e3d8db77 y[30] b7c878c9411cafc5071a34a00f4cf077 38912753dfce48f07576f0d4f94f42c6 y[31] d76f7ce973e9367095ba7e9a3649b7f4 61d9f9ac1332a4d1044c96aefee67676 y[32] 401b64457c54d65fef6500c59cdfb69a f7b6dddfcb0f086278dd8ad0686078df y[33] b0f3f79cd893d314168648499898fbc0 ced5f95b74e8ff14d735cdea968bee74 -------------------------------------------- LMS type 00000005 # LM_SHA256_M32_H5 path[0] d8b8112f9200a5e50c4a262165bd342c d800b8496810bc716277435ac376728d path[1] 129ac6eda839a6f357b5a04387c5ce97 382a78f2a4372917eefcbf93f63bb591 path[2] 12f5dbe400bd49e4501e859f885bf073 6e90a509b30a26bfac8c17b5991c157e path[3] b5971115aa39efd8d564a6b90282c316 8af2d30ef89d51bf14654510a12b8a14 path[4] 4cca1848cf7da59cc2b3d9d0692dd2a2 0ba3863480e25b1b85ee860c62bf5136 -------------------------------------------- LMS public key LMS type 00000005 # LM_SHA256_M32_H5 LMOTS type 00000004 # LMOTS_SHA256_N32_W8 I d2f14ff6346af964569f7d6cb880a1b6 K 6c5004917da6eafe4d9ef6c6407b3db0 e5485b122d9ebe15cda93cfec582d7ab -------------------------------------------- final_signature: -------------------------------------------- LMS signature q 0000000a -------------------------------------------- LMOTS signature LMOTS type 00000004 # LMOTS_SHA256_N32_W8 C 0703c491e7558b35011ece3592eaa5da 4d918786771233e8353bc4f62323185c y[0] 95cae05b899e35dffd71705470620998 8ebfdf6e37960bb5c38d7657e8bffeef y[1] 9bc042da4b4525650485c66d0ce19b31 7587c6ba4bffcc428e25d08931e72dfb y[2] 6a120c5612344258b85efdb7db1db9e1 865a73caf96557eb39ed3e3f426933ac y[3] 9eeddb03a1d2374af7bf771855774562 37f9de2d60113c23f846df26fa942008 y[4] a698994c0827d90e86d43e0df7f4bfcd b09b86a373b98288b7094ad81a0185ac y[5] 100e4f2c5fc38c003c1ab6fea479eb2f 5ebe48f584d7159b8ada03586e65ad9c y[6] 969f6aecbfe44cf356888a7b15a3ff07 4f771760b26f9c04884ee1faa329fbf4 y[7] e61af23aee7fa5d4d9a5dfcf43c4c26c e8aea2ce8a2990d7ba7b57108b47dabf y[8] beadb2b25b3cacc1ac0cef346cbb90fb 044beee4fac2603a442bdf7e507243b7 y[9] 319c9944b1586e899d431c7f91bcccc8 690dbf59b28386b2315f3d36ef2eaa3c y[10] f30b2b51f48b71b003dfb08249484201 043f65f5a3ef6bbd61ddfee81aca9ce6 y[11] 0081262a00000480dcbc9a3da6fbef5c 1c0a55e48a0e729f9184fcb1407c3152 y[12] 9db268f6fe50032a363c9801306837fa fabdf957fd97eafc80dbd165e435d0e2 y[13] dfd836a28b354023924b6fb7e48bc0b3 ed95eea64c2d402f4d734c8dc26f3ac5 y[14] 91825daef01eae3c38e3328d00a77dc6 57034f287ccb0f0e1c9a7cbdc828f627 y[15] 205e4737b84b58376551d44c12c3c215 c812a0970789c83de51d6ad787271963 y[16] 327f0a5fbb6b5907dec02c9a90934af5 a1c63b72c82653605d1dcce51596b3c2 y[17] b45696689f2eb382007497557692caac 4d57b5de9f5569bc2ad0137fd47fb47e y[18] 664fcb6db4971f5b3e07aceda9ac130e 9f38182de994cff192ec0e82fd6d4cb7 y[19] f3fe00812589b7a7ce51544045643301 6b84a59bec6619a1c6c0b37dd1450ed4 y[20] f2d8b584410ceda8025f5d2d8dd0d217 6fc1cf2cc06fa8c82bed4d944e71339e y[21] ce780fd025bd41ec34ebff9d4270a322 4e019fcb444474d482fd2dbe75efb203 y[22] 89cc10cd600abb54c47ede93e08c114e db04117d714dc1d525e11bed8756192f y[23] 929d15462b939ff3f52f2252da2ed64d 8fae88818b1efa2c7b08c8794fb1b214 y[24] aa233db3162833141ea4383f1a6f120b e1db82ce3630b3429114463157a64e91 y[25] 234d475e2f79cbf05e4db6a9407d72c6 bff7d1198b5c4d6aad2831db61274993 y[26] 715a0182c7dc8089e32c8531deed4f74 31c07c02195eba2ef91efb5613c37af7 y[27] ae0c066babc69369700e1dd26eddc0d2 16c781d56e4ce47e3303fa73007ff7b9 y[28] 49ef23be2aa4dbf25206fe45c20dd888 395b2526391a724996a44156beac8082 y[29] 12858792bf8e74cba49dee5e8812e019 da87454bff9e847ed83db07af3137430 y[30] 82f880a278f682c2bd0ad6887cb59f65 2e155987d61bbf6a88d36ee93b6072e6 y[31] 656d9ccbaae3d655852e38deb3a2dcf8 058dc9fb6f2ab3d3b3539eb77b248a66 y[32] 1091d05eb6e2f297774fe6053598457c c61908318de4b826f0fc86d4bb117d33 y[33] e865aa805009cc2918d9c2f840c4da43 a703ad9f5b5806163d7161696b5a0adc -------------------------------------------- LMS type 00000005 # LM_SHA256_M32_H5 path[0] d5c0d1bebb06048ed6fe2ef2c6cef305 b3ed633941ebc8b3bec9738754cddd60 path[1] e1920ada52f43d055b5031cee6192520 d6a5115514851ce7fd448d4a39fae2ab path[2] 2335b525f484e9b40d6a4a969394843b dcf6d14c48e8015e08ab92662c05c6e9 path[3] f90b65a7a6201689999f32bfd368e5e3 ec9cb70ac7b8399003f175c40885081a path[4] 09ab3034911fe125631051df0408b394 6b0bde790911e8978ba07dd56c73e7ee Test Case 2 Private Key -------------------------------------------- (note: procedure in Appendix A is used) Top level LMS tree SEED 558b8966c48ae9cb898b423c83443aae 014a72f1b1ab5cc85cf1d892903b5439 I d08fabd4a2091ff0a8cb4ed834e74534 Second level LMS tree SEED a1c4696e2608035a886100d05cd99945 eb3370731884a8235e2fb3d4d71f2547 I 215f83b7ccb9acbcd08db97b0d04dc2b -------------------------------------------- -------------------------------------------- Test Case 2 Public Key -------------------------------------------- HSS public key levels 00000002 -------------------------------------------- LMS type 00000006 # LM_SHA256_M32_H10 LMOTS type 00000003 # LMOTS_SHA256_N32_W4 I d08fabd4a2091ff0a8cb4ed834e74534 K 32a58885cd9ba0431235466bff9651c6 c92124404d45fa53cf161c28f1ad5a8e -------------------------------------------- -------------------------------------------- Test Case 2 Message -------------------------------------------- Message 54686520656e756d65726174696f6e20 |The enumeration | 696e2074686520436f6e737469747574 |in the Constitut| 696f6e2c206f66206365727461696e20 |ion, of certain | 7269676874732c207368616c6c206e6f |rights, shall no| 7420626520636f6e7374727565642074 |t be construed t| 6f2064656e79206f7220646973706172 |o deny or dispar| 616765206f7468657273207265746169 |age others retai| 6e6564206279207468652070656f706c |ned by the peopl| 652e0a |e..| -------------------------------------------- Test Case 2 Signature -------------------------------------------- HSS signature Nspk 00000001 sig[0]: -------------------------------------------- LMS signature q 00000003 -------------------------------------------- LMOTS signature LMOTS type 00000003 # LMOTS_SHA256_N32_W4 C 3d46bee8660f8f215d3f96408a7a64cf 1c4da02b63a55f62c666ef5707a914ce y[0] 0674e8cb7a55f0c48d484f31f3aa4af9 719a74f22cf823b94431d01c926e2a76 y[1] bb71226d279700ec81c9e95fb11a0d10 d065279a5796e265ae17737c44eb8c59 y[2] 4508e126a9a7870bf4360820bdeb9a01 d9693779e416828e75bddd7d8c70d50a y[3] 0ac8ba39810909d445f44cb5bb58de73 7e60cb4345302786ef2c6b14af212ca1 y[4] 9edeaa3bfcfe8baa6621ce88480df237 1dd37add732c9de4ea2ce0dffa53c926 y[5] 49a18d39a50788f4652987f226a1d481 68205df6ae7c58e049a25d4907edc1aa y[6] 90da8aa5e5f7671773e941d805536021 5c6b60dd35463cf2240a9c06d694e9cb y[7] 54e7b1e1bf494d0d1a28c0d31acc7516 1f4f485dfd3cb9578e836ec2dc722f37 y[8] ed30872e07f2b8bd0374eb57d22c614e 09150f6c0d8774a39a6e168211035dc5 y[9] 2988ab46eaca9ec597fb18b4936e66ef 2f0df26e8d1e34da28cbb3af75231372 y[10] 0c7b345434f72d65314328bbb030d0f0 f6d5e47b28ea91008fb11b05017705a8 y[11] be3b2adb83c60a54f9d1d1b2f476f9e3 93eb5695203d2ba6ad815e6a111ea293 y[12] dcc21033f9453d49c8e5a6387f588b1e a4f706217c151e05f55a6eb7997be09d y[13] 56a326a32f9cba1fbe1c07bb49fa04ce cf9df1a1b815483c75d7a27cc88ad1b1 y[14] 238e5ea986b53e087045723ce16187ed a22e33b2c70709e53251025abde89396 y[15] 45fc8c0693e97763928f00b2e3c75af3 942d8ddaee81b59a6f1f67efda0ef81d y[16] 11873b59137f67800b35e81b01563d18 7c4a1575a1acb92d087b517a8833383f y[17] 05d357ef4678de0c57ff9f1b2da61dfd e5d88318bcdde4d9061cc75c2de3cd47 y[18] 40dd7739ca3ef66f1930026f47d9ebaa 713b07176f76f953e1c2e7f8f271a6ca y[19] 375dbfb83d719b1635a7d8a138919579 44b1c29bb101913e166e11bd5f34186f y[20] a6c0a555c9026b256a6860f4866bd6d0 b5bf90627086c6149133f8282ce6c9b3 y[21] 622442443d5eca959d6c14ca8389d12c 4068b503e4e3c39b635bea245d9d05a2 y[22] 558f249c9661c0427d2e489ca5b5dde2 20a90333f4862aec793223c781997da9 y[23] 8266c12c50ea28b2c438e7a379eb106e ca0c7fd6006e9bf612f3ea0a454ba3bd y[24] b76e8027992e60de01e9094fddeb3349 883914fb17a9621ab929d970d101e45f y[25] 8278c14b032bcab02bd15692d21b6c5c 204abbf077d465553bd6eda645e6c306 y[26] 5d33b10d518a61e15ed0f092c3222628 1a29c8a0f50cde0a8c66236e29c2f310 y[27] a375cebda1dc6bb9a1a01dae6c7aba8e bedc6371a7d52aacb955f83bd6e4f84d y[28] 2949dcc198fb77c7e5cdf6040b0f84fa f82808bf985577f0a2acf2ec7ed7c0b0 y[29] ae8a270e951743ff23e0b2dd12e9c3c8 28fb5598a22461af94d568f29240ba28 y[30] 20c4591f71c088f96e095dd98beae456 579ebbba36f6d9ca2613d1c26eee4d8c y[31] 73217ac5962b5f3147b492e8831597fd 89b64aa7fde82e1974d2f6779504dc21 y[32] 435eb3109350756b9fdabe1c6f368081 bd40b27ebcb9819a75d7df8bb07bb05d y[33] b1bab705a4b7e37125186339464ad8fa aa4f052cc1272919fde3e025bb64aa8e y[34] 0eb1fcbfcc25acb5f718ce4f7c2182fb 393a1814b0e942490e52d3bca817b2b2 y[35] 6e90d4c9b0cc38608a6cef5eb153af08 58acc867c9922aed43bb67d7b33acc51 y[36] 9313d28d41a5c6fe6cf3595dd5ee63f0 a4c4065a083590b275788bee7ad875a7 y[37] f88dd73720708c6c6c0ecf1f43bbaada e6f208557fdc07bd4ed91f88ce4c0de8 y[38] 42761c70c186bfdafafc444834bd3418 be4253a71eaf41d718753ad07754ca3e y[39] ffd5960b0336981795721426803599ed 5b2b7516920efcbe32ada4bcf6c73bd2 y[40] 9e3fa152d9adeca36020fdeeee1b7395 21d3ea8c0da497003df1513897b0f547 y[41] 94a873670b8d93bcca2ae47e64424b74 23e1f078d9554bb5232cc6de8aae9b83 y[42] fa5b9510beb39ccf4b4e1d9c0f19d5e1 7f58e5b8705d9a6837a7d9bf99cd1338 y[43] 7af256a8491671f1f2f22af253bcff54 b673199bdb7d05d81064ef05f80f0153 y[44] d0be7919684b23da8d42ff3effdb7ca0 985033f389181f47659138003d712b5e y[45] c0a614d31cc7487f52de8664916af79c 98456b2c94a8038083db55391e347586 y[46] 2250274a1de2584fec975fb09536792c fbfcf6192856cc76eb5b13dc4709e2f7 y[47] 301ddff26ec1b23de2d188c999166c74 e1e14bbc15f457cf4e471ae13dcbdd9c y[48] 50f4d646fc6278e8fe7eb6cb5c94100f a870187380b777ed19d7868fd8ca7ceb y[49] 7fa7d5cc861c5bdac98e7495eb0a2cee c1924ae979f44c5390ebedddc65d6ec1 y[50] 1287d978b8df064219bc5679f7d7b264 a76ff272b2ac9f2f7cfc9fdcfb6a5142 y[51] 8240027afd9d52a79b647c90c2709e06 0ed70f87299dd798d68f4fadd3da6c51 y[52] d839f851f98f67840b964ebe73f8cec4 1572538ec6bc131034ca2894eb736b3b y[53] da93d9f5f6fa6f6c0f03ce43362b8414 940355fb54d3dfdd03633ae108f3de3e y[54] bc85a3ff51efeea3bc2cf27e1658f178 9ee612c83d0f5fd56f7cd071930e2946 y[55] beeecaa04dccea9f97786001475e0294 bc2852f62eb5d39bb9fbeef75916efe4 y[56] 4a662ecae37ede27e9d6eadfdeb8f8b2 b2dbccbf96fa6dbaf7321fb0e701f4d4 y[57] 29c2f4dcd153a2742574126e5eaccc77 686acf6e3ee48f423766e0fc466810a9 y[58] 05ff5453ec99897b56bc55dd49b99114 2f65043f2d744eeb935ba7f4ef23cf80 y[59] cc5a8a335d3619d781e7454826df720e ec82e06034c44699b5f0c44a8787752e y[60] 057fa3419b5bb0e25d30981e41cb1361 322dba8f69931cf42fad3f3bce6ded5b y[61] 8bfc3d20a2148861b2afc14562ddd27f 12897abf0685288dcc5c4982f8260268 y[62] 46a24bf77e383c7aacab1ab692b29ed8 c018a65f3dc2b87ff619a633c41b4fad y[63] b1c78725c1f8f922f6009787b1964247 df0136b1bc614ab575c59a16d089917b y[64] d4a8b6f04d95c581279a139be09fcf6e 98a470a0bceca191fce476f9370021cb y[65] c05518a7efd35d89d8577c990a5e1996 1ba16203c959c91829ba7497cffcbb4b y[66] 294546454fa5388a23a22e805a5ca35f 956598848bda678615fec28afd5da61a -------------------------------------------- LMS type 00000006 # LM_SHA256_M32_H10 path[0] b326493313053ced3876db9d23714818 1b7173bc7d042cefb4dbe94d2e58cd21 path[1] a769db4657a103279ba8ef3a629ca84e e836172a9c50e51f45581741cf808315 path[2] 0b491cb4ecbbabec128e7c81a46e62a6 7b57640a0a78be1cbf7dd9d419a10cd8 path[3] 686d16621a80816bfdb5bdc56211d72c a70b81f1117d129529a7570cf79cf52a path[4] 7028a48538ecdd3b38d3d5d62d262465 95c4fb73a525a5ed2c30524ebb1d8cc8 path[5] 2e0c19bc4977c6898ff95fd3d310b0ba e71696cef93c6a552456bf96e9d075e3 path[6] 83bb7543c675842bafbfc7cdb88483b3 276c29d4f0a341c2d406e40d4653b7e4 path[7] d045851acf6a0a0ea9c710b805cced46 35ee8c107362f0fc8d80c14d0ac49c51 path[8] 6703d26d14752f34c1c0d2c4247581c1 8c2cf4de48e9ce949be7c888e9caebe4 path[9] a415e291fd107d21dc1f084b11582082 49f28f4f7c7e931ba7b3bd0d824a4570 -------------------------------------------- LMS public key LMS type 00000005 # LM_SHA256_M32_H5 LMOTS type 00000004 # LMOTS_SHA256_N32_W8 I 215f83b7ccb9acbcd08db97b0d04dc2b K a1cd035833e0e90059603f26e07ad2aa d152338e7a5e5984bcd5f7bb4eba40b7 -------------------------------------------- final_signature: -------------------------------------------- LMS signature q 00000004 -------------------------------------------- LMOTS signature LMOTS type 00000004 # LMOTS_SHA256_N32_W8 C 0eb1ed54a2460d512388cad533138d24 0534e97b1e82d33bd927d201dfc24ebb y[0] 11b3649023696f85150b189e50c00e98 850ac343a77b3638319c347d7310269d y[1] 3b7714fa406b8c35b021d54d4fdada7b 9ce5d4ba5b06719e72aaf58c5aae7aca y[2] 057aa0e2e74e7dcfd17a0823429db629 65b7d563c57b4cec942cc865e29c1dad y[3] 83cac8b4d61aacc457f336e6a10b6632 3f5887bf3523dfcadee158503bfaa89d y[4] c6bf59daa82afd2b5ebb2a9ca6572a60 67cee7c327e9039b3b6ea6a1edc7fdc3 y[5] df927aade10c1c9f2d5ff446450d2a39 98d0f9f6202b5e07c3f97d2458c69d3c y[6] 8190643978d7a7f4d64e97e3f1c4a08a 7c5bc03fd55682c017e2907eab07e5bb y[7] 2f190143475a6043d5e6d5263471f4ee cf6e2575fbc6ff37edfa249d6cda1a09 y[8] f797fd5a3cd53a066700f45863f04b6c 8a58cfd341241e002d0d2c0217472bf1 y[9] 8b636ae547c1771368d9f317835c9b0e f430b3df4034f6af00d0da44f4af7800 y[10] bc7a5cf8a5abdb12dc718b559b74cab9 090e33cc58a955300981c420c4da8ffd y[11] 67df540890a062fe40dba8b2c1c548ce d22473219c534911d48ccaabfb71bc71 y[12] 862f4a24ebd376d288fd4e6fb06ed870 5787c5fedc813cd2697e5b1aac1ced45 y[13] 767b14ce88409eaebb601a93559aae89 3e143d1c395bc326da821d79a9ed41dc y[14] fbe549147f71c092f4f3ac522b5cc572 90706650487bae9bb5671ecc9ccc2ce5 y[15] 1ead87ac01985268521222fb9057df7e d41810b5ef0d4f7cc67368c90f573b1a y[16] c2ce956c365ed38e893ce7b2fae15d36 85a3df2fa3d4cc098fa57dd60d2c9754 y[17] a8ade980ad0f93f6787075c3f680a2ba 1936a8c61d1af52ab7e21f416be09d2a y[18] 8d64c3d3d8582968c2839902229f85ae e297e717c094c8df4a23bb5db658dd37 y[19] 7bf0f4ff3ffd8fba5e383a48574802ed 545bbe7a6b4753533353d73706067640 y[20] 135a7ce517279cd683039747d218647c 86e097b0daa2872d54b8f3e508598762 y[21] 9547b830d8118161b65079fe7bc59a99 e9c3c7380e3e70b7138fe5d9be255150 y[22] 2b698d09ae193972f27d40f38dea264a 0126e637d74ae4c92a6249fa103436d3 y[23] eb0d4029ac712bfc7a5eacbdd7518d6d 4fe903a5ae65527cd65bb0d4e9925ca2 y[24] 4fd7214dc617c150544e423f450c99ce 51ac8005d33acd74f1bed3b17b7266a4 y[25] a3bb86da7eba80b101e15cb79de9a207 852cf91249ef480619ff2af8cabca831 y[26] 25d1faa94cbb0a03a906f683b3f47a97 c871fd513e510a7a25f283b196075778 y[27] 496152a91c2bf9da76ebe089f4654877 f2d586ae7149c406e663eadeb2b5c7e8 y[28] 2429b9e8cb4834c83464f079995332e4 b3c8f5a72bb4b8c6f74b0d45dc6c1f79 y[29] 952c0b7420df525e37c15377b5f09843 19c3993921e5ccd97e097592064530d3 y[30] 3de3afad5733cbe7703c5296263f7734 2efbf5a04755b0b3c997c4328463e84c y[31] aa2de3ffdcd297baaaacd7ae646e44b5 c0f16044df38fabd296a47b3a838a913 y[32] 982fb2e370c078edb042c84db34ce36b 46ccb76460a690cc86c302457dd1cde1 y[33] 97ec8075e82b393d542075134e2a17ee 70a5e187075d03ae3c853cff60729ba4 -------------------------------------------- LMS type 00000005 # LM_SHA256_M32_H5 path[0] 4de1f6965bdabc676c5a4dc7c35f97f8 2cb0e31c68d04f1dad96314ff09e6b3d path[1] e96aeee300d1f68bf1bca9fc58e40323 36cd819aaf578744e50d1357a0e42867 path[2] 04d341aa0a337b19fe4bc43c2e79964d 4f351089f2e0e41c7c43ae0d49e7f404 path[3] b0f75be80ea3af098c9752420a8ac0ea 2bbb1f4eeba05238aef0d8ce63f0c6e5 path[4] e4041d95398a6f7f3e0ee97cc1591849 d4ed236338b147abde9f51ef9fd4e1c1 Acknowledgements Thanks are due to Chirag Shroff, Andreas Huelsing, Burt Kaliski, Eric Osterweil, Ahmed Kosba, Russ Housley, Philip Lafrance, Alexander Truskovsky, Mark Peruzel, and Jim Schaad for constructive suggestions and valuable detailed review. We especially acknowledge Jerry Solinas, Laurie Law, and Kevin Igoe, who pointed out the security benefits of the approach of Leighton and Micali [USPTO5432852], Jonathan Katz, who gave us security guidance, and Bruno Couillard and Jim Goodman for an especially thorough review. Authors' Addresses David McGrew Cisco Systems 13600 Dulles Technology Drive Herndon, VA 20171 United States of America Michael Curcio Cisco Systems 7025-2 Kit Creek Road Research Triangle Park, NC 27709-4987 United States of America Scott Fluhrer Cisco Systems 170 West Tasman Drive San Jose, CA United States of America Previous: RFC 8553 - DNS Attrleaf Changes: Fixing Specifications That Use Underscored Node Names Next: RFC 8555 - Automatic Certificate Management Environment (ACME)
http://www.faqs.org/rfcs/rfc8554.html
CC-MAIN-2021-17
refinedweb
15,379
56.08
Clemens thinks 'IDL' is good and often enough to hammer down your services interface and message contract - well somehow, yes. But we do not have to wait for Indigo, just some few months for Whidbey. Things really get better with ASMX v2 in Whidbey. The following description assumes that you already have an exisiting WSDL (or a bunch of them) and then generate code from it. But the process can also be turned around: First code your interface in .NET and voila... you have the code-based contract-first approach rather than the schema-based one with XSD and WSDL. ASMX v2 will generate a different interface for each binding in a WSDL description. E.g.: [WebServiceBinding(Name="OrderBinding", Namespace="urn:...")] public interface IOrderEntry { [WebMethod] [SoapDocumentMethod(...)] string PlaceOrder(Order order); [WebMethod] [SoapDocumentMethod(...)] string UpdateOrder(Order order); } Each interface has the WebServiceBindingAttribute with the binding's name and namespace. At runtime, ASMX reflects over the interfaces that a user's class implements to find all WebServiceBinding and WebMethod attributes. A class that implements an interface which has the WebServiceBindingAttribute can't itself have any Web services or XML serialization attributes. Makes sense but is very important! Obviously, a class can implement multiple interfaces each corresponding to a different WSDL binding, but a given binding cannot be split across multiple interfaces. If an interface inherits from another interface, at most one of the interfaces can have the WebServiceBindingAttribute. This is analogous to WSDL not allowing portType inheritance. The generated interface has the same name as the binding name and is prefixed with 'I' to indicate "Interface". Multiple bindings can be passed to the code generation process (e.g. with wsdl.exe) in one or more WSDL files. Each binding will then yield a different interface. And as already stated at the beginning of this article: Just use this approach reversely and you are all set to design your contract-first Web services in 'IDL'.
http://weblogs.asp.net/cweyer/archive/2004/09/14/229286.aspx
crawl-002
refinedweb
322
57.27
Type: Posts; User: sauc3_kid you are a star. i wish i had mentors like u around me to help me with my programming struggles lol i am a beginner. i want to declare score as integer so that when you win a game you get plus one i ran the program and its telling me der are too many initializers i am just about to finish my rock papper sissors game as i added classes to the games. however i dont know how to add a scoring system. any help. #include <iostream> #include <cstdlib> ... hey guys, i have been struggling for hours now on how to enter double values into my array so that it can output the sum of the numbers less than 24. this is my code so far. and im stuck ...
http://forums.codeguru.com/search.php?s=1b9bb4d7cd9fbdcb1bebcea67936b9da&searchid=5598041
CC-MAIN-2014-49
refinedweb
134
88.26
Auto Scaling Group for Your AWS Elastic Beanstalk Environment Your Elastic Beanstalk includes an Auto Scaling group that manages the Amazon EC2 instances in your environment. In a single-instance environment, the Auto Scaling group ensures that there is always one instance running. In a load-balanced environment, you configure the group with a range of instances to run, and Amazon EC2 Auto Scaling adds or removes instances as needed, based on load. The Auto Scaling group also manages the launch configuration for the instances in your environment. You can modify the launch configuration to change the instance type, key pair, Amazon Elastic Block Store (Amazon EBS) storage, and other settings that can only be configured when you launch an instance. The Auto Scaling group uses two Amazon CloudWatch alarms to trigger scaling operations. The default triggers scale when the average outbound network traffic from each instance is higher than 6 MiB or lower than 2 MiB over a period of five minutes. To use Amazon EC2 Auto Scaling effectively, configure triggers that are appropriate for your application, instance type, and service requirements. You can scale based on several statistics including latency, disk I/O, CPU utilization, and request count. To optimize your environment's use of Amazon EC2 instances through predictable periods of peak traffic, configure your Auto Scaling group to change its instance count on a schedule. You can schedule changes to your group's configuration that recur daily or weekly, or schedule one-time changes to prepare for marketing events that will drive a lot of traffic to your site. Amazon EC2 Auto Scaling monitors the health of each Amazon EC2 instance that it launches. If any instance terminates unexpectedly, Amazon EC2 Auto Scaling detects the termination and launches a replacement instance. To configure the group to use the load balancer's health check mechanism, see Auto Scaling Health Check Setting. Topics Configuring Your Environment's Auto Scaling Group You can configure how Amazon EC2 Auto Scaling works by editing Capacity on the environment's Configuration page in the environment management console. To configure scheduled actions in the Elastic Beanstalk console Open the Elastic Beanstalk console. Navigate to the management page for your environment. Choose Configuration. On the Capacity configuration card, choose Modify. In the Auto Scaling Group section, configure the following settings. Environment type – Select Load balanced. Min instances – The minimum number of EC2 instances that the group should contain at any time. The group starts with the minimum count and adds instances when the scale-up trigger condition is met. Max instances – The maximum number of EC2 instances that the group should contain at any time. Note If you use rolling updates, be sure that the maximum instance count is higher than the Minimum instances in service setting for rolling updates. Availability Zones – Choose the number of Availability Zones to spread your environment's instances across. By default, the Auto Scaling group launches instances evenly across all usable zones. To concentrate your instances in fewer zones, choose the number of zones to use. For production environments, use at least two zones to ensure that your application is available in case one Availability Zone goes out. Placement (optional) – Choose the Availability Zones to use. Use this setting if your instances need to connect to resources in specific zones, or if you have purchased reserved instances, which are zone-specific. If you also set the number of zones, you must choose at least that many custom zones. If you launch your environment in a custom VPC, you cannot configure this option. In a custom VPC, you choose Availability Zones for the subnets that you assign to your environment. Scaling cooldown – The amount of time, in seconds, to wait for instances to launch or terminate after scaling, before continuing to evaluate triggers. For more information, see Scaling Cooldowns. Choose Apply. The aws:autoscaling:asg Namespace Elastic Beanstalk provides configuration options for Auto Scaling settings in the aws:autoscaling:asg namespace. option_settings: aws:autoscaling:asg: Availability Zones: Any Cooldown: '720' Custom Availability Zones: 'us-west-2a,us-west-2b' MaxSize: '4' MinSize: '2'
http://docs.amazonaws.cn/en_us/elasticbeanstalk/latest/dg/using-features.managing.as.html
CC-MAIN-2019-04
refinedweb
684
53.31
Hello, I have made the two changes that Simon suggested and uploaded a new version of the library. By the way, GHC seemed to work correctly even without the extra boolean parameter, perhaps it treats unsafePerformIO specially somehow? A somewhat related question: I ended up using three calls to unsafeInterleaveIO which seems like a bit much. Could I have done it in a different way somehow? This is what I did: gen r = do v <- unsafeInterleaveIO (genSym r) ls <- unsafeInterleaveIO (gen r) rs <- unsafeInterleaveIO (gen r) return (Node v ls rs) Note that a single unsafeInterleaveIO around the whole do block is not quite right (this is what the code in the other package does) because this will increment the name as soon as the generator object is forced, and we want the name to be increment when the name is forced. -Iavor On Fri, Dec 19, 2008 at 1:24 AM, Simon Marlow <marlowsd at gmail.com> wrote: >> Why not depend on this instead? >> >> > > Looking at the code for this, I'm somewhat suspicious that it actually works > with GHC: > > -- The extra argument to ``gen'' is passed because without > -- it Hugs spots that the recursive calls are the same but does > -- not know that unsafePerformIO is unsafe. > where gen _ r = Node { supplyValue = unsafePerformIO (genSym r), > supplyLeft = gen False r, > supplyRight = gen True r } > > even if that extra Bool argument is enough to fool Hugs, I wouldn't count on > it being enough to fool GHC -O2! You probably want to use > unsafeInterleaveIO like we do in GHC's UniqSupply library. > > Also, I'd replace the MVar with an IORef and use atomicModifyIORef for > speed. > > Cheers, > Simon >
http://www.haskell.org/pipermail/glasgow-haskell-users/2008-December/016373.html
CC-MAIN-2014-15
refinedweb
278
63.32
A C program basically has the following form: Preprocessor Commands Functions Variables Statements & Expressions The following program is written in the C programming language. Open a text file hello.c using vi editor and put the following lines inside that file. #include <stdio.h> int main() { /* My first program */ printf("Hello, World! \n"); return 0; } Preprocessor Commands: These commands tells the compiler to do preprocessing before doing actual compilation. Like #include <stdio.h> is a preprocessor command which tells a C compiler to include stdio.h file before going to actual compilation. You will learn more about C Preprocessors in C Preprocessors session. Functions: are main building blocks of any C Program. Every C Program will have one or more functions and there is one mandatory function which is called main() function. This function is prefixed with keyword int which means this function returns an integer value when it exits. This integer value is retured using return statement. The C Programming language provides a set of built-in functions. In the above example printf() is a C built-in function which is used to print anything on the screen. Check Builtin function section for more detail. You will learn how to write your own functions and use them in Using Function session. Variables: are used to hold numbers, strings and complex data for manipulation. You will learn in detail about variables in C Variable Types. Statements & Expressions : Expressions combine variables and constants to create new values. Statements are expressions, assignments, function calls, or control flow statements which make up C programs. Comments: are used to give additional useful information inside a C Program. All the comments will be put inside /*...*/ as given in the example above. A comment can span through multiple lines. C is a case sensitive programming language. It means in C printf and Printf will have different meanings. C has a free-form line structure. End of each C statement must be marked with a semicolon. Multiple statements can be one the same line. White Spaces (ie tab space and space bar ) are ignored. Statements can continue over multiple lines. To compile a C program you would have to Compiler name and program files name. Assuming your compiler's name is cc and program file name is hello.c, give following command at Unix prompt. $cc hello.c This will produce a binary file called a.out and an object file hello.o in your current directory. Here a.out is your first program which you will run at Unix prompt like any other system program. If you don't like the name a.out then you can produce a binary file with your own name by using -o option while compiling C program. See an example below $cc -o hello hello.c Now you will get a binary with name hello. Execute this program at Unix prompt but before executing / running this program make sure that it has execute permission set. If you don't know what is execute permission then just follow these two steps $chmod 755 hello $./hello This will produce following result Hello, World Congratulations!! you have written your first program in "C". Now believe me its not difficult to learn "C".
http://www.tutorialspoint.com/cgi-bin/printversion.cgi?tutorial=ansi_c&file=c_program_structure.htm
CC-MAIN-2014-15
refinedweb
539
68.87
Wizards can recycle objects at will, toad and newt players, put a room within a room within a room within their pocket ... they can do everything that does not violate the MOO server consistency rules (which means that they cannot , e.g. put something into itself or make an object the child of its children). Other duties/powers of the wizards include shutting down the MOO, forcing a database dump, blacklisting abusive sites ... Every MOO comes with a pre-made wizard, object #2. Sociologically speaking, wizards are the mothers and fathers of the MOO, and players in general will come crying to them for just about everything. This keeps happening until some attempt at social reform is done - usually with mixed success, witness LambdaMOO. Masters of Arcane magics this class is one of the favored classes in the game. This is one of the prime classes.. wizard n. 1. Transitively, a person who knows how a complex piece of software or hardware works (that is, who groks it); esp.. The term `wizard' is also used intransitively of someone who has extremely high-level hacking or problem-solving ability. 3. A person who is permitted to do things forbidden to ordinary people; one who has wheel privileges on a system. 4. A Unix expert, esp. a Unix systems programmer. This usage is well enough established that `Unix Wizard' is a recognized job title at some corporations and to most headhunters. See guru, lord high fixer. See also deep magic, heavy wizardry, incantation, magic, mutter, rain dance, voodoo programming, wave a dead chicken. --The Jargon File version 4.3.1, ed. ESR, autonoded by rescdsk. Wizard was a prototype game for the Atari 2600. The basic concept is to move your little stick figure around a big red maze, while avoiding the oddly shaped enemies. This game is emulated by all the popular Atari 2600 emulators (Z26, Stella, etc), but there is little reason to bother playing it, because it isn't really that fun. This game was never finished and exists only in prototype form. I am unable to put a value on it at this time. Author: John Varley ISBN: 0441900674 Paperback: 372 pages Publisher: Ace Books Genre: Science Fiction Warning!! Though I intend to keep the secrets of the second book, it is possible that spoilers for the first book may exist, as the three books are tied rather closely together. Read with caution if you have not read the first one and still intend to. So, remember all those folks you met in the first book of the Gaean Trilogy? Many of them return (as well as some new faces) for this book, the second and my favorite of the three. Chris'fer Minor is an incredibly unlucky guy, and he's got a major, psychotic problem. Occasionally, he becomes a completely different person, an angry, sexually aggressive, violent person, though his normal attitude is very laid-back (how could you not be laid-back with a name like Chris'fer?), and is always surprised to find himself with new wounds received from a jealous boyfriend, or to wake up in a city jail for beating a man close to death for looking at him funny. Fortunately for him, a planet exists, out near Saturn, that is run by a god keen on giving miracles to those who deserve them. The planet is named Gaea--named so because that is the name of the god who runs the place--and she's perfectly willing to break normal rules of physics and medicine to cure the sick, aid the poor, and defend the righteous, so long as they give a good show. Anyway, he convinces the nice Titanide with the shitting-in-public faux pas issue to send him off to Gaea to get himself a miracle cure. We also get to meet Robin the Nine-fingered, a member of the Coven, a religious sect that bought up some floating cans out in the LaGrange points near the Moon to practice their witchery and lesbianness. These women are of the belief that men are useful for nothing, save the production of semen. Given a few more years, they're pretty sure they'll have that taken care of, too. In any event, Robin, one of the short women (a practical joke from Earth; the sperm sent to the Coven was all from short men), has a form of epilepsy which makes it difficult for her to deal with life, the shakes disabling her for long periods of time. She sends off for the Miracle Cure, and is accepted--off she goes, taking her python Nasu, an ill-tempted but obedient giant fucking snake. Varley sets this second book a couple decades ahead of the first one, and explains a few very dramatic things. First and foremost, Cirocco Jones has been named the Wizard of Gaea, to act as God's Hand on Earth, as it were. She can talk with god directly, can speak all the languages spoken on the Great Wheel, and acts almost without any direct involvement of the deity. But there are a few quirks. First, the Titanides (in an effort to keep the population of the freely-screwing centaurs down) can no longer reproduce without the direct action of Rocky. Her spit activates the rear-fertilized eggs that have to be implanted in the frontal ovaries for actual birth to occur. Rear-sex, they call it, happens all the time between friends (all Titanides have a rear penis, one that looks very human, but is the size of a horse's, and an anterior vagina) and after such an activity, an un-activated egg pops out a couple days later. Most Titanides just save these as keepsakes, good memories, until they eventually decay after a couple years. In order for pregnancy to occur, that golf-ball-sized egg must be put in Cirocco Jones's mouth, and then crammed in the frontal vagina (Titanides' sex is determined by the frontal genitals--either one or the other). Well, Rocky's not too keen on this, having to be the last say on who does and who does not procreate among the folk she cares for so deeply. So, Rocky (with Gaby beside her) spends the first half of this book setting out feelers (when she's not utterly drunk on Titanide liquor, the stress of playing God getting to be too much for her) among the "regional brains" of Gaea. After all, Gaea is a big place--you can't expect her to run everything, so each zone in her wheel gets its own brain (save for one, Rhea, who is dead, and Oceanus, who doesn't really care to do anything in favor of Gaea, given that he waged war against her several hundred thousand years ago), and Cirocco is the only person alive who can talk to them without risking immediate death. So, she just might be interested in planting the seeds of revolution, if the regional minds see it as appropriate... My favorite of the trilogy, I give Wizard two human thumbs and a Titanide hoof up. The storyline is continuous, without too much of the mind-numbing detail that can occasionally bog down SF authors interested in describing a new world. Varley attacks the reader with a near-constant barrage of new ideas, which, moments after you're used to them, he shatters with a whole new revelation. The Gaean Trilogy Titan | Wizard | Demon Written for The Bookworm Turns: An Everything Literary Quest. Wizard. Wizards are a simplification of the tools that are provided by the program, set up by programmers to use those tools quickly and simply so that the general user don't get bogged down in learning how to upload a double column Ap-J format and not screw it up by hitting backspace too many times. There is a philosophical clash here with many mid to high range computer users who are used to play with programs and learning their secrets. Wizards try to present themselves to the user, as anyone who has tried to remove Clippy can visualize, and this presentation annoys some who think that this is an attempt on the part of the people who made the program to impede their learning of it. Wiz"ard (?), n. [Probably from wise + -ard.] 1. A wise man; a sage. See how from far upon the eastern road The star-led wizards [Magi] haste with odors sweet! Milton. 2. One devoted to the black art; a magician; a conjurer; a sorcerer; an enchanter. The wily wizard must be caught. Dryden. © Webster 1913. Wiz"ard, a. Enchanting; charming. Collins. Haunted by wizards. Where Deva spreads her wizard stream. Milton. © Webster 1913. printable version chaos Everything2 Help
http://everything2.com/title/wizard
crawl-002
refinedweb
1,467
67.18
cmd — Line-oriented Command Processors¶ The cmd module contains one public class, Cmd, designed to be used as a base class for interactive shells and other command interpreters. By default it uses readline for interactive prompt handling, command line editing, and command completion. Processing Commands¶ A command interpreter created with cmd uses a loop to read all lines from its input, parse them, and then dispatch the command to an appropriate command handler. Input lines are parsed into two parts: the command, and any other text on the line. If the user enters foo bar, and the interpreter class includes a method named do_foo(), it is called with "bar" as the only argument. The end-of-file marker is dispatched to do_EOF(). If a command handler returns a true value, the program will exit cleanly. So to give a clean way to exit the interpreter, make sure to implement do_EOF() and have it return True. This simple example program supports the “greet” command: import cmd class HelloWorld(cmd.Cmd): def do_greet(self, line): print("hello") def do_EOF(self, line): return True if __name__ == '__main__': HelloWorld().cmdloop() Running it interactively demonstrates how commands are dispatched and shows of some of the features included in Cmd. $ python3 cmd_simple.py (Cmd) The first thing to notice is the command prompt, (Cmd). The prompt can be configured through the attribute prompt. The prompt value is dynamic, and if a command handler changes the prompt attribute the new value is used to query for the next command. Documented commands (type help <topic>): ======================================== help Undocumented commands: ====================== EOF greet The help command is built into Cmd. With no arguments, help shows the list of commands available. If the input includes a command name, the output is more verbose and restricted to details of that command, when available. If the command is greet, do_greet() is invoked to handle it: (Cmd) greet hello If the class does not include a specific handler for a command, the method default() is called with the entire input line as an argument. The built-in implementation of default() reports an error. (Cmd) foo *** Unknown syntax: foo Since do_EOF() returns True, typing Ctrl-D causes the interpreter to exit. (Cmd) ^D$ No newline is printed on exit, so the results are a little messy. Command Arguments¶ This example includes a few enhancements to eliminate some of the annoyances and add help for the greet command. import cmd class HelloWorld(cmd.Cmd): def do_greet(self, person): """greet [person] Greet the named person""" if person: print("hi,", person) else: print('hi') def do_EOF(self, line): return True def postloop(self): print() if __name__ == '__main__': HelloWorld().cmdloop() The docstring added to do_greet() becomes the help text for the command: $ python3 cmd_arguments.py (Cmd) help Documented commands (type help <topic>): ======================================== greet help Undocumented commands: ====================== EOF (Cmd) help greet greet [person] Greet the named person The output shows one optional argument to greet, person. Although the argument is optional to the command, there is a distinction between the command and the callback method. The method always takes the argument, but sometimes the value is an empty string. It is left up to the command handler handler does not include the command itself. That simplifies parsing in the command handler, especially if multiple arguments are needed. Live Help¶ In the previous example, the formatting of the help text leaves something to be desired. Since it comes from the docstring, it retains the indentation from the source file. The source could be changed to remove the extra white-space, but that would leave the application code looking poorly formatted. A better solution is to implement a help handler for the greet command, named help_greet(). The help handler is called to produce help text for the named command. # Set up gnureadline as readline if installed. try: import gnureadline import sys sys.modules['readline'] = gnureadline except ImportError: pass import cmd class HelloWorld(cmd.Cmd): def do_greet(self, person): if person: print("hi,", person) else: print('hi') def help_greet(self): print('\n'.join([ 'greet [person]', 'Greet the named person', ])) def do_EOF(self, line): return True if __name__ == '__main__': HelloWorld().cmdloop() In this example, the text is static but formatted more nicely. It would also be possible to use previous command state to tailor the contents of the help text to the current context. $ python3 handler methods. The user triggers completion by hitting the tab key at an input prompt. When multiple completions are possible, pressing tab twice prints a list of the options. Note The GNU libraries needed for readline are not available on all platforms by default. In those cases, tab completion may not work. See readline for tips on installing the necessary libraries if your Python installation does not have them. $ python3 cmd_do_help.py (Cmd) <tab><tab> EOF greet help (Cmd) h<tab> (Cmd) help Once the command is known, argument completion is handled by methods with the prefix complete_. This allows new completion handlers to assemble a list of possible completions using arbitrary criteria (i.e., querying a database or looking at a file or directory on the file system). In this case, the program has a hard-coded set of “friends” who receive a less formal greeting than named or anonymous strangers. A real program would probably save the list somewhere, and read it once then cache the contents to be scanned as needed. # Set up gnureadline as readline if installed. try: import gnureadline import sys sys.modules['readline'] = gnureadline except ImportError: pass import cmd class HelloWorld(cmd.Cmd): FRIENDS = ['Alice', 'Adam', 'Barbara', 'Bob'] def do_greet(self, person): "Greet the person" if person and person in self.FRIENDS: greeting = 'hi, {}!'.format(person) elif person: greeting = 'hello, {}'.format3¶ Cmd includes several methods that can be overridden as hooks for taking actions or altering the base class behavior. This example is not exhaustive, but contains many of the methods commonly useful. # Set up gnureadline as readline if installed. try: import gnureadline import sys sys.modules['readline'] = gnureadline except ImportError: pass import cmd class Illustrate(cmd.Cmd): "Illustrate the base class method use." def cmdloop(self, intro=None): print('cmdloop({})'.format(intro)) return cmd.Cmd.cmdloop(self, intro) def preloop(self): print('preloop()') def postloop(self): print('postloop()') def parseline(self, line): print('parseline({!r}) =>'.format(line), end='') ret = cmd.Cmd.parseline(self, line) print(ret) return ret def onecmd(self, s): print('onecmd({})'.format(s)) return cmd.Cmd.onecmd(self, s) def emptyline(self): print('emptyline()') return cmd.Cmd.emptyline(self) def default(self, line): print('default({})'.format(line)) return cmd.Cmd.default(self, line) def precmd(self, line): print('precmd({})'.format(line)) return cmd.Cmd.precmd(self, line) def postcmd(self, stop, line): print('postcmd({}, {})'.format(stop, line)) return cmd.Cmd.postcmd(self, stop, line) def do_greet(self, line): print('hello,', line) def do_EOF(self, line): "Exit" return True if __name__ == '__main__': Illustrate().cmdloop('Illustrating the methods of cmd.Cmd') cmdloop() is the main processing loop of the interpreter. Overriding it is usually not necessary, since the preloop() and postloop() hooks are available. Each iteration through cmdloop() calls onecmd() to dispatch the command to its handler. handler is looked up and invoked. If none is found, default() is called instead. Finally postcmd() is called. Here is an example session with $ python3¶ In addition to the methods described earlier, it can be set on the class directly. When printing help, the doc_header, misc_header, undoc_header, and ruler attributes are used to format the output. import cmd class HelloWorld(cmd.Cmd):() This example class shows a command handler to let the user control the prompt for the interactive session. $ python3 cmd_attributes.py Simple command processor example. prompt: prompt hello hello: help doc_header ---------- help prompt undoc_header ------------ EOF hello: Running Shell Commands¶ To supplement the standard command processing, Cmd includes two special command prefixes. A question mark ( ?) is equivalent to the built-in help command, and can be used in the same way. An exclamation point ( !) maps to do_shell(), and is intended for “shelling out” to run other commands, as in this example. import cmd import subprocess class ShellEnabled(cmd.Cmd): last_output = '' def do_shell(self, line): "Run a shell command" print("running shell command:", line) sub_cmd = subprocess.Popen(line, shell=True, stdout=subprocess.PIPE) output = sub_cmd.communicate()[0].decode('utf-8') print(output) self.last_output = output def do_echo(self, line): """Print the input, replacing '$out' with the output of the last shell command. """ # Obviously not robust print(line.replace('$out', self.last_output)) def do_EOF(self, line): return True if __name__ == '__main__': ShellEnabled().cmdloop() This echo command implementation replaces the string $out in its argument with the output from the previous shell command. $ python3 cmd_do_shell.py (Cmd) ? Documented commands (type help <topic>): ======================================== echo help shell Undocumented commands: ====================== EOF (Cmd) ? shell Run a shell command (Cmd) ? echo Print the input, replacing '$out' with the output of the last shell command (Cmd) shell pwd running shell command: pwd .../pymotw-3/source/cmd (Cmd) ! pwd running shell command: pwd .../pymotw-3/source/cmd (Cmd) echo $out .../pymotw-3/source/cmd Alternative Inputs¶ While the default mode for Cmd() is to interact with the user through the readline library, it is also possible to pass a series of commands in to standard input using standard Unix shell redirection. $ echo help | python3 cmd_do_help.py (Cmd) Documented commands (type help <topic>): ======================================== greet help Undocumented commands: ====================== EOF (Cmd) To have the program read a script file directly, a few other changes may be needed. Since readline interacts with the terminal/tty device, rather than the standard input stream, it should be disabled when the script is going to be reading from a file. Also, to avoid printing superfluous prompts, the prompt can be set to an empty string. This example shows how to open a file and pass it as input to a modified version of the HelloWorld example. import cmd class HelloWorld(cmd.Cmd): # Disable rawinput module use use_rawinput = False # Do not show a prompt after each command read prompt = '' def do_greet(self, line): print("hello,", line) def do_EOF(self, line): return True if __name__ == '__main__': import sys with open(sys.argv[1], 'rt') as input: HelloWorld(stdin=input).cmdloop() With use_rawinput set to False and prompt set to an empty string, the script can be called on an input file with one command on each line. Running the example script with the example input produces the following output. $ python3 cmd_file.py cmd_file.txt hello, hello, Alice and Bob Commands from sys.argv¶ Command line arguments to the program can also be processed as commands for the interpreter class, instead of reading commands from the console or a file. To use the command line arguments,3 cmd_argv.py greet Command-Line User hello, Command-Line User $ python3 cmd_argv.py (Cmd) greet Interactive User hello, Interactive User (Cmd) See also - Standard library documentation for cmd - cmd2 – Drop-in replacement for cmdwith additional features. - GNU readline – The GNU Readline library provides functions that allow users to edit input lines as they are typed. readline– The Python standard library interface to readline. subprocess– Managing other processes and their output.
https://pymotw.com/3/cmd/index.html
CC-MAIN-2017-43
refinedweb
1,843
58.28
Java Tutorial Java is a popular programming language. Java is used to develop mobile apps, web apps, desktop apps, games and much more.Start learning Java now » Examples in Each Chapter Our "Try it Yourself" editor makes it easy to learn Java. You can edit Java code and view the result in your browser. Example public class Main { Java Quiz Test your Java skills with a quiz. Learn by Examples Learn by examples! This tutorial supplements all explanations with clarifying examples. My Learning Track your progress with the free "My Learning" program here at W3Schools. Log into your account, and start earning points! This is an optional feature. You can study W3Schools without using My Learning. Java Reference Download Java Download Java from the official Java web site: Kickstart your career Get certified by completing the courseGet certified
http://localdev.w3schools.com/java/default.asp
CC-MAIN-2022-40
refinedweb
138
59.9
One of the most common questions we get is how long should an ObjectContext should live. Options often cited include one per: - Function - Form - Thread - Application Plenty of people are asking these types of questions, case in point here is a question on Stackflow. I am sure there are many more buried away on our forums too. This is a classic it depends type of question. Lots of factors weigh into the decision including: - Disposal: Cleanly disposing of the ObjectContext and it’s resources is important. It is also significantly easier if you create a new ObjectContext for each Function, because then you can simply write a using block to ensure resources are disposed appropriately: using (MyContext ctx = new MyContext()) { … } - Cost Of Construction: Some people are, quite understandably, concerned about the cost of recreating the ObjectContext again and again. The reality is this cost is actually pretty low, because mostly it simply involves copying, by reference, metadata from a global cache into the new ObjectContext. Generally I don’t think this cost is worth worrying about, but as always, there will be exceptions to that rule. - Memory Usage: The more you use an ObjectContext, generally the bigger it gets. This is because it holds a reference to all the Entities it has ever known about, essentially whatever you have queried, added or attached. So you should reconsider sharing the same ObjectContext indefinitely. There are some exceptions to that rule and a workaround, but for the most part these approaches just aren’t recommended. - If your ObjectContext only ever does NoTracking queries then it won’t get bigger because the ObjectContext immediately forgets about these entities. - You could implement some very explicit tidy-up logic, i.e. implement some sort of Recycle interface, that iterates through the ObjectStateManager detaching entities and AcceptingChanges(..) to discard deleted objects. Note: I’m not recommending this, I’m just saying it should be possible, I have no idea if relative to recreation it will result in any savings. So this might be a good subject for a future blog post. - Thread Safety: If you are trying to re-use an ObjectContext you should be aware that is not thread safe, i.e. similar to the standard .NET collection classes. If you access it from many threads (e.g. web requests) you will need to insure that you synchronize access manually. - Stateless: If your services are designed to be stateless, as most web services should be, re-using an ObjectContext between requests might not be best because, the leftovers in the ObjectContext from the last call may have subtle effects on your application that you are not expecting. - Natural finite lifetimes: If you have a natural finite lifetime way of managing an ObjectContext,such as a short lived Form, a UnitOfWork or a Repository, then scoping the ObjectContext accordingly might be the best thing to do. As you can see there are lots of issues at play. Most of them tend to point towards a short lived context that isn’t shared. So that is my recommended rule of thumb. However as always understanding the reasoning behind a ‘rule of thumb’ will help you know when it is appropriate to go your way. PingBack from Another plus of reusing the same entity context across the application is that you need to load something like Products only once into memory across all requests instead of fetching Products each time the page is loaded by a user. Personally though, I prefer disposing the context as soon as I’m done with it because of the ‘Stateless’ reason you mention and ran into some issues with it a while back. As the EF matures I hope to see the recommendation shift towards creating a global entity context because it seems a lot more efficient. This is 20th post in my ongoing series of Entity Framework Tips . Fixed Length Field Padding: If you I like the idea of a "using" block to clean up. However, if one creates the ObjectContext in a method that returns an Entity (or IQueryable) retrieved by that ObjectContext, then one cannot use a "usings" block for the ObjectContext creation because at the caller side it complains (such as during GridView.DataBind). What then? @Mark, You definitely shouldn’t return something unenumerated from a using block. generally I do things like this psuedo code: using (ctx) { return Query.ToArray(); } Now if you need to load relationships later, for example your query returns a customer, and you know you need to enumerate the Orders, if your ctx has been disposed (because of the using block) it won’t work either. In that situation you should eagerly load what you need… i.e. using (ctx) { var Query = …; Query.Include("Orders"); return Query.ToArray(); } Hope this helps Alex This is 20th post in my ongoing series of Entity Framework Tips . Fixed Length Field Padding: If you The reason I use the context as a private class variable is that I have to change the entities outside my repository. So if I return an object and dispose its context. Then I can’t change its properties, and send it back to get saved. I then have to manually serialize the entity before I send it to the repository, or I will get the "This entity is associated with another context"-error. Maybe I’m missing something here, but I would think this is the main reason to use the context as a private class variable. Because then you just implement IDisposable in your repository, and use the using pattern where the repository is used instead. Moe, I don’t think you are missing anything. Quite the contrary, what you describe sounds completely reasonable, maybe even a best practice. Alex My problem is that I tried to keep my context around in Session for the same reasons Moe described above. At login, I would retrieve some information and the user would manipulate that information. Then, since I had the context in Session, I could simply update the object, and save the changes. This worked great until I tried to change to SQL Server Session State…..context cannot be serialized. BOOM! I’m done. Now I need to change all my data access pieces to run more stateless, which I understand the importance. I was hoping that I could use the new .NET RIA Services, but that’s really only for Silverlight. Nice article. Reassuringly, some of the suggests are conclusions I had already come to but some other nice reassurances like the fact that contructing the ObjectContext (with using(ctx) { … }) isn't have on the system. I was worried about that. Thanks Thanks for clarifying the cost of creating the ObjectContext. Would there ever be a situation where using a class scoped context and a method scoped context would be a good idea? For example if you are returning and IQueryable of users where the data will be further processed, you would not want to destroy the context so you would use the class scoped. Then if you are preforming an add you could just put it in, save the changes and go on with life. public class UserRepository: IRepository<user> { private ColoDatabase staticDB = new ColoDatabase(); public IQueryable<user> GetList() { return staticDB.users; } public Boolean Add(ref user item) { using (ColoDatabase db = new ColoDatabase()) { item.id = db.users.Select(x => x.id).OrderByDescending(x => x).First() + 1; db.users.AddObject(item); var changes = db.SaveChanges(); return changes > 0; } } } This though could create issues where the method scoped context could add a user and it would not be reflected in the class scoped context. Thoughts? Love the post though, really good to see other people are concerned with best practices. Matthew
https://blogs.msdn.microsoft.com/alexj/2009/05/07/tip-18-how-to-decide-on-a-lifetime-for-your-objectcontext/
CC-MAIN-2018-43
refinedweb
1,289
61.97
This article describes how to use CFileFindEx, a class based on the MFC class CFileFind that allows you to specify file filters that control which files are returned. The class plugs in wherever a CFileFind class was used previously and is pretty easy to understand. The programmer can use either DOS wildcard or ATL regular expression based includes or excludes. CFileFindEx CFileFind My company, Rimage, manufactures high end CD and DVD production equipments. The software I work on specifically is called QuickDisc. It is the interface that helps desktop users collect files using drag and drop and select the options that they want to use when creating discs. Our equipment automatically loads the disc drives and prints on the disc using a printer that we have developed. One of the problems with QuickDisc was that it didn't make a very good back up program because it always selected all the files from folders that were dropped on the UI. The class included in this article was created for an upcoming version to allow us to filter the files based on user input. The class seemed useful and general enough that I thought others may have a use for it. The project download includes the source code for the class and a program that implements its features. The class is simple to use. The programmer can define one or more include or exclude filters in a format similar to the following example: *.cpp|*.h|*.rc Note that each filter is separated by a vertical bar '|' character. This character was used because it is not valid for DOS files. If the above is included as an "Include" filter only files with extensions .cpp, .h, or .rc will be returned. Similarly, if the above filter is specified as an "Exclude" filter all files except those of type .cpp, .h, or .rc will be returned. Note: Folders are always returned regardless of their name or extension. Alternatively, Include and Exclude filters may be specified using a subset of the typical regular expression syntax as defined in the ATL class CAtlRegExp. The following syntax is allowed: CAtlRegExp", "666", and so on). Indicates that the preceding expression matches zero or more times. ??, +?, *? Non-greedy versions of ?, +, and *. These match as little as possible, unlike the greedy versions which match as much as possible. Example: given the input "<abc><def>", <.*?> matches "<abc>" while <.*> matches "<abc><def>". Escape character: interpret the next character literally (for example, [0-9]+ matches one or more digits, but [0-9]\+ matches a digit followed by a plus character). Also used for abbreviations (such as \a for any alphanumeric character; see table below). At the end of a regular expression, this character matches the end of the input. Example: [0-9]$ matches a digit at the end of the input. Alternation operator: separates two expressions, exactly one of which matches (for example, T|the matches "The" or "the"). Negation operator: the expression following ! does not match the input. Example: a!b matches "a" not followed by "b". ! Any alphanumeric character: ([a-zA-Z0-9]) White space (blank): ([ \\t]) Any alphabetic character: ([a-zA-Z]) Any decimal digit: ([0-9]) Any hexadecimal digit: ([0-9a-fA-F]) \n Newline: (\r|(\r?\n)) \q A quoted string: (\"[^\"]*\")|(\'[^\']*\') \w A simple word: ([a-zA-Z]+) \z An integer: ([0-9]+) For example, the previous filter list could be entered as: ^.*?\.cpp$|^.*?\.h$|^.*?\.rc$ Regular expressions are more trouble to define and only available as an artifact of the way the class does its matching, but some useful expressions could be done: ^[a-d].*?\.cpp$ Would only include (or exclude) files that start with a, b, c, or d and have the extension .cpp. Matches done with this class are always case insensitive. The class is implemented as in the following example. Don't forget to include filefindex.h. #include "filefindex.h" CString csFilePath = _T("C:\\TestFiles"); // Include all .doc, .xls, or .ppt files. CString csIncludeFilter = _T("*.doc|*.xls|*.ppt"); // Note don't want .doc files that start with Tom CString csExcludeFilter = _T("Tom*.doc"); // Check for files based on the critera the user filled out. CFileFindEx fileInfo; BOOL bWorked = fileInfo.FindFile(csFilePath,csIncludeFilter, csExcludeFilter,bUseRegularExpression); if(bWorked) { do { bWorked = fileInfo.FindNextFile(); // Do something with the files... } while(bWorked); } Anyone who has used CFileFind knows that it is annoying to have to call FindNextFile() before ever even using the file first found in the first call to FindFile(). In trying to make this class work as much like the original as possible, it was tricky to duplicate this illogical logic. However, I think I figured out a way to do it and it seems to work without running any slower than the original in my tests. I've only started using this class so it is pretty new, but I've tested it quite a bit using the included sample program to make sure that my version was just as annoying as the original since we've all gotten kind of used to it. FindNextFile() Find.
https://www.codeproject.com/articles/11627/cfilefindex?fid=215666&df=90&mpp=25&noise=3&prof=true&sort=position&view=none&spc=relaxed&fr=26
CC-MAIN-2017-13
refinedweb
840
65.12
Post your Comment Replacing a Node with a New One Replacing a Node with a New One This Example shows you how to Replace a node with existing...:- Node before replacing is :Companyname Node after replacing name is:Id Splitting One Text Node into Three Splitting One Text Node into Three  ... into three new Node in a DOM document. Methods which are used for splitting... paragraph = (Element) root.getFirstChild():-creates a new node named paragraph Xml append node problem in a different document than the one that created it. Now that, I already have a node "nd...: WRONGDOCUMENTERR: A node is used in a different document than the one that created... to append a new node. <?xml version="1.0" encoding="UTF-8" standalone="no"?>< Node class Node class hii, What is a node class? hello, A node class is a class that has added new services or functionality beyond the services inherited from its base class JTree Remove Node , it will take node name (New Volume (E:)) in the input box and click the "OK"... Removing a Node from the JTree Component  ... to remove a node from the JTree component. Removing a node from JTree it means Insert a Processing Instruction and a Comment Node root.insertBefore(instruction, node):- This method inserts a new child node before an existing child node. Here new node is instruction and existing... Insert a Processing Instruction and a Comment Node   Java--Xml Modify Node Value - Java Beginners Java--Xml Modify Node Value I have the following xml. test... void main(String[] arg){ try { //SAXReader reader = new..."); BufferedReader bf = new BufferedReader(new InputStreamReader(System.in Java get Node Text Java get Node Text  ... of the node in the specified XML file. For this we have create a 'employee.xml' file... code, we want to describe you how to obtain the text of the node in the java Java get Node Value Java get Node Value In this section, you will learn how to obtain the node value...()- This method allows direct access to the child node that is the root element Locate a Node and Change Its Content Locate a Node and Change Its Content  ... of a node in a DOM document. JAXP (Java API for XML Processing) is an interface... is used to create new DOM parsers. These are some of the methods used in code given Listening for Changes to Preference Values in a Preference Node Listening for Changes to Preference Values in a Preference Node... to change the Preference values in a Preference node. You can see in the given... a preference is added, changed, or removed from a preference node if the application Java Xml -Node retrieval - Java Beginners Java Xml -Node retrieval I have the following xml test... = DocumentBuilderFactory.newInstance(); File xmlFile2 = new File("D:\\XML_Utility\\Version 11... java.text.SimpleDateFormat; public class XMLParser{ Date date=new Date(); Java-Xml -Modify and Update Node - Java Beginners date=new Date(); public static void main(String[] args) throws IOException{ XMLParser detail = new XMLParser("buyer.xml"); } public XMLParser(String str){ try{ File file = new File(str); if (file.exists()){ SAXParserFactory New to Java - New to java tutorial to the Email Address use one more argument for name. Address address = new.... Properties props = new Properties(); // code to fill props with any... a unique session by getInstance() method… Properties props = new Properties JavaScript setAttributeNode method a new attribute node to the specified element. Syntax:  ... reference whose attribute node is to be set and attribute_name is the name of the attribute node which we want to set with some specific value. If the attribute JPA One-to-One Relationship JPA One-to-One Relationship  ... will learn about the one-to-one relationship. In the one-to-one relation mapping a single value association to another entity. One-to-One: In one-to-one New to programming... Are you New to Java Programming Language? Learn the how you can Java programming language? Java is one of the popular programming language... development framework. New Zealand , the population of New Zealand is 4,393,500, that makes it one of the least densely populated... is one of the hottest tourists spots in New Zealand. View Latitude and Longitude... it one of the least densely populated country in the world. The capital Post your Comment
http://www.roseindia.net/discussion/21819-Replacing-a-Node-with-a-New-One.html
CC-MAIN-2016-07
refinedweb
716
66.84
The solution begins by first finding out if there is a cyle or not. If no cycle then return null. To find out the cycle use the slow, fast pointer technique. Once it has been established that cycle exists, find out the distance of the intersect node from the head of the list. Also find out the size of the loop. Now the question reduces to finding the common element in two linked lists. One list starts at head, and the other one starts at intersect node. To do this align the nodes such that they are both the same distance away from the end(intersect). Once this is done, you just have to increment and check if the nodes are equal or not. public class Solution { public ListNode detectCycle(ListNode head) { if (head == null) return head; //first check whether cycle exists or not ListNode first, second; first = second = head; while(true){ first = first.next; if (second.next != null) second = second.next; else return null; if (second.next != null) second = second.next; else return null; if (first == second) break;//list contains a cycle break } //cycle exists store the intersect node ListNode intersect = first; first = head; int k = 1;//the distance of the intersect node from head while(true){ if (first == intersect) break; first = first.next; k++; } //the intersection is at distance k away from the head; //now get the size of the loop int s = 0;first = intersect; while(true){ first = first.next; s++; if (first == intersect) break; } //s is the size of the loop now //now the question reduces to find the first intersecting element //of two linked lists, list1 starts at head, list2 starts at intersect now //the first step is to align the nodes so they are at the same distance from the end(intersect node) first = head;second = intersect; if (s > k){ for(int i = s; i < k;i++) second = second.next; }else{ for(int j = k; j < s; j++) first = first.next; } while(true){ if (first == second) return first; first = first.next; second = second.next; } } }
https://discuss.leetcode.com/topic/5627/o-n-time-o-1-space-a-different-approach-to-finding-the-start-of-cycle
CC-MAIN-2017-39
refinedweb
340
72.36
What database are you using? SQL server, MySQL, Access...? ADO.net has the ability to create SQL server databases on the fly using the System.data.sqlClient class namespace. see MS Knowledge base: VB.net:;EN-US;305079 C#.net:;EN-US;307283 other links on the above pages for C++ and J# More information can be found about .NET (including ADO.NET) at : Feel free to email me if you have any questions Hello, IF what i understand is right then what you need to do is in the Web.Config file tell the authentication mode to Windows and in the Authorized tag specify the users that you want to allow or deny access. otherwise if this is not the scenario then what i think is you want to restrict the user from viewing certain information. well that can be done by assigning access rights to the Database Users. through the Database. and then set the Authentication mode in the Web.Config file to Forms .... and then use the Form to take the Username as input and then use it to login to the database. Hope this helps. Take Care. ASP .NET Is there any way that they can use ASP with simple Domain user (Windows 2000) rights? This conversation is currently closed to new comments.
http://www.techrepublic.com/forums/discussions/asp-net/
CC-MAIN-2017-09
refinedweb
217
76.93
Posted 15 Sep 2015 Link to this post Hello, at the moment I am evaluating the Telerik Richtextbox and I want to use it in my LightSwitch-Application. Everything works fine so far and now I want to customize the InsertHyperlinkDialog to my purpose. Therefore I have downloaded the sample "CustomInsertHyperlinkDialog" from your website. Then I added the two files InsertHyperlinkDialog.xaml and InsertHyperlinkDialog.xaml.cs to my Silverlight "SilverlightControls" where the RichTextBox is located. Then I have changed the namespace of InsertHyperlinkDialog.xaml.cs to Silverlightcontrols and I have also changed the x:Class in InsertHyperlinkDialog.xaml to x:Class="SilverlightControls.InsertHyperlinkDialog" What to I have to do that my custom window is used instead of the standard window? I have tried to use the code provided in the sample within radRichTextBox_HyperlinkClicked: this.radRichTextBox.Commands.ShowInsertHyperlinkDialogCommand.Execute(); But this seems to do nothing. And I have also tried to create a new instance of InsertHyperlinkDialog: InsertHyperlinkDialog hyperDialog = new InsertHyperlinkDialog(); hyperDialog.ShowDialog(); When I try this, my custom dialog and the standard dialog are going to be opened. And nothing happens when I try to Insert an hyperlink using my custom control. What do I have to do to make this work? Posted 15 Sep 2015 in reply to Thomas Link to this post I have tried to make this work all day. But it just won´t work. It always opens the original Dialog when I call "this.radRichTextBox.Commands.ShowInsertHyperlinkDialogCommand.Execute();" I cant figure out where the RichTextBox is told to open the custom Dialog and not the original one? I am using [CustomInsertHyperlink] within "InsertHyperlinkDialog.xaml.cs" but this code never gets executed. When I use the example it is executed when I call "this.radRichTextBox.Commands.ShowInsertHyperlinkDialogCommand.Execute". But why not in my Solution? Do I need more files than "InsertHyperlinkDialog.xaml.cs" and "InsertHyperlinkDialog.xaml" to use a custom Dialog? Or is there a Problem to use a custom Dialog inside Lightswitch? Thanks, Thomas Posted 17 Sep 2015 Link to this post this .radRichTextBox.InsertHyperlinkDialog = new CustomInsertHyperlinkDial
http://www.telerik.com/forums/customize-inserthyperlinkdialog-using-the-custominserthyperlinkdialog--sample
CC-MAIN-2017-17
refinedweb
342
52.46
Manipulate arrays of complex data structures as easily as Numpy. Project description awkward-array is a pure Python+Numpy library for manipulating complex data structures as you would Numpy arrays. Even if your data structures - contain variable-length lists (jagged or ragged), - are deeply nested (record structure), - have different data types in the same list (heterogeneous), - are masked, bit-masked, or index-mapped (nullable), - contain cross-references or even cyclic references, - need to be Python class instances on demand, - are not defined at every point (sparse), - are not contiguous in memory, - should not be loaded into memory all at once (lazy), this library can access them with the efficiency of Numpy arrays. They may be converted from JSON or Python data, loaded from “awkd” files, HDF5, Parquet, or ROOT files, or they may be views into memory buffers like Arrow. Consider this monstrosity: import awkward array = awkward.fromiter([[1.1, 2.2, None, 3.3, None], [4.4, [5.5]], [{"x": 6, "y": {"z": 7}}, None, {"x": 8, "y": {"z": 9}}] ]) It’s a list of lists; the first contains numbers and None, the second contains a sub-sub-list, and the third defines nested records. If we print this out, we see that it is called a JaggedArray: array # returns <JaggedArray [[1.1 2.2 None 3.3 None] [4.4 [5.5]] [<Row 0> None <Row 1>]] at 79093e598f98> and we get the full Python structure back by calling array.tolist(): array.tolist() # returns [[1.1, 2.2, None, 3.3, None], # [4.4, [5.5]], # [{'x': 6, 'y': {'z': 7}}, None, {'x': 8, 'y': {'z': 9}}]] But we can also manipulate it as though it were a Numpy array. We can, for instance, take the first two elements of each sub-list (slicing the second dimension): array[:, :2] # returns <JaggedArray [[1.1 2.2] [4.4 [5.5]] [<Row 0> None]] at 79093e5ab080> or the last two: array[:, -2:] # returns <JaggedArray [[3.3 None] [4.4 [5.5]] [None <Row 1>]] at 79093e5ab3c8> Internally, the data has been rearranged into a columnar form, with all values at a given level of hierarchy in the same array. Numpy-like slicing, masking, and fancy indexing are translated into Numpy operations on these internal arrays: they are not implemented with Python for loops! To see some of this structure, ask for the content of the array: array.content # returns <IndexedMaskedArray [1.1 2.2 None ... <Row 0> None <Row 1>] at 79093e598ef0> Notice that the boundaries between sub-lists are gone: they exist only at the JaggedArray level. This IndexedMaskedArray level handles the None values in the data. If we dig further, we’ll find a UnionArray to handle the mixture of sub-lists and sub-sub-lists and record structures. If we dig deeply enough, we’ll find the numerical data: array.content.content.contents[0] # returns array([1.1, 2.2, 3.3, 4.4]) array.content.content.contents[1].content # returns array([5.5]) Perhaps most importantly, Numpy’s universal functions (operations that apply to every element in an array) can be used on our array. This, too, goes straight to the columnar data and preserves structure. array + 100 # returns <JaggedArray [[101.1 102.2 None 103.3 None] # [104.4 [105.5]] # [<Row 0> None <Row 1>]] at 724509ffe2e8> (array + 100).tolist() # returns [[101.1, 102.2, None, 103.3, None], # [104.4, [105.5]], # [{'x': 106, 'y': {'z': 107}}, None, {'x': 108, 'y': {'z': 109}}]] numpy.sin(array) # returns <JaggedArray [[0.8912073600614354 0.8084964038195901 None -0.1577456941432482 None] # [-0.951602073889516 [-0.70554033]] # [<Row 0> None <Row 1>]] at 70a40c3a61d0> Rather than matching the speed of compiled code, this can exceed the speed of compiled code (on non-columnar data) because the operation may be vectorized on awkward-array’s underlying columnar arrays. (To do: performance example to substantiate that claim.) Installation Install awkward-array like any other Python package: pip install awkward or similar (use sudo, --user, virtualenv, or pip-in-conda if you wish). 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/awkward/
CC-MAIN-2019-04
refinedweb
697
66.74
Contents - 1 How to Rename Columns in Pandas? - 2 Create a Sample Pandas DataFrame - 3 Change Column Names in Pandas with Column Attribute - 4 Change Column Names in Pandas with set_axis() - 5 Rename Column Names in Pandas with rename() How to Rename Columns in Pandas? In this tutorial, we will show you various ways how to rename column in Pandas dataframe. In specific we will cover three main approaches of columns attribute, set_axis(), and rename() function for pandas rename of columns along with examples. Create a Sample Pandas DataFrame Let us create a sample dataframe in pandas that will be used in all the subsequent examples to change column name in Pandas. In [0]: import pandas as pd; # create a dataframe data = {'Employee_No': ['E0001', 'E0002', 'E0003', 'E0004'], 'Employee_Name': ['John', 'Ron', 'Sam', 'Alice'], 'Department':['Sales','Sales','Finance','Finance']} df = pd.DataFrame(data) df Out[0]: Change Column Names in Pandas with Column Attribute Example 1 The first way to change the column name in pandas is to use the column attribute of the datframe. As shown in the below example, we have assigned the list of columns with modified names to df.column attribute. It should be noted here that even though we don’t want to change the names of all columns, it is mandatory to pass all names of columns. Otherwise, it will throw an error. In the below example we wanted to rename Employee_Id to Emp_Id and Emloyee_Name to Emp_Name. But still, we passed the Department column even though it was unchanged. In [1]: df.columns = ["Emp_Id", "Emp_Name", "Department"] df Out [1]: Change Column Names in Pandas with set_axis() Example 2 In this example, we shall use set_axis attribute of Pandas to modify the column name. Just like the previous approach, here also we have to pass the entire list of columns even though we want to change just the first two columns. The axis = 1 tells pandas that the changes are to be applied on the columns and also inplace = True is used so that changes are persisted in the current dataframe df. In [2]: df.set_axis(["Emp_Id", "Emp_Name", "Department"], axis=1, inplace = True) df Out [2]: Rename Column Names in Pandas with rename() In the earlier examples with column and set_axis attributes, we had to pass the entire list of columns even though we had a requirement to change an only couple of them. It is okay when the total number of columns is less but when there are hundreds of columns then it is not practical to pass all column names just to change a couple of them. This is where rename() comes in very handy as it lets you work with only the column that needs to be renamed in pandas. And it also supports the use of the lambda function to let you modify the columns programmatically. Let us understand this with various examples. Example 3 In this example, we are passing the mapping of existing and new column names in the dictionary data structure to rename() function. It should be noted that here only those columns are passed that are to be renamed. Also, the axis =1 tells Pandas that this rename is for columns and inplace=True allows the change to persist in place in the dataframe. In [3]: df.rename({'Employee_No':'Emp_Id', 'Employee_Name':'Emp_Name'}, axis=1, inplace = True) df Out [3]: Example 4 This is another variation of the above example of columns rename in Pandas. Instead of passing axis=1 we are using columns parameter to assign the dictionary mapping of old and new column names. In [4]: df.rename(columns= {'Employee_No':'Emp_Id', 'Employee_Name':'Emp_Name' }, inplace = True) df Out [4]: Example 5 – Rename Column Names to Lower Case in Pandas It is quite easy to rename all columns of pandas dataframe to lower case with rename() function as shown in the below example. Isn’t it cool? In [5]: df.rename(columns= str.lower, inplace = True) df Out [5]: Example 6 – Change Column Names to Upper Case in Pandas Just like the above example, we can also change column names to upper cases with rename() function as shown below. In [6]: df.rename(columns= str.upper, inplace = True) df Out[6]: Example 7 – Rename Pandas Column Names with Lambda Function If you wish to change rename columns of pandas dataframe programmatically it can be done by rename() by using lambda function. This really adds to the flexibility and power that rename() function offers. In our example, we wish to add the prefix ‘Cmp_’ in front of every column name. Rather than doing this manually, we have done this with the lambda function as shown below. Lambda function opens the whole new possibilities of renaming columns as you want just with a line of code. In [7]: df.rename(columns=lambda x: 'Cmp_'+ x, inplace = True) df Out[7]: Reference – Pandas Documentation
https://machinelearningknowledge.ai/how-to-rename-column-in-pandas-dataframe/
CC-MAIN-2022-33
refinedweb
812
60.75
Performance is a very key aspect of modern day web applications. And especially if your application users are on mobile devices with slow connections. Running performance audits and checks every day is not easy and we often don’t do that. So why don’t we automate this stuff and add checks at necessary places? This is exactly what we will do by learning how to run Lighthouse performance audits on every pull request. The plot So, I am working on a GatsbyJS web application and I am very specific to having a good performance. I want my application to score high on Lighthouse metrics. I can keep running performance audits every now and then, but I want more control over which piece of code commit caused my application performance to degrade. Rather than doing these tests manually, why don’t we diagnose and run tests at pull request time? We can do this using Continuous Integration (CI) isn’t it. And it’s a fantastic way of catching regressions before merging. This is exactly what we will achieve in this article. With all the modern tooling out there at our disposal, it’s not too difficult actually. Let’s get started. What is Lighthouse? Lighthouse is an open-source, automated tool from Google for improving the quality of web pages. For us, we will be using the Lighthouse Node module. Context The application that my tutorial uses is a GatsbyJS web application. So the NPM scripts (to run tests) that you will see here are Gatsby specific. But the learnings from this article is not limited to Gatsby. You can apply the same technique to any app – React SPA, React SSR, Vanilla HTML/CSS/JS app. Anything that runs on the browser. CI/CD Pipeline For running Continuous Integration builds I am using CircleCI. CircleCI works right out of the box with Github. My project is already on Github and every time I make a commit to a Pull Request, the Lighthouse performance audit will run on a CI container hosted by CircleCI. So the first thing to do would be to create a free account on CircleCI. Once you login to CircleCI, it will show up all your Github projects (including private repo). Go ahead and set up your project. Getting Started Fork out a branch from the master branch. git checkout -b feature-branch We will create a PR from this branch to master. Next, create a new folder in the root of your project named .circleci and create a new file named config.yml inside it. Now, copy the YAML config below and paste it inside config.yml file. version: 2.1 aliases: restore_cache: &restore_cache restore_cache: name: Restore node_modules cache keys: - yarn-cache-{{ checksum "yarn.lock" }} install_node_modules: &install_node_modules run: name: Install node modules command: yarn --frozen-lockfile persist_cache: &persist_cache save_cache: name: Save node modules cache key: yarn-cache-{{ checksum "yarn.lock" }} paths: - ~/.cache jobs: test-lighthouse: docker: - image: circleci/node:10-browsers steps: - checkout - <<: *restore_cache - <<: *install_node_modules - <<: *persist_cache - run: yarn clean - run: yarn build - run: yarn test:lighthouse workflows: version: 2 performance-audit: jobs: - test-lighthouse So this will be the build instructions to CircleCI. There are three important commands towards the end of the file. - run: yarn clean - run: yarn build - run: yarn test:lighthouse yarn clean cleans up the production bundle. yarn build generates the production bundle again. These are Gatsby specific commands. Replace with the commands that defines your production builds for whatever project you are working on. The last command runs the Lighthouse test on the CI/CD container. Just to reiterate we run Lighthouse audits on production builds. I will talk more about this command in the sections below. Let’s move onto the next step and write our test code. NPM modules we need We need the following node modules/packages for our set up. - lighthouse: to run performance audits for us. This is the main tool. - chrome-launcher: to launch Google Chrome with ease from code. - jest: for running tests. It’s a Testing framework. - cli-table: to show tabular logs in the terminal. - start-server-and-test: starts server, waits for URL, then runs test command; when the tests end, shuts down the server. Go ahead and install these as dev dependencies inside your project yarn add --dev lighthouse jest cli-table chrome-launcher start-server-and-test Your package.json should look like this after installation, "devDependencies": { "chrome-launcher": "^0.13.1", "cli-table": "^0.3.1", "jest": "^25.3.0", "lighthouse": "^5.6.0", "start-server-and-test": "^1.10.11" } The versions of individual packages might differ when you are trying this out. Writing the Test File Now let’s write our tests. Create a new file named lighthouse.test.js inside the project root. touch lighthouse.test.js Copy the code below and paste it inside the test file. const lighthouse = require('lighthouse'); const chromeLauncher = require('chrome-launcher'); const fs = require('fs'); var Table = require('cli-table'); const flags = {onlyCategories: ['performance']}; //if you only need performance scores from lighthouse // instantiate cli table var table = new Table({ head: ['Key', 'Score'] }); function printCLITable(scores) { Object.keys(scores).forEach((key, index) => { table.push([key, scores[key]]); }); return table.toString(); } function launchChromeAndRunLighthouse(url, opts = {}, config = null) { return chromeLauncher.launch({chromeFlags: opts.chromeFlags}).then(chrome => { opts.port = chrome.port; return lighthouse(url, opts, config).then(results => { // use results.lhr for the JS-consumable output // // use results.report for the HTML/JSON/CSV output as a string // use results.artifacts for the trace/screenshots/other specific case you need (rarer) return chrome.kill().then(() => results) }); }); } test('Lighthouse Prformance Audit', async () => { const { lhr, report } = await launchChromeAndRunLighthouse(''); //flags //create reports //fs.writeFileSync('./report.html', report); //lhr.categories is an object const scores = {}; const categories = lhr.categories; for(let key in categories) { scores[key] = categories[key].score; } //console.log(scores); //eg. {performance: 0.98, seo: 0.97, accessibility: 0.99..} console.log(printCLITable(scores)); expect(scores.performance).toBeGreaterThanOrEqual(0.95); //95% // expect(scores.accessibility).toBe(1) // expect(scores['best-practices']).toBeGreaterThanOrEqual(0.93) //expect(scores.seo).toBe(1) }, 30000); We will use JEST to run this file. Let me explain the important bits. We import lighthouse and chome-launcher node modules. We start our lighthouse test by launching a Chrome instance and passing the URL to test to the lighthouse instance. We get the scores that come inside the lhr.categories property. We loop through it and read the scores for performance, SEO, accessibility and other metrics. We print the scores in a tabular log and finally run our JEST assertion. Lighthouse scores are reported between 0 -1. 1 represents the highest score of 100. So in our example above, I have been a little soft on the benchmark. You can modify it as per your needs and performance standards. You can read more from the official lighthouse git repo. is the URL where Gatsby serves a production build. You can replace this with your’s accordingly. Now you may ask me – who starts a server inside my CI/CD container? CircleCI will do it for you. It will run the build inside a Docker container so it has everything necessary it needs. And that’s exactly where we are going next. The test report log will look like this, Adding necessary NPM scripts Alright, onto the last part now. Add these NPM scripts inside package.json file. "scripts": { "test": "jest", "test:lighthouse": "start-server-and-test serve test" }, test:lighthouse is the command that will run our Lighthouse perf audit. If you remember, we have added this inside config.yml file. This command has a few important parts to it. Let me break it down. - start-server-and-test: is the NPM module we installed earlier. It will start a server, wait for the URL, run a test and exit. - serve: is the gatsby serve command which is part of scripts inside package.json. This serves a production bundle at localhost:9000 -: is the URL to test. Our production app. - test: runs the test command inside scripts. This will invoke JEST to run the unit test written inside lighthouse.test.js file The two NPM scripts added above are additional scripts to what Gatsby already provides us by default. Example below. "scripts": { "build": "gatsby build", "develop": "gatsby develop", "format": "prettier --write \"**/*.{js,jsx,json,md}\"", "start": "npm run develop", "serve": "gatsby serve", "clean": "gatsby clean" }, Now let’s run our test. Finally 🙂 Run the Lighthouse performance audits You can run the test on your computer once. Just to try things out. Run the command below in the terminal from your project root. yarn test:lighthouse It should launch Google Chrome, run the tests and generate a report. Now, commit your changes to Github and create a Pull Request to master. git commit -m "my lighthouse test" CircleCI will automatically trigger a build. Meanwhile, your Pull request will show the status of the test Once the test runs successfully and it passed, you will see the test logs inside CircleCI dashboard. Your Github Pull Request will also update accordingly Let’s fail the performance audit To test out if our assertions are correct, I intentionally added some large JS & CSS libraries to my index page and degraded the performance of my Gatsby app. import _ from 'lodash'; import 'bulma/css/bulma.css'; I also increased my performance benchmark. expect(scores.performance).toBe(1); Commit the changes to Github. CircleCI triggers the build again. Lighthouse comes back with negative results. Github PR also shows the negative status This is a fantastic way to detect performance regressions and exactly find out which commit or PR caused your app’s performance to degrade. I hope you find this useful and would definitely give this a try. Cheers! If you enjoyed this post and want similar articles to be delivered to your inbox directly, you can subscribe to my newsletters. I send out an email every two weeks with new articles, tips & tricks, news, free materials. No spamming, of course.
https://josephkhan.me/run-lighthouse-performance-audits/
CC-MAIN-2020-40
refinedweb
1,672
68.47
Overview Atlassian Sourcetree is a free Git and Mercurial client for Windows. Atlassian Sourcetree is a free Git and Mercurial client for Mac. ppx_implicits, implicit arguments and type classes for OCaml via PPX ppx_implicits provides implicit arguments: omittable function arguments whose default values are automatically generated from their types. Overloading, type-classes, polymorphic value printers, etc ... can be defined/mimicked with implicit arguments. ppx_implicits is NOT a compiler modification but a PPX preprocessor. You can play type classes and etc with your official OCaml compiler. Simple overloading Let's start with a simple example of overloaded add function which can work both for int and float additions. Here are two addition functions for int and float in OCaml which we want to overload to one function add: val (+) : int -> int -> int val (+.) : float -> float -> float We first gather them in a single module, a namespace for overload instances: module Add = struct let int = (+) let float = (+.) end Then, define a type for overloading, the type of implicit argument for add: type 'a add = ('a -> 'a -> 'a, [%imp Add]) Ppx_implicits.t In ppx_implicits, (ty, spec) Ppx_implicits.t is the special type for implicit arguments: roughly equivalent with type ty whose default value is determined by spec. In this case, 'a add is equivalent with type 'a -> 'a -> 'a, the most general anti-unifier type of the types of (+) : int -> int -> int and (+.) : float -> float -> float, and its default value is composed using the values defined in a module named Add. We can define the overloaded add function using this type: let add : ?d:'a add -> 'a -> 'a -> 'a = Ppx_implicits.imp val Ppx_implicits.imp : ?d:('a,'spec) Ppx_implicits.t -> 'a is the extractor function of implicit arguments. If the optional argument is applied then it simply gets the value of ty encapsulated in (ty, spec) Ppx_implicits.t. If the optional argument is omitted, the function fails, but it should not happen with ppx_implicits: if omitted, the optional argument of type (ty, spec) Ppx_implicits.t is applied automatically by ppx_implicits, using spec. add function is just an alias of this Ppx_implicits.imp but with a stricter type: if the optional argument of add is omitted, it is auto-applied according to the spec [%imp Add] which means using the values defined in the module named Add. Here is an example of such auto-application: let () = assert (add 1 1 = 2) Ppx_implicits converts the above code to: let () = assert (add ~d:(Ppx_implicits.embed Add.int) 1 1 = 2) where Ppx_implicits.embed encapsulate its argument into (ty,spec) Ppx_implicits.t. Another exapmle of add used for float addition: let () = assert (add 1.2 3.4 = 4.6) This time, ppx_implicits converts to let () = assert (add ~d:(Ppx_implicits.embed Add.float) 1 1 = 2) Here is the whole code: module Add = struct let int = (+) let float = (+.) end type 'a add = ('a -> 'a -> 'a, [%imp Add]) Ppx_implicits.t let add : ?d:'a add -> 'a -> 'a -> 'a = Ppx_implicits.imp let () = assert (add 1 2 = 3) let () = assert (add 1.2 3.4 = 4.6) Limitation ppx_implicits does not work with OCaml toplevel (REPL). Please use ocamlc or ocamlopt. This is due to the limitation of PPX framework, which cannot pass big information from preprocessing of one compilation unit to another. In the toplevel, the compilation unit is each toplevel expression and ppx_implicits cannot share important typing information between toplevel expressions. This could be fixed by keeping one PPX process running throughout an REPL session, but it would need significant change of the REPL... How to build opam install ppx_implicits. Probably it may be not the latest version. The development version source code is available at, but it is likely dependent on development versions of other libraries: $ hg clone $ cd ppx_implicits $ cp OMakeroot.in OMakeroot $ omake $ omake install How to use Add -package ppx_implicits to your ocamlfind calls. If you do not use ocamlfind, add -ppx ppx_implicits to your compiler commands. Type class Type class is one of the most complicated example of ppx_implicits but everyone loves type classes so let's start with it. Class declaration In ppx_implicits, type classes are defined like as follows: module type Show = sig type a val show : a -> string end [@@typeclass] This is almost equivalent with the following type class definition in Haskell: -- Haskell class Show a where show :: a -> String A module type definition with attribute [@@typeclass] defines a module of the same name. The values declared in the signature are available as values in the module. In the above example, ppx_implicits defines a module named Show with a value show. Its signature is: module Show : sig val show : ?_imp: 'a Show._class -> 'a -> string end Optional arguements labeled with ?_xxx are considered as type class constraints by ppx_implicits. The above signature is almost equivalent with the following Haskell signature: show :: 'a Show => 'a -> string Instance declaration Now let's define instances of Show: module M = struct (* Instance for int *) module Int = struct type a = int let show = string_of_int end [@@instance Show] (* Instance for float *) module Float = struct type a = float let show = string_of_float end [@@instance Show] end A module declaration with [@@instance PATH] is to declare an instance of type class PATH. The module must have a signature less general than the module type PATH. Haskell equivalent of the above code is like as follows: -- Haskell module M where instance Show Int where show = string_of_int -- Haskell has Double instead of Float actually... never mind instance Show Float where show = string_of_float Use of overloaded values Show.show is now usable. Which instances should be used is controlled by open statement: open M let () = assert (Show.show 1 = "1") let () = assert (Show.show 1.2 = "1.2") Here, open M makes the instances declarations under M available for the use of Show.show. It is as same as import M controls instance availableness in Haskell: -- Haskell import M import qualified Show main :: IO () main = do -- Haskell overloads number literals... assert (Show.show (1 :: Int) = "1") $ return () assert (Show.show (1.2 :: Float) = "1.2") $ return () Overloading is first class You can define a new overloaded value from one defined with [@@typeclass]. So far, manual wiring of constraint labels is required, either by explicit applications of dispatch show ?_imp x or by an explicit type annotation: (* Explicit dispatching by application *) let show_twice : ?_imp x = show ?_imp x ^ show ?_imp x let () = assert (show_twice 1.2 = "1.21.2") or (* Explicit dispatching by type annotation *) let show_twice' : ?_imp: 'a Show._class -> 'a -> string = fun ?_imp x -> show x ^ show x let () = assert (show_twice' 1.2 = "1.21.2") They are similar to the following Haskell code: -- Haskell show_twice :: Show a => a -> string show_twice x = show x ++ show x This explicit wiring is unfortunate but currently necessary in ppx_implicits. Implicit values Ok, now let's go back to the basics of ppx_implicits. [%imp SPEC] expression Special expression [%imp SPEC] is for implicit values, whose definitions are dependent on the context type of the expression and automatically composed from the values specified by SPEC. For example, the expression [%imp Show] is expaneded using the values defined under module Show: module Show = struct let int = string_of_int let float = string_of_float end let () = assert ([%imp Show] 1 = "1") (* [%imp Show] is expanded to Show.int *) let () = assert ([%imp Show] 1.0 = "1.") (* [%imp Show] is expanded to Show.float *) The values for the composition are called instances. Instances can be combined recursively: module Show2 = struct include Show (* int and float are available *) let list ~_d:show xs = "[ " ^ String.concat "; " (List.map show xs) ^ " ]" (* currently a label starts with '_' is required to express instance dependencies *) end let () = assert ([%imp Show2] [ [ 1 ]; [ 2; 3 ]; [ 4; 5; 6 ] ] = "[ [ 1 ]; [ 2; 3 ]; [ 4; 5; 6 ] ]") (* [%imp Show] is expanded to Show2.(list ~_d:(list ~_d: int)) *) The special label which starts with _ attached to the argument of Show2.list denotes that the value is actually a higher order instance. Such labels of the form _LABEL or ?_LABEL are called constraint labels. If you know Haskell, constraint labels correspond with Haskell's special arrow for type classes: C => t. Instance search policies The spec is not a simple module path but forms a small DSL. For example, you can list policies by , to accumulate instances: module Show3 = struct let twin ~_d (x,y) = "(" ^ _d x ^ ", " ^ _d y ^ ")" end let () = assert ([%imp Show, Show3] ([ 1 ], [ 2; 3 ]) = "([ 1 ], [ 2; 3 ])") (* [%imp Show] is expanded to Show3.list ~_d:(Show3.twin ~_d: Show.int) *) You can also write opened PATH to specify multiple modules at once which exist just under the opened module paths named PATH. This is like Haskell's import to specify class instances: module MInt = struct module Show = struct let int = string_of_int end end module MFloat = struct module Show = struct let float = string_of_float end end module MList = struct module Show = struct let list ~_d:show xs = "[ " ^ String.concat "; " (List.map show xs) ^ " ]" end end open MInt open MFloat open MList let () = assert ([%imp opened Show] [ 1 ] = "[ 1 ]") (* MInt.Show, MFloat.Show and MList.Show are the instance space *) (* Here, [%imp opened Show] is equivalent with [%imp MInt.Show, MFloat.Show, MList.Show] *) Type dependent instance spec With some conditions, we can simply write [%imp] and omit its spec. The spec of [%imp] is type-dependent: it is deduced from the type information of the expression. - The type of [%imp]must be (t1,..,tn) PATH.nameor (t1,...,tn) PATH.name optionor their alias, so that the spec can be found in module PATH. - The module PATHmust have a special declaration [%%imp SPEC]for [%imp]expressions of a type related with PATH. For example, if we have module M = struct type 'a t = ... [%%imp SPEC] end and if an expression [%imp] has a type int M.t, it is equivalent with [%imp SPEC]. Let's use this [%imp] in an actual example: module M = struct type 'a t = Packed of 'a -> string [%%imp opened Show] end let show (M.Packed x) = x (* We use modules defined above *) open MInt open MFloat open MList let () = assert (show [%imp] [ 1 ] = "[ 1 ]") (* [%imp] has the type int list M.t. Module M has [%%imp opened Show] Therefore this [%imp] is equivalent with [%imp opened Show] *) We cannot define the type M.t simply as type 'a t = 'a -> string, since M.t must not be an alias. This is essential to associate data types and policies together. The form of the type of [%imp] is not only (t1,...,tn) PATH.name but also can be (t1,...,tn) PATH.name option. This is for efficient handling implicit parameters explained later. Default instances for type dependent [%imp] If [%imp]'s spec is defined in a module M, and if this module M has a module Instances, then the values defined in this M.Instances are considered as instances of the implicit value. Deriving value implicits You can let-define implicit values from other implicit values: let show (M.Packed x) = x let show_twice imp x = show imp x ^ show imp x let () = assert (show_twice [%imp] 1 = "11") show_twice function takes an implicit paramter imp and delivers it to its internal uses of show. The type information of the first argument of show_twice is as same as the one of the first argument of show, 'a M.t. Therefore show_twice [%imp] 1 works as intended using the spec defined in module M. This is classic but requires explicit code of implicit value dispatch. Actually you can let ppx_implicits to wire up this dispatch code more easily by explicitly writing some types: let show_twice ~_imp:(_:'a M.t) (x : 'a) = show [%imp] x ^ show [%imp] x When a function takes an argument with a constraint label ( _LABEL or ?_LABEL), the argument value is automatically added to the instance search spaces for all the occurrences of [%imp] and [%imp SPEC] in its scope. In the above example, the argument labeled _imp has type 'a M.t. The argument value is an instance of implicit values for 'a M.t inside the body of this function abstraction. The uses of [%imp] in the function body have the same type 'a M.t, therefore they are expanded to the argument value and the whole code becomes as follows: let show_twice ~_imp:(imp:'a M.t) (x : 'a) = show imp x ^ show imp x which is equivalent with the first example of show_twice with the explicit dispatch. Implicit parameters as optional parameter Optional constraint labels ?_LABEL: are as same as non-optional constraint labels ~_LABEL: but they are to provide implicit parameters. Implicit parameters can be omitted at function applications. If omitted, ppx_implicits applies Some [%imp] instead: (* Assume module M, MInt, MFloat and MList defined above are available *) let show ?_imp = match _imp with | None -> assert false | Some (M.Packed x) -> x let () = assert (show 1 = "1") (* ?_imp is omitted and it is equivalent with show ?_imp:None 1 ppx_implicits replaces it by show ?_imp:(Some [%imp]) 1 which is equivalent with show ?_imp:(Some [%imp opened Show]) 1 finally it is expanded to show ?_imp:(Some Show (M.Packed (MInt.Show.int))) 1 *) let () = assert (show 1.2 = "1.2") (* ?_imp is omitted and it is equivalent with show ?_imp:None 1.2 ppx_implicits replaces it by show ?_imp:(Some [%imp]) 1.2 which is equivalent with show ?_imp:(Some [%imp opened Show]) 1.2 finally it is expanded to show ?_imp:(Some Show (M.Packed (MFloat.Show.float))) 1 *) Now show is overloaded! Back to type class Implicit policies Expression [%imp SPEC] has SPEC parameter to specify the instance search space for the implicit value. SPEC is a comma separated list of sub-policies p1, .., pn Type dependent spec When [%imp] has no written policies, its spec is deduced from its static typing: [%imp]must have a type whose expanded form is either ... M.name' or... M.name option for some moduleM`. - Module Mmust have a declaration [%%imp SPEC]. Under these conditions [%imp]is equilvalent with [%imp SPEC]. related spec [%imp related] gathers instances from the modules appear in its type. For example if [%imp related] has a type 'a M.t N.t -> O.t option then its instances are obtained from module M, N and O. Note that types are unaliased in the current typing environment to get the module names for instances. For example if M.t is defined as type t = P.t * Q.t then module M is not considered as instance space but P and Q (if P.t and Q.t are not alias.). aggressive(p) spec By default, higher order implicit values have constraint labels ~_LABEL and ?_LABEL to receive instances. For example: val show_list_imp : ~_imp:('a -> string) -> 'a -> string here, ~_imp is the sole constraint of the function show_list_imp. Spec aggressive removes this limitation: any function arrow can be treated as constraint arrows. This is useful to use existing functions as implicit value instances without changing types. Suppose we have a function show_list of the following type: val show_list : ('a -> string) -> 'a list -> string If this function show_list is in an aggressive instance space, the function's arrows are treated as constraint arrows: the value is treated as if it had the following types: val show_list : ~_imp:('a -> string) -> 'a list -> string val show_list : ~_imp:('a -> string) -> ~_imp2:'a list -> string Note that one value can provide more than one instances. For example, show_list has two ways to be used as intances. The first one is useful to provide implicit show function combining other show_xxx functions, but the second one is probably useless. name "rex" p spec Spec name "rex" p filters the instances obtained from the spec p by the regular expression "rex". The regular expression must be one of PCRE. name is useful to restrict instances obtained by related which tends to collect undesired values. Recursion limit To assure the type inference of implicit values, recursive uses of instances are limited: if one instance x is composed like x ~_imp:x ..., then the type of the internal use must be strictly smaller than the one of the outer use.
https://bitbucket.org/camlspotter/ppx_implicits
CC-MAIN-2018-26
refinedweb
2,678
65.42
Welcome abroad, newcomers, I hope you'll enjoy Arch at least as much as I do Have you Syued today? Free music for free people! | Earthlings "Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away." -- A. de Saint-Exupery Offline Ok, after using Arch for about two months and lurking the forums and ML for most of that time: Hello everyone! Offline Hello everyone, I'm using Arch for about three months now. I'm reading along in the forums for quite a while now but never said hello. So as they say in the Netherlands: "Hallo allemaal" Last edited by Vintendo (2008-06-10 20:19:49) Offline I think this thread is more appropriate in the Newbie Corner subforum, so, moving it Have you Syued today? Free music for free people! | Earthlings "Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away." -- A. de Saint-Exupery Offline I posted this in another thread, but this is the correct place for it : Just wanted to say that I'm very impressed with this distro. I started off with Linux a few years back - Mandrake off and on, Smoothwall, Clarkconnect, Ubuntu for a few years - and now finally Arch. I'm not terribly experienced with the guts of Linux, but wanted to force myself to learn more of it, so here I am! I followed the beginner's wiki guide to install onto my laptop, which was pretty straightforward. It feels really good to be able to hand pick the bits you need and leave out the stuff you don't! So, thanks to all involved Offline I have deleted that thread, as you requested Have you Syued today? Free music for free people! | Earthlings "Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away." -- A. de Saint-Exupery Offline Thanks finferflu! Offline hi this is my 3rd installed linux distro, previous was slackware and opensuse. ive been using linux for 5 months and i believe console is the power, but its so hard to master, isnt it?) live and learn (or learn as u live edit: oh yes, i printed that 52 page beginners install manual, really helpful, because i dont have another pc to open the site and consult myself during installation, and 52 pages is hard to memorize )) Last edited by reasa1 (2008-06-13 02:55:43) Offline Hello! Very excited about this distro. I came to GNU/Linux about 8 years ago. Used it off and on since then. Mainly used for personal hobby projects for microcontroller communications and front end control GUI's for micontrollers. I have always jumped from Debian/Ubuntu/Fedora etc... Distro OCD Hell. For the first time I have found a Distro that I can call true Home. Installed a few weeks ago and could not be happier. My Wife does not understand my new found happiness. I just wanted to thank all of you very much for the hard work you done. I was listening to an old podcast from Linux Reality "Chess G" and this is where I heard about Arch. Again, Super Thanks to the people who put this together and maintain it. I will be looking over the next few weeks and see how I can also contribute. Offline Hey all. I am new to Arch (installed it a few days ago). I moved to Arch from Ubuntu distro, which was my first "serious" attempt for Linux. So far I like it though its way harder to handle for a noob like me I hope I will learn from this process and eventually it will improve my Linux knowledge. Aside from that, it seems like a great distro. Offline so, err, yeah, I've been on the distrohopping mood again lately, and it looks like i'm gonna land here for while, I might have to leave or stop drinking coffee if the experience stays the same - it appears that there's still a sense of humour amongst the newsletter team and on the forums. I might try and annihilate this by having clever plans like walking to the corner shop with no pants on in order to file a report for Rumor only to remember that I'm english so it's very unlikely the shopkeeper will notice unless I remove my trousers as well... So now I've done the custom flag-waving that say's I'm a muppet, I'm going to get down to the real buisness of making things work on my desktop, breaking my Eee, and looking to see who the smug git with all the fanboys is so I can publicly ask him one of those questions. Open Saucery isn't enough, we need Open Cakery too.. Offline Ahoy- I have been lurking on the forums and wiki for about 2 months so I figured it was time to say hello. Arch is my only linux experience to date and has been quite enjoyable. Arch was pretty scary 2 months ago, but the archlinux community is very helpful. Not to mention all the other resources at my disposal. I've found the answers to most of my questions and got my computer running arch with very little trouble. So thanks to everyone who worked very hard on all of this, and I look forward to learning more about linux with you folks. "Try not. Do. Or do not. There is no try." -Yoda Offline Hi, I'm Jakob, XAD because alle the other pseudonyms I use are taken. I installed Arch last week, after trying many many many different distro's where most failed to install, and the two that did not fail utterly, was sluggish or not quite on the bleeding edge (Mandriva and PCLOS). So now on what some would term an expert distro, I have a fully working system with bells and whistles, and I had not touched linux since sometime before y2k when getting a DK keymap just wouldn't happen in Red Hat "some low number" and I just left it. I knew basically only what you learn from a mandriva installation - nothing. I know something now and tomorrow I will know more - CU /J Offline Hi everybody, I am Robert, username blueskycatastrophe. I just installed Arch on a USB harddrive and, after some problems configuring GRUB, got it to boot from it. I have a eeePC 4G, so additional diskspace was required. I just got my networking working, after some fiddling with the rc.conf file... Forgot I use dhcp, so...well, anyway.. it works, I just pinged google.com and got a positive response. Pretty painless install and editing the configuration files takes me back to my slackware days. Sooo.... I'll be using arch as a host to finish building my LFS system and after that, I want to play around with the hurd and I needed a stable system for that too. I chose Arch mostly because of pacman. Now, I'll just get X to work and take it from there. Just thought I dropped in and said Hi...so, Hi! Offline I'm jo from the U.S.A. I'm a computer science flunky and a visual artist and singer and general mad scientist-type tinkerer with all things electronic. I've been using Arch for about two weeks I think. Put it on a Toshiba Satellite A205-S5825 out of the box and am playing with it on my old Dell Inspiron 1000, and seriously contemplating putting it on my custom build PIII server running Debian Sid right now. I like to dive right in and start helping and contributing right away, especially if there's some code or a package I need that I think others could use, and I figure this stuff out pretty quickly. I'm a big DIYer. Please pardon any sloppy posting on my part. I'm dyslexic and have trouble catching all my typos/left-out words. : () { : | :& } ;: Offline #include <brain.h> int main() { printf ("\n\t Hello, arch users! \n\n"); return 0; } I'm Ugljesha from Serbia. Student of Faculty of Technical Sciences in Novi Sad, Republic of Serbia, Programming, and computer sciences. In the beginning struggled with Ubuntu, afterwards driving a bit of arch, but transfered to Gentoo. Since I do not have to much time for learning Gentoo, got back to good old distro - archlinux. Hope to read you all in the future. Life is a big chair, so just sit & enjoy. #include <brain.h> Offline Hey everyone, I have used Arch for about a few months, I really enjoy using this as my primary distro, never I had to bother looking back at other distros, everything I wanted and needed was here. For a few years I have jumped from Suse > Debian > Ubuntu > Gentoo and now Arch. After a while of using Arch, I actually feel the comfort of GNU/Linux, everything being so simple and flexible. Arch (right now) has been the second longest used distro compared to Debian. I have Arch currently installed on my Thinkpad X61s and I could not be anymore happier. The fact that you can install packages from the bottom-up with a base install, was an enjoyable experience with a great package manager all together. It gives me great sentimental value for what I done. What I really appreciate the most is the well documented wiki and the support of the community, I have read around the forums for the past couple of months, which allowed me to learn more about Linux then any other distro, at much more accelerated rate, so I thank you all. I hope to continue learning more. Offline Hello everyone, I'm new to both Arch and Linux, and have been using Xubuntu for a couple of months before switching to Arch. I'm liking it a lot . One thing that I think is great about this distro is that it has the best wiki and forum I've ever read! Cheers. --- My thanks and respect for all you Arch developers Offline Hi All ! I am from Chennai , India aged 47. My linux journey started in 2001-02 and there is no looking back. I started with RH7 (for a week) and moved on to Mandrake (was a long time OS on my disk). Introduced to Slackware by a friend which made me learn linux esp. CLI, tried PCLOS, Ubuntu / Kubuntu, Debian, Vector, Zenwalk, Slax, Puppy, Arch 64, myahos, Lunar etc. Returned back to Arch now which has never let me down. And pacman ! The finest asset Arch has in it ! It has made windows installers run for their money. And the community ! I feel as if I am in the company of my family when I am in the Arch fora. Good Luck ! Linux learner and admirer - ALWAYS Regd Linux User : 431318 Offline Hi ! I'm Michael, from France. I'm quite new to Arch and Linux, although I installed Arch on my desktop (which I never use ) and I set up some Debian servers during my studies. I started to dig into Arch last week, when I uninstalled Windows from my laptop. It's soooo different from all these... hem... from this proprietary and ready-to-use-and-don't-ask-questions-it-works-so-touch-nothing OS I found Gentoo some months ago, asking myself "what Linux will I install when I drop M$ ?", and thought it was the kind of distro I wanted. Then I found Arch, and I knew it was the distro I wanted No bloatware, you set up the system you want, so you know how it works, how to maintain it, and you learn so many things doing this way... Oh, and you don't have to compile every piece of software... And you have a nice wiki, nice forums, and a nice logo So Hello World ! It's my first serious attempt at using Linux in my every day life, and it's also my first contact with the famous Open Source Community Offline Hi, I'm Ben. Been using linux for a few years now and tried quite a few different distros (Ubuntu, Debian, Fedora, Mint, OpenSuse, Sabayon, Meppis) tried Arch before when I first started using linux but found it too hard to setup so went with another distro but after getting bored of ubuntu i decided to give it another go and I'm loving it so far, brilliant documentation on the forums and wiki. Hope to learn a lot more about linux and Arch and become part of the community. Offline Wow! So many newcomers Welcome to Arch! Have you Syued today? Free music for free people! | Earthlings "Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away." -- A. de Saint-Exupery Offline Hi guys Newbie here, been using Linux for the last two years but never really dare to install Arch until last week Thanks to the excellent wiki, without which I won't be able to install this wonderful distro. At first I thought it will be too complicated, especially since I managed to ruin my own partition (don't ask, my own stupidity ), but on the second try, it all went smoothly. Looking forward to learn & share! Offline Hello everyone, I'm Danilo from Rome Italy I started out using linux (linux mint) one year ago and now coming round to Arch. It's more hard but I hope that I can learn more about Arch so it will became simple. Good Wiki and Forum. Bye Offline I just realised I never posted here! Well, hello, I am Michael, and have been using Linux exclusively for over half a year now. I have a post on my blog detailing my distro hopping and how I got into Linux here Moving on to other things you won't find out about me without really looking; I am arachnophobic, a minimalist, and a masochist*. *When I get everything set up the way I like it I consider it boring and change it all completely to make life difficult and interesting. Hence my installation of PulseAudio (which disappointingly worked perfectly with Flash) and Emacs. Offline
https://bbs.archlinux.org/viewtopic.php?pid=384830
CC-MAIN-2017-30
refinedweb
2,406
70.84
Create a Blog with React and Strapi In this article we will be building a Blog with React.Js , Strapi and Strapi SDK. When building a complete Blog as a Single Page Application, some of the questions that comes to mind are : - How to manage contents at the backend without doing much work as a developer? - How to build and manage API for the Blog? The good news is, there is a headless CMS called Strapi we can use to manage contents and to takes care of the API development Strapi Strapi is the most advanced open-source Content Management Framework to build powerful API with no effort built on Nodejs. It is shipped with an admin interface allows creating of contents. Think of content management in Strapi like a Wordpress backend with an interface where you can create, edit and delete contents. Reactjs React.js is an open-source JavaScript library which is used for building user interfaces specifically for single page applications. We will use it to build the blog interface. Strapi SDK Strapi SDK is integrated into Strapi to replace the use of XHR library(like Axios). So, let get started! Setup Strapi API Setup To setup Strapi, you must have the following installed: - Nodejs (version 9 or higher) - MongoDB, MySQL or PostgreSQL We will be installing Strapi with npm globally on command line: npm i strapi@alpha -g Strapi has been installed globally. We now have access to `strapi` command. If you have permissions error, you can follow the official npm tutorial or run it with root permission that will ask for the root password. See the command below: sudo npm install strapi@alpha -g To check if Strapi installed, copy and paste the command below to your command line: strapi -v This should output something like 3.0.0-alpha.x.x.x. If your output is similar to the one above, you have successfully installed Strapi. Congrats! Create a Strapi Project On your command line, follow the instructions below. strapi new blog-api This will create blog-api folder and bootstrap a new Strapi project inside it. Change directory to the folder created which is blog-api: cd blog-api Then, start the server: strapi start The above command will launch the Strapi project and you can see it by typing on the address bar your browser. If you visit you will be ready to create the first user that will manage Strapi which is the ADMIN. Creating First User Create A Content Type To create blog posts at the backend using Strapi CMS, we need a content type to create the contents for our blog and to generate the APIs. Under Plugins Menu, click on Content Type. Create a Content Type named Blog Post with three fields: - title (type string) - content (type text, tick “Display as a WYSIWYG” in Advanced Setting tab) - author (type relation, many article to one user: “Blog Post has and belongs to one User”) Then, click on Save button. Creating Blog Post We will be inserting contents into the database using the Blog Post content type we created above - Visit Blog Post page (which is at the top left corner of your screen) - Click on “Add new blog post” - Enter values to the Title, Author and Content fields - Click on save Create three more blog posts. Access Control For security reasons, API access is, by default, restricted. To allow access, visit the Role and Permissions section under Plugins. Click on Public. Under Public look for Permissions section. In Permission section, click on Application and select find under the Blog Post — and save. At this point, you should be able to request the list of blog posts. The author API access is also restricted. Authorize anonymous access by selecting the find (in “Users & Permissions” section) action and save the form. If you visit on your browser, you will see the list of blog posts. So we have successfully created our API to read on our blog. Let move on to the frontend part. React Setup We will be using create-react-app to bootstrap our react blog application. Installing Create React App On your command line, type the following: npx create-react-app (npx comes with npm 5.2+ and higher) This will bootstrap react setup into blog folder Change directory to blog directory cd blog Launch the app with: npm start This will launch the react app. If you visit, you will see app running on your browser. Our react setup is done, now we need to install strapi sdk. To do that, run the following command: npm install strapi-sdk-javascript Once the installation is successful, open the project folder in editor of your choice. (I am using Atom). Once you load the project into the IDE, open App.js file, delete all content. Copy and paste the following code to App.js file. import React from ‘react’; import Strapi from ‘strapi-sdk-javascript/build/main’;const strapi = new Strapi(‘');class App extends React.Component { constructor() { super(props); state = { } }async componentDidMount() { try { const posts = await strapi.getEntries(‘blogpost’) this.setState({ posts }); } catch(err) { alert(err); } }render() { return ( <section> {this.state.posts.map(post => { <article> <div>Title: {post.title}</div> <div>Content: {post.content}</div></article> })} </section> ) } }export default App; we import Strapi from ‘strapi-sdk-javascript/main/build’ In line 4, we have an instance of our API and set the variable to strapi You will also noticed in componentDidMount, we added async/await to get the blog entries and set new state. You could see how easy Strapi is easy to setup and use through Strapi SDK. You can read more on Strapi SDK here and here. Conclusion Setting up Strapi with React.js is a lot easier than you think. In the next article, we will be looking at Authentication with React.Js
https://medium.com/@adeyinkakazeemolufemioluoje/create-a-blog-with-react-and-strapi-cc3d8f0f01e1
CC-MAIN-2020-10
refinedweb
977
63.29
A2.1 MATLAB BASICS MATLAB provides several standard functions. In addition, there are several toolboxes or collections of functions and procedures available as part of the MATLAB package. MATLAB offers the option of developing customized toolboxes. Many such tools are available worldwide. MATLAB is case sensitive, so the commands and programming variables must be used very carefully. It means A + B is not the same as a + b. The MATLAB prompt (>>) will be used to indicate where the commands are entered. Anything written after this prompt denotes user input (i.e., a command) followed by a carriage return (i.e., the “enter” key). A2.1.1 Help Command MATLAB provides help on any command or topic by typing the help command ... No credit card required
https://www.oreilly.com/library/view/dynamics-of-structures/9789332579101/xhtml/Appendix2.xhtml
CC-MAIN-2018-51
refinedweb
125
61.33
java.lang.Object com.lowagie.text.pdf.hyphenation.Hyphencom.lowagie.text.pdf.hyphenation.Hyphen public class Hyphen This class represents a hyphen. A 'full' hyphen is made of 3 parts: the pre-break text, post-break text and no-break. If no line-break is generated at this position, the no-break text is used, otherwise, pre-break and post-break are used. Typically, pre-break is equal to the hyphen character and the others are empty. However, this general scheme allows support for cases in some languages where words change spelling if they're split across lines, like german's 'backen' which hyphenates 'bak-ken'. BTW, this comes from TeX. public java.lang.String preBreak public java.lang.String noBreak public java.lang.String postBreak public java.lang.String toString() toStringin class java.lang.Object
http://www.coderanch.com/how-to/javadoc/itext-2.1.7/com/lowagie/text/pdf/hyphenation/Hyphen.html
CC-MAIN-2014-15
refinedweb
136
61.02
Hi, If I wanted to create a schedule function that did not use time as it's decision of when to execute the code, how would I do that? I want the schedule function to execute based on parameters I set previously, not associated with time. My sloppy code looks like this now... having syntax errors, no updated backtest... def initialize(context): context.security = sid(8554) """ The problem is this schedule function situation gets called on hours, minutes, market open, market close etc... but does not execute when the conditions of the trader function are met... it executes when the hour happens, when the minute happens, when market open or market close happens etc... it needs to execute when the event occurs, in this case the crossover, the "x", formed by the mavg_1 and mavg_2 signifying a change in the market going up or down or sideways. """ """Also I want to be able to only execute the trader function when I do not have a position, in other words I do not want to take a position if I already have a position in the underlying security, in this case SPY. The following code is an attempt to describe that situation. """ def position(context,data): # position = context.portfolio.positions # if position > abs(2000000): # return True #do go to the trader function below def trader(context,data): price_hist_2 = data.history(context.security, 'price', 9, '1m') mavg_1 = price_hist_2.mean() price_hist = data.history(context.security, 'price', 18, '1m') mavg_2 = price_hist.mean() """Here I need to calculate the changing slope of mavg_1 and mavg_2. When the slope of mavg_1 begins to become negative after the slope has been positive, a downward moving market should be coming, and the "x". When the slope of mavg_1 becomes positive after being negative, an upward moving market should be coming, and the "x". The shift in slope of the mavg_1 being positive then negative then positive then negative and so on is where you capture your profit, you're making profit in the change in location of the "x". The crossover of the moving averages indicates the long or short market... When the lines intersect, you trade. When the lines don't intersect but are still moving with coresponding slopes indicative of the direction you are positioned for, the code executes on a small percentage of profit, continuously, to capute profit. """ slope_1 = changing slope of mavg_1 slope_2 = changing slope of mavg_2 cost_basis = context.portfolio.positions[context.security].cost_basis current_price = context.portfolio.positions[context.security].last_sale_price account_value = context.portfolio.portfolio_value if mavg_2 < mavg_1 and : order_percent(context.security, .10) log.info("Long") if mavg_2 > mavg_1: order_percent(context.security, -.10) log.info("Short") """Here is me trying to execute the small percentage change of profit by exiting all positions at a .0625 % gain""" elif current_price >= cost_basis * 1.0625 or current_price <= cost_basis * .9375: order_percent(context.security, 0.0) log.info("exiting") If you look at the transaction details in the backtest you will see it's only trading one time a day, 2 minutes after market open, rather than through out the day whenever the crossover of the moving averages occurs. I guess my main question is, how do you program a "Schedule Function" without using time to determine when it executes, instead of using time it would use any other indicator. Best, Lovis
https://www.quantopian.com/posts/schedule-functions-independent-of-time
CC-MAIN-2018-17
refinedweb
552
55.95
Issue I tried using csv files in my Angular projects like this: import * as data1 from "./data.csv"; import * as data2 from "./data2.csv"; They are located in the same folder as the .ts i am trying to use them with. I got following error: Cannot find module ‘data.csv’ What I also tried was moving them to the assets folder: import * as data1 from '/assets/data.csv'; But the error still shows up. What am I doing wrong? Solution Read the csv file content using HttpClient, for example: constructor (private http: HttpClient) {} readCsvData () { this.http.get('path.to.csv') .subscribe( data => console.log(data), err => console.log(err) ); }
https://errorsfixing.com/fixed-import-data-in-angular/
CC-MAIN-2022-27
refinedweb
109
71.21
Figure 1. Sample with specific colors rendered with VML in Internet Explorer. Figure 2. Sample with specific colors rendered with canvas in Firefox. Figure 3. Sample showing collapsed and selected nodes rendered with VML in Internet Explorer. This article presents a JavaScript component which renders a tree on the screen using VML (Vector Markup Language) in Internet Explorer 6+ or the <canvas> element in Firefox 1.5+. There are plenty of JavaScript trees out there, and most of them have a better cross-browser compatibility than this, are faster and better optimized. The goal of this code is to present a client-side implementation of the Walker's layout algorithm (see References), leaving off code optimizations. In short, the component has born after the algorithm, as I think that a living sample would be better than an abstract source-code level implementation. One of the classic treeview JavaScript components I use sometimes is Geir Landr�'s DTree: outstanding and simple. Some time ago, an article appeared here at CodeProject that presents a horizontal JavaScript tree, based upon DTree, which uses HTML tables to render the tree in a horizontal manner. I want to mention those here as they inspired me to publish this article. Moreover, much of the functionalities of this version mimic that on those scripts. I hope this component will fill the gap in projects when a tree layout is needed, but without server-side code. Of course, any comments, corrections, suggestions, etc... are very welcome. The best way to get an idea of what could be accomplished by using this component is to download the sources and play with the sample included. The API reference below could give you a more precise idea of what could be done. But, as a briefing, features include: I would like to say that this is a work in progress. In particular, the code is structured to allow different rendering technologies and I must definitively work harder on this topic. The Walker's algorithm expands on the previous works of Reingold, Tilford, Shannon et al. providing a solution where a tree drawing occupies as little space as possible while satisfying the following aesthetic rules: The Walker's algorithm goal over its predecessors was to provide a solution to fully satisfy the third rule, by means of spacing out evenly smaller subtrees in the interior of adjacent larger subtrees. Figure 4. Samples showing the difference of the apportion routine in Walker's algorithm.. The main concepts of the algorithm are: The algorithm works in two passes. The first pass ( firstWalk) is a postorder traversal. The different subtrees are processed recursively from bottom to top and left to right positioning the rigid units that form each subtree until no one touch each other. As the traversal goes, smaller subtrees are combined forming larger subtrees until we reach the root. During the process, the apportion routine space out evenly the inner smaller subtrees that could float between two adjacent larger subtrees (to satisfy the symmetry of the 3rd rule). The second pass ( secondWalk) is a preorder traversal which calculates the final node position by adding all the ancestors modifiers to the preliminary coordinate of each node. Gao Chaowei (see References) proposed an optimization to the firstWalk routine which consists in an incremental version of the Walker's algorithm. This version avoids to recalculate the node preliminary coordinate and modifier when changes made to the tree structure don't imply modifications to their values. This optimization is not yet implemented in this component. The algorithm also adjust the calculations if the layout is to be made in a different direction (i.e. bottom to top). Different uses may require different views. In occident, traditionally a top disposition means power, like in organizational hierarchies; a bottom layout means evolution or growth, like in biology; whereas left and right layouts could mean time evolution. (But this is a particular consideration). Just a word to mention that, an uniform layout algorithm like this one is adequate for relative small trees. Trees with a large number of nodes may require other layout and visualization techniques, like the ability to zoom, pan and focus, collapse some but not all the children of a node, adding interactive searching. There are a number of other solutions to achieve the same objectives including, but not limited to, hyperbolic trees, treemaps, Degree of interest calculations, ... The curious reader could find a lot of information on the net. Let's build an example, (all samples are included in the download) to understand how to draw a simple tree. After that, with the API reference and looking at the advanced samples code you could fully understand how to use this component. First of all, you must include the component script and link the style-sheet in the <head> section of your HTML page (remember to set the paths upon your installation): <head> <!-- Content goes here... --> <script type="text/javascript" src="ECOTree.js"></script> <link type="text/css" rel="style-sheet" href="ECOTree.css" /> <!-- Content goes here... --> </head> Besides, if you plan to user Internet Explorer you must add the next lines to the <head> section of your HTML page for VML to render correctly: <head> <!-- Content goes here... --> <xml:namespace <style>v\:*{ behavior:url(#default#VML);}</style> <!-- Content goes here... --> </head> In your HTML page you must place a block container for the tree, like a <div> with an ID that you must supply to the tree constructor. Then you must include a <script> block to create the tree itself, add some nodes -probably from a database in real projects- and then draw the tree. Let's look at an example: <div id="myTreeContainer"></div> var myTree = new ECOTree("myTree","myTreeContainer"); myTree.add(0,-1,"Apex Node"); myTree.add(1,0,"Left Child"); myTree.add(2,0,"Right Child"); myTree.UpdateTree(); The result will be: Figure 5. Quick example 1. You must ensure that the script block gets executed once the page is loaded, or at least when the container is loaded. So you could choose to insert the script after the container or to create the tree inside a function that gets called when the OnLoad event occurs for the document or body, as usual. Note that the component has default values for almost everything, causing that those five lines of code could create a tree that you can collapse or expand at will, and you can select/unselect multiple nodes by simply clicking them. Also, every node has a hyperlink Javascript:void(0); by default. Almost every time, you will want to change the look and feel and the behavior of the tree to better fit your needs. This can be done with the config instance member of the tree. Let's modify the previous example by adding some lines: var myTree = new ECOTree("myTree","myTreeContainer"); myTree.config.linkType = 'B'; myTree.config.iRootOrientation = ECOTree.RO_BOTTOM; myTree.config.topYAdjustment = -160; myTree.config.linkColor = "black"; myTree.config.nodeColor = "#FFAAAA"; myTree.config.nodeBorderColor = "black"; myTree.config.useTarget = false; myTree.config.selectMode = ECOTree.SL_SINGLE; myTree.add(0,-1,"Apex Node"); myTree.add(1,0,"Left Child"); myTree.add(2,0,"Right Child"); myTree.UpdateTree(); With these minor changes, the tree now will look like this: Figure 6. Quick example 2. This time, the nodes don't have a hyperlink ( useTarget = false) and you can select only one node at a time ( selectMode = ECOTree.SL_SINGLE). OK, now that the basics had been covered, let's go on to discover all the possibilities. Here are the config parameters with their default values: this.config = { iMaxDepth : 100, iLevelSeparation : 40, iSiblingSeparation : 40, iSubtreeSeparation : 80, iRootOrientation : ECOTree.RO_TOP, iNodeJustification : ECOTree.NJ_TOP, topXAdjustment : 0, topYAdjustment : 0, render : "AUTO", linkType : "M", linkColor : "blue", nodeColor : "#CCCCFF", nodeFill : ECOTree.NF_GRADIENT, nodeBorderColor : "blue", nodeSelColor : "#FFFFCC", levelColors : ["#5555FF","#8888FF","#AAAAFF","#CCCCFF"], levelBorderColors : ["#5555FF","#8888FF","#AAAAFF","#CCCCFF"], colorStyle : ECOTree.CS_NODE, useTarget : true, searchMode : ECOTree.SM_DSC, selectMode : ECOTree.SL_MULTIPLE, defaultNodeWidth : 80, defaultNodeHeight : 40, defaultTarget : 'Javascript:void(0);', expandedImage : './img/less.gif', collapsedImage : './img/plus.gif', transImage : './img/trans.gif' } iMaxDepth: The maximum number of levels allowed for tree. Set it to a value larger than the maximum level expected. iLevelSeparation: The space distance between levels in pixels. Note that a level size will be given by the maximum node size at that level. iSiblingSeparation: The minimum space distance between sibling nodes in pixels. iSubtreeSeparation: The minimum space distance between neighbor nodes (don't have the same parent) in pixels. iRootOrientation: The direction of the layout. Possible values are: ECOTree.RO_TOP: Layout from top to bottom. ECOTree.RO_BOTTOM: Layout from bottom to top. ECOTree.RO_RIGHT: Layout from right to left. ECOTree.RO_LEFT: Layout from left to right. iNodeJustification: The alignment of the nodes that belong to the same level. Possible values are: ECOTree.NJ_TOP: Nodes are top aligned. ECOTree.NJ_CENTER: Nodes are center aligned. ECOTree.NJ_BOTTOM: Nodes are bottom aligned. topXAdjustment: The horizontal offset in pixels that the root node will be given. Use it to center/pan the tree on the screen. topYAdjustment: The vertical offset in pixels that the root node will be given. Use it to center/pan the tree on the screen. render: The render type. Possible values are: "AUTO": Automatic. This is the default value. Code will autodetect if the client is Internet Explorer 6+ or Firefox and the render type will be set to "VML"or "CANVAS"respectively. "VML": Vector Markup Language. For Internet Explorer only. If you use it, remember to add the XML namespaceand the <style>in the headsection as indicated in the article. "CANVAS": Render will be based in the <canvas>HTML element. Only for Firefox 1.5+. (Firefox 2.0 is faster, though). linkType: The style of the node links. Possible values are: "M": Manhattan. Links are crossed straight lines. Classic. "B": B�zier. Links are B�zier curves. More suitable in some cases. linkColor: The color used for the link lines. Any color expressed in HTML is valid. nodeColor: The color used for the nodes. See comments in the article on how to hack the mode how nodes are rendered. Any color expressed in HTML is valid. nodeFill: The fill style of the nodes. Possible values are: ECOTree.NF_GRADIENT: The nodes will be filled with a gradient between the node color and "whitesmoke". ECOTree.NF_FLAT: The nodes will have a solid fill. nodeBorderColor: The color used for the node borders. Any color expressed in HTML is valid. nodeSelColor: The color used for the selected nodes. Any color expressed in HTML is valid. levelColors: A Javascript array with the colors for consecutive levels. Applies when the colorStyleoption is set to use level colors. The nodes at the first level of the tree will have the first color in this array, the second level nodes the second color of the array, and so on. If there are more levels than elements in this array the subsequent levels will repeat the colors anew. Any color expressed in HTML is valid. levelBorderColors: Same as above, but for the border colors. colorStyle: Indicates how the nodes colors are calculated. Possible values are: ECOTree.CS_NODE: Each node will use it's own colors to render. ECOTree.CS_LEVEL: The nodes will use different colors depending on the level of the node in the tree, ignoring it's own colors. useTarget: Whether the nodes will show the hyperlinks or not. Possible values are trueor false searchMode: Express how the searches (see API searchNodes) will be done. Possible values are: ECOTree.SM_DSC: Searches will be done within the node titles. ECOTree.SM_META: Searches will be done within the node metadata. ECOTree.SM_BOTH: Searches will be done within both values. selectMode: Indicates the selection behavior of the tree. Possible values are: ECOTree.SL_MULTIPLE: The user can interactively select and unselect multiple nodes by clicking them. ECOTree.SL_SINGLE: The user can interactively select and unselect a single node by clicking it. A new node selection will unselect the previous selection. ECOTree.SL_NONE: The user can't select nodes by clicking them. Anyway, the API methods that cause node selections will always work, like searches on the tree. defaultNodeWidth: The node width in pixels, if no explicit width is given when adding a node to the tree. defaultNodeHeight: The node height in pixels, if no explicit height is given when adding a node to the tree. defaultTarget: The node hyperlink (when clicked on the title), if no explicit target is given when adding a node to the tree. Usually set when all or most nodes have the same link. expandedImage: The minus icon which allows to collapse a subtree. Change it if you don't like it, or to point to your own images folder. collapsedImage: The plus icon which allows to expand a collapsed subtree. Change it if you don't like it, or to point to your own images folder. transImage: A transparent icon used to separate the collapse/expand icon and the title. Change it if you don't like it, or to point to your own images folder. UpdateTree(): Causes the tree to refresh. add(id, pid, dsc, w, h, c, bc, target, meta): Adds a new node to the tree. The three first parameters are mandatory. Parameters are: id: The node ID. Any number or string will be valid. pid: The parent ID of this node. If this is a root node, the parent ID must be -1. dsc: The node title. This will be the visible description. It will be the link to the node target as well. w: (Optional) The node width in pixels. c: (Optional) The node color. bc: (Optional) The node border color. h: (Optional) The node height in pixels. target: (Optional) The node hyperlink target. If you don't supply this value, the node will have the dafault value. But, if you supply an empty string as target, you will end with a node without target. meta: (Optional) The node's metadata. The metadata will not be visible. You can search nodes based on its contents, or you can use it simply as a container for your own node data. If you use a Javascript object as metadata, provide a toString()method in that object's prototype to get the searches working properly. After the node has been added to the tree, you can use other API's to modify them, for example, to mark it as selected or collapsed if it has children, before the first call to UpdateTree(). It's not mandatory to add the nodes in any particular order. searchNodes(str): Searches the tree for nodes containing the strstring. The found nodes will be selected and, if it's the case, their ancestors expanded to get the found node into view. The searches could be done in the node's title, metadata or both. The search is case insensitive. If the selectModeis SL_MULTIPLEor SL_NONEall the found nodes will be selected. If the selectModeis SL_SINGLEonly the first node (in database order) will be selected, but subsequent searches will start from the next node in order, so you can call this API to simulate the search next functionality. After all the nodes will be visited, searches will restart from the beginning. UpdateTree()is called internally, so you don't need to refresh the tree. selectAll(): Causes all the nodes in the tree to appear as selected. If the selectModeis set to SL_NONEthis API will return without selections. UpdateTree()is called internally, so you don't need to refresh the tree. unselectAll(): Clears all the selections. Could be used no matter the selectModewas. Should be used to clear selections between searches. UpdateTree()is called internally, so you don't need to refresh the tree. collapseAll(): Causes all the parent nodes to become collapsed. UpdateTree()is called internally, so you don't need to refresh the tree. expandAll(): Causes all the parent nodes to become expanded. UpdateTree()is called internally, so you don't need to refresh the tree. collapseNode(nodeid, upd): Collapses the node with ID = nodeid. UpdateTree()is called internally only if you supply the second parameter as true. So if you plan to collapse several nodes, you should refresh only once after all the work will be done. selectNode(nodeid, upd): Marks as selected the node with ID = nodeid. UpdateTree()is called internally only if you supply the second parameter as true. setNodeTitle(nodeid, title, upd): Sets the title titleof the node with ID = nodeid. UpdateTree()is called internally only if you supply the third parameter as true. setNodeMetadata(nodeid, meta, upd): Sets the metadata metaof the node with ID = nodeid. UpdateTree()is called internally only if you supply the third parameter as true. setNodeTarget(nodeid, target, upd): Sets the hyperlink targetof the node with ID = nodeid. UpdateTree()is called internally only if you supply the third parameter as true. setNodeColors(nodeid, color, border, upd): Sets the background colorand bordercolor of the node with ID = nodeid. UpdateTree()is called internally only if you supply the fourth parameter as true. getSelectedNodes(): Returns a JavaScript Array of objects, each having the instance members "id", "dsc", "meta"with the values of node ID, title and metadata of each of the selected nodes respectively. See the samples to get an example on how to use it. It could be useful if you're doing some editing with the tree client-side and you use the XMLHttpobject to send the results of the user selections or searches to the server. ( XMLHttpand AJAX are not in the scope of this article, but good to hear that IE7 finally implements XMLHttpas a native intrinsic object...). In the download you can find several simple examples you can play with. All the images in this article are made with the code on the examples. There is an advanced example which will let you play with almost all the options in the component. The data in the samples has been obtained in the Wikipedia. <canvas>element Resources "AUTO", the component will auto-detect the browser and will choose a render type accordingly. I strongly recommend to use Firefox 2.0 to get a much faster <canvas>experience, but Firefox 1.5 will work as well. General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/scripting/graphic_javascript_tree.aspx
crawl-002
refinedweb
3,031
59.19
The Honeycomb-lx2k is a nice board with lots of potential, beside the boot/reboot quirk I mentioned in the previous post. I do wonder if what I got is defective, hopefully I'll get some reply from the manufacturer later this week. Yesterday I installed on it Gentoo and it built everything as should so it seems working well at least as development board. $ qlop clang 2020-06-01T20:31:43 >>> sys-devel/clang: 48′54″ 2020-06-02T10:28:35 >>> sys-devel/clang: 34′11″ The first one when build clang while building gcc in parallel, the second one building clang alone. Building a new kernel I want to use on this machine few software that requires some kernel features: - portage: It uses namespaces to sandbox the build process - lxd: It uses cgroups, a number of networking features (veth, macvlan), namespaces and few netfilter modules get handy. - docker: It uses more or less the same kernel features. - wireguard: It needs few networking options to be really useful. None of that is available and most of it cannot be built as module. According to what I could see from the image builder the kernel sources in use aren't mainline. $ git clone $ git checkout -b LSDK-20.04-V5.4 refs/tags/LSDK-20.04-V5.4 Its default config is assembled by merging few defaults: ./scripts/kconfig/merge_config.sh arch/arm64/configs/defconfig arch/arm64/configs/lsdk.config $ROOTDIR/configs/linux/lx2k_additions.config After this, I just issued the usual $ make menuconfig $ make all -j 20 $ make modules_install $ make install And then I updated extlinux/extlinux.conf accordingly. I did not change the device tree file so no strange dances with u-boot-tools were needed. Coming next I'll have to complete some more configuration but it is fairly standard and not so interesting. Soon I'll run some benchmarks to see how rav1e is behaving on a many-cores Aarch64 since Vibhoothi is merging in some interesting asm optimizations from dav1d and they will appear on the release 0.4.0. Posted on by: Luca Barbato I do multimedia opensource stuff, lately in rust Discussion
https://dev.to/luzero/honeycomb-lx2k-second-day-4db9
CC-MAIN-2020-40
refinedweb
359
53.1
Responses of 1st , 2nd, and soon 3rd order Drosophila olfactory neurons Project description Installation pip install drosolf If you need elevated permissions to install (if the pip install line fails with some sort of permissions error), you can try: sudo -H pip install drosolf Examples To get Hallem and Carlson ORN responses, with the baseline added back in. Returned as a pandas DataFrame with columns of receptor and row indices of odor. The transpose (i.e. orn_responses.T) will have odors as the columns. from drosolf import orns orn_responses = orns.orns() To get simulated projection neuron responses, using the Olsen input gain control model and the ORN responses. from drosolf import pns pn_responses = pns.pns() Get correlation matrices at the ORN and (simulated) PN levels for a list of odors, named as the columns of the previous DataFrames. from drosolf import corrs orn_correlations, pn_correlations = corrs.get_corrs(list_of_odors) Generate plots of the same ORN and PN correlation matrices (uses seaborn). import matplotlib.pyplot as plt from drosolf import corrs corrs.plot_corrs(list_of_odors) plt.show() Todo - DoOR integration - KC model(s) - sympy description of transformations applied to ORN data 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/drosolf/
CC-MAIN-2019-51
refinedweb
214
55.74
Defining Functional Data Structures Defining Functional Data Structures by Paul Chiusano and Rúnar Bjarnason, authors of Functional Programming in Scala Functional programs do not update variables or modify data structures. This raises pressing questions—what sort of data structures we use in functional programming, how do we define them can in Scala, and how do we operate over these data structures? This article, based on chapter 3 of Functional Programming in Scala, explains the concept of a functional data structure and how to define and work with such structures. A functional data structure is (not surprisingly!) operated on using only pure functions. A pure function may only accept some values as input and yield a value as output. It may not change data in place or perform other side effects. Therefore, functional data structures are immutable. For example, the empty list, (denoted List() or Nil in Scala) is as eternal and immutable as the integer values 3 or 4. And just as evaluating 3 + 4 results in a new number 7 without modifying either 3 or 4, concatenating two lists together (the syntax for this is a + b for two lists a and b) yields a new list and leaves the two inputs unmodified. Doesn't this mean we end up doing a lot of extra copying of the data? Somewhat surprisingly, the answer is no. We will return to this issue after examining the definition of what is perhaps the most ubiquitous of functional data structures, the singly-linked list. The definition here is identical in spirit to (though simpler than) the data type defined in Scala's standard List library. This code listing makes use of a lot of new syntax and concepts, so don't worry if not everything makes sense at first—we will talk through it in detail. [1] Listing 1 Singly-linked lists package fpinscala.datastructures sealed trait List[+A] case object Nil extends List[Nothing] case class Cons[+A](head: A, tail: List[A]) extends List[A] object List {) } def apply[A](as: A*): List[A] = if (as.isEmpty) Nil else Cons(as.head, apply(as.tail: _*)) val example = Cons(1, Cons(2, Cons(3, Nil))) val example2 = List(1,2,3) val total = sum(example) } Let's look first at the definition of the data type, which begins with the keywords sealed trait. In general, we introduce a data type with the trait keyword. A trait is an abstract interface that may optionally contain implementations of some methods. Here we are declaring a trait, called List, with no methods on it. Adding sealed in front means that all implementations of our trait must be declared in this file. [2] There are two such implementations or data constructors of List (each introduced with the keyword case) declared next, to represent each of the two possible forms a List can take—it can be empty, denoted by the data constructor Nil, or it can be nonempty (the data constructor Cons, traditionally short for construct), in which case it consists of an initial element, head, followed by a List (possibly empty) of remaining elements (the tail). Listing 2 The data constructors of List case object Nil extends List[Nothing] case class Cons[+A](head: A, tail: List[A]) extends List[A] Just as functions can be polymorphic, data types can be as well, and by adding the type parameter [+A] after sealed trait List and then using that A parameter inside of the Cons data constructor, we have declared the List data type to be polymorphic in the type of elements it contains, which means we can use this same definition for a list of Int elements (denoted List[Int]), Double elements (denoted List[Double]), String elements (List[String]), and so on (the + indicates that the type parameter, A is covariant—see sidebar "More about variance" for more info). A data constructor declaration gives us a function to construct that form of the data type (the case object Nil lets us write Nil to construct an empty List, and the case class Cons lets us write Cons(1, Nil), Cons(1, Cons(2, Nil)), and so on for nonempty lists), but also introduces a pattern that can be used for pattern matching, as in the functions sum and product. More about variance In the declaration, the in trait List[+A], the + in front of the type parameter A is a variance annotation that signals A is a covariant or positive parameter of List. This means that, for instance, List[Dog] is considered a subtype of List[Animal], assuming Dog is a subtype of Animal. (More generally, for all types X and Y, if X is a subtype of Y, then List[X] is a subtype of List[Y]). We could leave out the + in front of the A, which would make List invariant in that type parameter. But notice now that Nil extends List[Nothing]. Nothing is a subtype of all types, which means that, in conjunction with the variance annotation, Nil can be considered a List[Int], a List[Double], and so on, exactly as we want. These concerns about variance are not very important for the present discussion and are more of an artifact of how Scala encodes data constructors via subtyping. [3] Pattern matching Let's look in detail at the functions sum and product, which we place in the object List, sometimes called the companion object to List (see the sidebar). Both of these definitions make use of pattern matching.) } As you might expect, the sum function states that the sum of an empty list is 0, and the sum of a nonempty list is the first element, x, plus the sum of the remaining elements, xs. [4] Likewise, the product definition states that the product of an empty list is 1.0, the product of any list starting with 0.0 is 0.0, and the product of any other nonempty list is the first element multiplied by the product of the remaining elements. Notice these are recursive definitions, which are quite common when writing functions that operate over recursive data types like List (which refers to itself recursively in its Cons data constructor). This isn't the most robust test—pattern matching on 0.0 will match only the exact value 0.0, not 1e-102 or any other value very close to 0. Pattern matching works a bit like a fancy switch statement that may descend into the structure of the expression it examines and extract subexpressions of that structure (we'll explain this shortly). It is introduced with an expression (the target or scrutinee), like ds followed by the keyword match, and a {}-wrapped sequence of cases. Each case in the match consists of a pattern (like Cons(x,xs)) to the left of the => and a result (like x * product(xs)) to the right of the =>. If the target matches the pattern in a case (see below), the result of that case becomes the result of the entire match expression. If multiple patterns match the target, Scala chooses the first matching case. Companion objects in Scala We will often declare a companion object in addition to our data type and its data constructors. This is just an object with the same name as the data type (in this case List) where we put various convenience functions for creating or working with values of the data type. If, for instance, we wanted a function def fill[A](n: Int, a: A): List[A], that created a List with n copies of the element a, the List companion object would be a good place for it. Companion objects are more of a convention in Scala. [5] We could have called this module Foo if we wanted, but calling it List makes it clear that the module contains functions relevant to working with lists, and also gives us the nice List(1,2,3) syntax when we define a variadic apply function (see sidebar "Variadic functions in Scala"). Let's look at a few more examples of pattern matching: - List(1,2,3) match { case _ => 42 } results in 42. Here we are using a variable pattern, _, which matches any expression. We could say x or foo instead of _ but we usually use _ to indicate a variable whose value we ignore in the result of the case. [6] - List(1,2,3) match { case Cons(h,t) => h } results in 1. Here we are using a data constructor pattern in conjunction with variables to capture or bind a subexpression of the target. - List(1,2,3) match { case Cons(_,t) => t } results in List(2,3). - List(1,2,3) match { case Nil => 42 } results in a MatchError at runtime. A MatchError indicates that none of the cases in a match expression matched the target. What determines if a pattern matches an expression? A pattern may contain literals, like 0.0 or "hi", variables like x and xs which match anything, indicated by an identifier starting with a lowercase letter or underscore, and data constructors like Cons(x,xs) or Nil, which match only values of the corresponding form (Nil as a pattern matches only the value Nil, and Cons(h,t) or Cons(x,xs) as a pattern only match Cons values). These components of a pattern may be nested arbitrarily—Cons(x1, Cons(x2, Nil)) and Cons(y1, Cons(y2, Cons(y3, _))) are valid patterns. A pattern matches the target if there exists an assignment of variables in the pattern to subexpressions of the target that make it structurally equivalent to the target. The result expression for a matching case will then have access to these variable assignments in its local scope. EXERCISE 1: What will the result of the following match expression be? val x = List(1,2,3,4,5) match { case Cons(x, Cons(2, Cons(4, _))) => x case Nil => 42 case Cons(x, Cons(y, Cons(3, Cons(4, _)))) => x + y case Cons(h, t) => h + sum(t) case _ => 101 } You are strongly encouraged to try experimenting with pattern matching in the REPL to get a sense for how it behaves. Variadic functions in Scala The function List.apply in the listing above is a variadic function, meaning it accepts zero or more arguments of type A. For data types, it is a common idiom to have a variadic apply method in the companion object to conveniently construct instances of the data type. By calling this function apply and placing it in the companion object, we can invoke it with syntax like List(1,2,3,4) or List("hi","bye"), with as many values as we want separated by commas (we sometimes call this the list literal or just literal syntax).):_*). Summary In this article, we covered a number of important functional programming concepts related to Scala. We introduced algebraic data types and pattern matching. 1. Note—the implementations of sum and product here are not tail recursive. ↩ 2. We could also say abstract class here instead of trait. Technically, an abstract class can contain constructors, in the OO sense, which is what separates it from a trait, which cannot contain constructors. This distinction is not really relevant for our purposes right now. ↩ 3. It is certainly possible to write code without using variance annotations at all, and function signatures are sometimes simpler (while type inference often gets worse). ↩ 4. We could call x and xs anything there, but it is a common convention to use xs, ys , as, bs as variable names for a sequence of some sort, and x , y , z , a, or b as the name for a single element of a sequence. Another common naming convention is h for the first element of a list (the "head" of the list), t for the remaining elements (the "tail"), and l for an entire list. ↩ 5. There is some special support for them in the language that isn't really relevant for our purposes. ↩ 6. The _ variable pattern is treated somewhat specially in that it may be mentioned multiple times in the pattern to ignore multiple parts of the target.↩ Here are some other Manning titles you might be interested in: - Login or register to post comments - Printer-friendly version - manning_pubs's blog - 6806 reads
https://weblogs.java.net/node/892488/atom/feed
CC-MAIN-2014-15
refinedweb
2,066
57.1
I am building a custom Splunk application. The app leverages custom python scripts to query an external API and present data in a dashboard directly in the Splunk UI. Using the setup.xml, I am able to successfully store the external API credentials in a passwords.conf file. When I invoke the scripts and API calls with the admin user, everything works perfectly without any issues. However, when I try to do the same with a non-admin user, I get the following error: Error: [HTTP 403] Client is not authorized to perform requested action; How can I successfully pull out the credentials from passwords.conf with a user that isn't an admin? My getCredentials() method is as follows: def getCredentials(sessionKey, targetUsername, logger): try: # list all credentials entities = entity.getEntities(['admin', 'passwords'], namespace=myapp, owner='nobody', sessionKey=sessionKey) except Exception, e: logger.error("Could not get %s credentials from splunk. Error: %s" % (myapp, str(e))) raise Exception("Could not get %s credentials from splunk. Error: %s" % (myapp, str(e))) credentials = [] # return credentials for i, c in entities.items(): if c['username'] == targetUsername: credentials.append((c['username'], c['clear_password'])) return credentials logger.error("No credentials have been found") raise Exception("No credentials have been found") My password.conf file looks like this (encrypted password string obfuscated): [credential::api_user:] password = $1234abcd= Anyone you needs to hit the endpoint for stored creds needs to have the role capability 'liststoragepasswords' in v6.5+. Prior to 6.5 it has to be 'adminallobjects'. Interesting, however would not liststoragepasswords allow the REST API to be used to obtain the clear text password if the user had the knowledge and the ability (restpropertiesget) to use the REST API? Wouldn't this then potentially allow the user to see the real password (assuming they had access to port 8089, had the required authorize.conf setting and found the passwords endpoint)... Gareth, how do you reverse engineer the password from the crypt. Do you not also need the splunk.secret ? (and that means splunk host access) ? Try in a browser, as per Storing Encrypted Credentials or Splunk Alert Scripts Where using a default app such as search you may see the passwords from every other application, if you have many you may need to append ?count=-1 to the URL.
https://community.splunk.com/t5/Developing-for-Splunk-Enterprise/I-ve-created-a-custom-Splunk-App-that-has-passwords-conf-file/td-p/305078
CC-MAIN-2020-34
refinedweb
383
57.77
#include <hallo.h> Phil Blundell wrote on Mon Feb 25, 2002 um 04:47:21PM: > > disks, but it is nothing but ugly, and still was not sucessfull. So is > > anyone really interessted in keeping 1200kB version alive? If yes, come > > and help, otherwise we shold drop this subflavor. > > We talked about this before and there was strong feeling (from Adam I > think) that dropping 1.2M disks was not acceptable. Okay, we may keep them. Now I am uploading my CVS build (bf2.4), CVS diff and new files to. Remaining problems: - modconf call must get a proper locale, like de_DE.UTF-8. Phil, could you have a look? - check rule must be adapted for the new libs - Makefile should be rewritten a bit. Currently, it does create a root.bin with few locales, makes 1.2meg images, removes root.bin and continues as usuall. Gruss/Regards, Eduard. -- X ist ein genialer terminal multiplexer -- oxygene in #debian.de
https://lists.debian.org/debian-boot/2002/02/msg00862.html
CC-MAIN-2015-32
refinedweb
158
79.16
Introduction This is part three in adventures with statsmodels.stats, after power and multicomparison.. For more background see this Wikipedia page which was the starting point for my code.. Cohen's Kappa The relevant information about the data can be summarized by a square contingency table, where the entries are the counts of observations for pairs of category assignments. For example, a are the number of observations where both raters assigned category one, e is the number of observations where rater 1 assigned category two and rater 2 assigned category one. To have an illustrative example and code to work with, I import the relevant function and define a table as a numpy array. import numpy as np from statsmodels.stats.inter_rater import cohens_kappa, to_table table = np.array([[ 2., 6., 3., 0.], [ 5., 4., 2., 2.], [ 5., 2., 6., 0.], [ 2., 2., 3., 7.]]) Calling the function from statsmodels and printing the results, we see that kappa for this table is 0.1661, and that we cannot reject at the 5% level the Null Hypothesis that kappa is zero. >>> print cohens_kappa(table) Simple Kappa Coefficient -------------------------------- Kappa 0.1661 ASE 0.0901 95% Lower Conf Limit -0.0105 95% Upper Conf Limit 0.3426 Test of H0: Simple Kappa = 0 ASE under H0 0.0798 Z 2.0806 One-sided Pr > Z 0.0187 Two-sided Pr > |Z| 0.0375 cohens_kappa returns a results instance that provides additional information. >>> res = cohens_kappa(table) >>> type(res) <class 'statsmodels.stats.inter_rater.KappaResults'> >>> res.keys() ['distribution_kappa', 'pvalue_one_sided', 'kappa_low', 'kappa_max', 'std_kappa', 'z_value', 'alpha', 'pvalue_two_sided', 'var_kappa', 'kappa_upp', 'kind', 'kappa', 'std_kappa0', 'alpha_ci', 'weights', 'distribution_zero_null', 'var_kappa0'] Cohen's kappa takes the column and row total counts as given when the "pure chance" agreement is calculated. This has two consequences: While kappa is always smaller than or equal to one (as is the correlation coefficient), the largest kappa that can be achieved for given marginal counts, can be strictly smaller than one. cohens_kappa calculates the largest simple Kappa that can be obtained for the given margin totals, available as kappa_max >>> res.kappa_max 0.86969851814001009 The second consequence is that kappa values in unequally distributed tables might be surprising >>> t3 = np.array([[98, 2], [2,0]]) >>> t3 array([[98, 2], [ 2, 0]]) >>> res3 = cohens_kappa(t3) >>> res3.kappa -0.019999999999998037 Kappa is negative, raters agree in 98 out of 100 cases, but disagree on the other two. Conditioning on the margin totals to define chance agreement, works as if raters have been told that there are 98 cases of category one and 2 cases of category two. Raters in this example disagree which are the two cases in category two. An extension of the simple kappa allows for different weights when aggregating the agreement counts from the contingency table. Which weights are appropriate for a given dataset depends on the interpretation of the categories. Kappa is a measure of association between two random variables (the two ratings). If the categories were numeric, then we could also use the correlation coefficient. Weighted kappa allows us to measure agreement for different types of data, such as categorical or ordered categories. I am going through some examples for different interpretations of the categories, and show how the corresponding weights can be defined for cohens_kappa. Case 1: Categorical Data Suppose our categories are "clothing", "housing", "food" and "transportation", and raters have to assign each unit to one of the categories. In this case, the categories are purely categorical, there is no difference in closeness between any pairs. Agreement means that both raters assign the same category, if one rater assigns, for example, "housing" and the other rater assigns "food", then they don't "almost" agree, they just disagree. The count of agreement cases only counts those on the main diagonal, a+f+k+p, off-diagonal counts are ignored. The corresponding Cohen's kappa is then called simple or unweighted. Case 2: Equally Spaced Ordered Categories Examples for this case are simple grading scales, such as 0 to 4 stars, or letter grades A, B, C, D. The assumption is that weighting for the agreement of points only depends on the distance. One star difference is the same whether it is zero stars versus one star, or 2 stars versus 3 stars. The weight or distance only depends on how far away the point is from the main diagonal, b, g, l and e, j, o all represent one level disagreement. The distance table in this case is >>> d array([[ 0., 1., 2., 3.], [ 1., 0., 1., 2.], [ 2., 1., 0., 1.], [ 3., 2., 1., 0.]]) The actual weighting could be linear, quadratic or some arbitrary monotonic function of the distance. The corresponding options as described in the docstring are wt : None or string <...> wt in ['linear', 'ca' or None] : use linear weights, Cicchetti-Allison actual weights are linear in the score "weights" difference wt in ['quadratic', 'fc'] : use quadratic weights, Fleiss-Cohen actual weights are squared in the score "weights" difference The kappa for these two weights are >>> cohens_kappa(table, wt='linear').kappa 0.23404255319148948 >>> cohens_kappa(table, wt='quadratic').kappa 0.31609195402298862 We get the same result if we use the above distance matrix directly >>> cohens_kappa(table, weights=d).kappa 0.23404255319148937 >>> cohens_kappa(table, weights=d**2).kappa 0.31609195402298873 This distance based weighting scheme implies that the weight matrix has a Toeplitz structure, the value of an entry only depends on the distance to the main diagonal. To allow more flexibility in the definition of weights, I added the toeplitz option wt : None or string <...> wt = 'toeplitz' : weight matrix is constructed as a toeplitz matrix from the one dimensional weights. Consider the following examples, the categories are "solid blue", "leaning blue", "leaning red" and "solid red". We would like to include a half point weight for assignments where the raters chose neighboring categories, and not include pairs of category assignments that are more than one level apart. weights = [0, 0.5, 1, 1] This is again defined in terms of distance. We can also get the actual weights (which are 1 - the distance matrix) >>> res = cohens_kappa(table, weights=np.array([0, 0.5, 1, 1]), wt='toeplitz') >>> 1 - res.weights array([[ 1. , 0.5, 0. , 0. ], [ 0.5, 1. , 0.5, 0. ], [ 0. , 0.5, 1. , 0.5], [ 0. , 0. , 0.5, 1. ]]) The kappa given these weights is larger than the simple kappa: >>> res.kappa 0.19131334022750779 As a check, we can also calculate the simple kappa as a special case of toeplitz >>> cohens_kappa(table, weights=np.array([0, 1, 1, 1]), wt='toeplitz').kappa 0.16607051609606549 >>> _ - cohens_kappa(table).kappa 1.1102230246251565e-16 Aside: Since R's irr package does not offer any option that corresponds to toeplitz, the unit test only look at cases where toeplitz has an equivalent representation in on of the other options. Case 3: Unequally Spaced Ordered Categories We can also look at cases where categories are ordered but the distance between categories is not equal. Take as example a list of categories "apples", "oranges", "cars", "minivans", "trucks". We could assign a distance scale that reflects closeness across categories, for example (1, 2, 7, 8, 10). The distance between apples and oranges is 1, the distance between oranges and cars is 5. The scale will be rescaled for the weights, so only relative distances matter( in the linear reweighting case). We have only 4 categories in our example table, so let's assume our categories are "excellent", "very good", "very bad" and "awful", and we assign distance scores (0, 1, 9, 10). wt='linear' uses the linear Cicchetti-Allison transformation to rescale the scores. Weighted kappa and weights (rescaled distances) are >>> res = cohens_kappa(table, weights=np.array([0, 1, 9, 10]), wt='linear') >>> res.kappa 0.28157383419689141 >>> res.weights array([[ 0. , 0.1, 0.9, 1. ], [ 0.1, 0. , 0.8, 0.9], [ 0.9, 0.8, 0. , 0.1], [ 1. , 0.9, 0.1, 0. ]]) The actual weights are >>> 1 - res.weights array([[ 1. , 0.9, 0.1, 0. ], [ 0.9, 1. , 0.2, 0.1], [ 0.1, 0.2, 1. , 0.9], [ 0. , 0.1, 0.9, 1. ]]) Identical category assignments have weight 1, ("excellent", "very good") and ("very bad" and "awful") pairs have weight 0.9 close to full agreement, ("very good" and "very bad") pairs have weight 0.2 (normalized distance is 0.8), and so on. Another usage for this is to calculate kappa for merged tables. We can define a scale that has a distance of zero between the two categories at the extremes. >>> res = cohens_kappa(table, weights=np.array([1, 1, 2, 2]), wt='linear') >>> res.kappa 0.298165137614679 >>> res.weights array([[ 0., 0., 1., 1.], [ 0., 0., 1., 1.], [ 1., 1., 0., 0.], [ 1., 1., 0., 0.]]) >>> 1 - res.weights array([[ 1., 1., 0., 0.], [ 1., 1., 0., 0.], [ 0., 0., 1., 1.], [ 0., 0., 1., 1.]]) Which gives us the same kappa as the one from the merged table where we combine the two "good" and the two "bad" categories into one level each >>> table_merged = np.array([[table[:2, :2].sum(), table[:2, 2:].sum()], [table[2:, :2].sum(), table[2:, 2:].sum()]]) >>> table_merged array([[ 17., 7.], [ 11., 16.]]) >>> cohens_kappa(table_merged).kappa 0.29816513761467894 Besides weighted kappa, cohens_kappa also calculates the standard deviations and hypothesis test for it. I also implemented Fleiss' kappa, which considers the case when there are many raters, but I only have kappa itself, no standard deviation or tests yet (mainly because the SAS manual did not have the equations for it). An additional helper function to_table can convert the original observations given by the ratings for all individuals to the contingency table as required by cohen's kappa. I had also added more functions for inter-rater agreement or reliability to my wish list, but I am not planning to work on it anytime soon (except maybe ICC Intraclass correlation . Note: While writing this, after not having looked at cohens_kappa for some time, I discovered that the function does not check whether the user specified weights in the toeplitz case make sense. When the full weight matrix is given, the function also just uses whatever the user defined. I think, raising ValueErrors or automatic transformations to valid weight or distance matrices in the flexible cases will be necessary. Also, I think the docstring is not clear in what is a weight matrix (with 1 on the main diagonal) and what is a distance matrix (with 0 on the main diagonal) Development Notes and Surprises with R I had a quiet evening, was to tired or too lazy to do any serious work, and picked something from my wishlist that looked easy to implement as a late evening activity. I started with the Wikipedia article on Cohen's kappa and implemented it very fast. Then, I went to the SAS manual to get more background, and to see what other statistical packages provide. Since SAS has a lot more than what's described on Wikipedia and it has the formulas in the documentation, it started to get serious. Understanding and working through the weighting schemes started to be a fun challenge. A few days later, I was ready to look at R, to write more unit tests than the ones based on the printouts that I found for the SAS examples. I found the package irr in R, that has Cohens' kappa. So, I started to write my tests cases verifying against it. I have been using R for several years to write unit tests for scipy.stats and statsmodels, but never tried to learn it systematically. My knowledge of R is very eclectic. Stackoverflow is often a good source to get around some of the trickier parts, once I know what to look out for. R factors are one dimensional, I guess I started to look at one of the datasets that come with the irr package. I converted the dataframe with factors to numeric values, and started to compare the results with my implementation. My numbers didn't match and I spent some time looking for a bug. Finally, I realized that R converts each factor separately to numeric. The last rater in the following example does not use one of the categories, so the mapping between string and numeric levels is not the same across raters. Individuals (rows) 1 and 4 have the same diagnosis by all raters, but the numeric value of the last rater (column) is different. > sapply(diagnoses, class) rater1 rater2 rater3 rater4 rater5 rater6 "factor" "factor" "factor" "factor" "factor" "factor" > sapply(diagnoses, mode) rater1 rater2 rater3 rater4 rater5 rater6 "numeric" "numeric" "numeric" "numeric" "numeric" "numeric" > diagnoses[1:5, ] rater1 rater2 rater3 rater4 1 4. Neurosis 4. Neurosis 4. Neurosis 4. Neurosis 2 2. Personality Disorder 2. Personality Disorder 2. Personality Disorder 5. Other 3 2. Personality Disorder 3. Schizophrenia 3. Schizophrenia 3. Schizophrenia 4 5. Other 5. Other 5. Other 5. Other 5 2. Personality Disorder 2. Personality Disorder 2. Personality Disorder 4. Neurosis rater5 rater6 1 4. Neurosis 4. Neurosis 2 5. Other 5. Other 3 3. Schizophrenia 5. Other 4 5. Other 5. Other 5 4. Neurosis 4. Neurosis > data.matrix(diagnoses)[1:5,] rater1 rater2 rater3 rater4 rater5 rater6 1 4 4 4 4 4 3 2 2 2 2 5 5 4 3 2 3 3 3 3 4 4 5 5 5 5 5 4 5 2 2 2 4 4 3 I had expected that a matrix is a matrix and not a collection of columns. Columns with no observations Since the last rater does not use one of the levels, the contingency table has a zero row or column when the last rater is compared to any of the other raters. Either kappa2 (or the factor handling in R) drops the column with zeros, which changes the value of Cohen's kappa. SAS had a similar problem in the past with several work-arounds published by users on the internet, but according to the latest documentation, SAS has an explicit option not to drop rows or columns with all zeros. However, since I was already alerted to the problem from the SAS stories, debugging time wasn't very long for this. Hi Josef, Thanks for this post, this is a great function. I had a comment/question. Because cohens_kappa always requires 'square' input, I've run into difficulty using it regularly with pandas.crosstab which I was using to convert an n(subjects) x m(raters) data frame into pairwise frequency tables. The issue has been if some factors/levels have no members, the output of crosstab is not square. This is expected behaviour I'm sure, but does mean further fiddling is required to "re-square" to frequency table. This a big behavioural difference with the R version of kappa2(which accepts the original nxm matrix rather than a freq table) and likely part of the reason for your last few points in the article - it's their hack to cope with factors without members. My "hack" for the python version was to write a function that will accept an array that lists all possible factor levels (eg [0,1,2,4,9]) and produces a zero'd square dataframe that size. I then perform the crosstab and add the two. This preserves the squareness and keeps the zeros which I think statistically is the correct thing to do! I'm just wondering that considering the likely use cases of cohens_kappa, is there a better way of making it "factor/level" aware? Realistically, for anything other than 2 levels you won't want to be entering tables by hand as you have done in your examples. Making it play nice with crosstab output would make for nice pandas integraton! Thanks again, David. Hi David, The import at the top also shows a helper function "to_table" which can be used to create the table from the data. However, I have not tried it out with a pandas dataframe. I would like to keep the functions separate, but there might be ways to integrate them better. Please, open an issue for statsmodels on github, if there are problems with "to_table" or you have suggestions to make it more user friendly. For example, I don't think I keep track of label names. Hi, It's long after the fact, so you have probably discovered this by now. The problem you experienced with factors in R is one that can be easily addressed. One only has to explicitly list the expected factor levels when creating the factors. Say the variable 'color' represents the color of a series of objects which may be either red, blue, or green. But the rater has seen a sequence of objects that contains no blue ones. The default operation of the factor() function is to use only the levels that are found in the object being factored. That is illustrated with the code fragment here. > color = c("red","green","green","red") > fcolor = factor( color) > table( fcolor ) fcolor green red 2 2 But if the expected levels are supplied in the call to factor as shown here, the desired and correct behavior results. > fcolor = factor( color, levels=c("blue","green","red")) > table(fcolor) fcolor blue green red 0 2 2
http://jpktd.blogspot.com/2013/03/inter-rater-reliability-cohen-kappa-and_268.html
CC-MAIN-2017-22
refinedweb
2,882
63.59
In-Depth Use Backbone & Backgrid to rejuvenate (or rescue) a data grid that's been pushed well beyond its original design. The two potential problems we're going to set out to solve with Backbone today are pretty common ones – either getting an older grid view to start performing better, or bringing something new to your client's newfound Web 2.0 expectations. Let's say there's a client you've been working with for years that originally had some of their data set up in a grid view. This is a common pattern for many organizations that need their application to present a collection of data in a readable table-like view. Over time, the business requirements either change or expand, which requires expansions of this grid view. As data from different sources are stitched together, the cost of fetching a single item grows and grows. It's definitely not unheard of for these once slick and fast grid views to become a sore thumb for the entire application, with horrifyingly long load times and borderline unusable behavior. Often, there's just too much data coming down and further query optimization will not yield the results your client is looking for. Luckily, client-side frameworks such as Backgrid (which depends on Backbone) can solve this problem. When you're working on the client, you have the freedom to request data either piece-wise or on-demand, which gives you much more flexibility in how you can manage the data requests necessary to render out the grid view. With server-side-only technologies, you're forced to send down everything the user will need until they change the page, which eventually piles up and creates the non-responsive experience we'll be solving. In order to get to this place, we'll be demonstrating a few of the powerhouses today in client-side, enterprise-level Web development, including the Backgrid grid view library and the Backbone MVC Framework on which it relies. Let's say you have a list of customer orders that looks something like this (in JSON, of course): { "Phone": "030-0074321", "ContactName": "Maria Anders", "Address": "Obere Str. 57", "CustomerID": "ALFKI", "CompanyName": "Alfreds Futterkiste", "Country": "Germany", "City": "Berlin", "ContactTitle": "Sales Representative" } This will be the conceptual starting point. However you deliver this serialized data to the page is up to you (it will have to be AJAX-based, or else you'll come across the same problems you started with). This article assumes that this list of orders is available at the generic endpoint of "/api/order". If you're following along with your own code, you can start by writing all the HTML that will be needed for this example. It's not much, as you can see: <div id="root" class="container"> <h3>Northwind Co. Order View</h3> <div class="clearfix"> <span id="addOrderButton" class="btn pull-right">Add Order</span> </div> <br /> <div id="tableWrap"></div> </div> <script src="js/app/run.js"></script> Before setting up the grid, there's a few Backbone objects that need to be created that mirror the server-side entities and structures. A working knowledge of Backbone is assumed for this article, so these will be presented fairly quickly. The grid view that Backgrid creates is based on a Backbone Collection: In this case, a collection of Order models. A good deal of the action in Backbone takes place on the Collection object, and the objects that are extended from it. Backbone Collections usually handle communication with the server, as well as most of the filtering logic in an application. Because you're essentially building a "smart" list of data, a good deal of the focus for this specific application will be on setting up your Backbone Collection objects. In addition to Collections, Backbone also provides base "classes" (careful; if you're not used to JavaScript ideas, it's not the classical Java/C# idea of classes) for the idea of Models, which make up collections and views. Views are the most dynamic of the three, and often can be seen playing the role of the View and that of the Controller in the model-view-controller (MVC) concept. In order to keep applications organized, a common practice is to set up a root Backbone object extended off of Backbone View, where the higher-level routines of your application are kept. In addition, because JavaScript code all share the same operating environment, it's good practice to expose as few global variables as possible. Exposing just one is almost always possible. In code, this app's adherence to these principles looks like the following: /* Smartgrid.App definition */ // Namespace for our app var Smartgrid = Smartgrid || {}; _(Smartgrid).extend(function () { // A root Backbone.View to hold all the App's functionality var App = Backbone.View.extend({ }); // Return the value of App, so it may be added to the Smartgrid namespace return { App: App }; }()); Now that the namespace and root app object are set up, the two objects needed for Backgrid to understand the data can be set up. These are the Order Model and the corresponding Order Collection. /* Smartgrid.Order definition */ // Namespace var Smartgrid = Smartgrid || {}; _(Smartgrid).extend(function () { // Model Definition var Order = Backbone.Model.extend({ defaults: { Phone: "", ContactName: "" } }); return { Order: Order }; }()); There's nothing too extraordinary going on here; all the frills can be added on a per-implementation basis. The second item that needs to be created is the Backbone Collection, which is mostly defined using the model that's already been created: /* Smartgrid.OrderCollection definition */ // Namespace var Smartgrid = Smartgrid || {}; _(Smartgrid).extend(function () { // Collection Definition var OrderCollection = Backbone.Collection.extend({ url: '/api/order', model: Smartgrid.Order, }); return { OrderCollection: OrderCollection }; }()); There's a few things to point out for those unfamiliar with Backbone syntax. The URL field has been set to /api/order, the generic endpoint mentioned earlier. This will likely change from project to project, so be sure to change this out for the endpoint that makes sense for your context. The last step before getting into the Backgrid implementation and getting to a point where the data is visible is to actually load these files. Then, create a new instance of the Smartgrid.App you defined. One pattern to follow here is to use a "run.js" file that loads in the necessary files asynchronously. In this example, a tiny library called head.js is used: var app; // The function to run after all the necessary files are loaded function init() { app = new Smartgrid.App({ el: $('#root') }); } head.js( // Libraries "/js/lib/jquery.js", "/js/lib/underscore.js", "/js/lib/backbone.js", "/js/lib/backgrid.js", // App '/js/app/app.js', '/js/app/order.js', '/js/app/orderCollection.js', // Callback init ); If you now open up a browser such as Chrome to check out what's available in the console, you'll be able to type in "app" and find the instance of the Smartgrid.App running on your page. Now let's make the app do something more interesting. A logical starting point would be to give the root App view an initialize function. For those familiar with Backbone, the initialize function is something close to a constructor; it's the first thing done when creating a new view, model or collection. To solve the problem at hand, the initialize function for this root view should look something like this: var App = Backbone.View.extend({ initialize: function () { this.orders = new Smartgrid.OrderCollection(); this.orders.fetch(); } }); In this sample, a new OrderCollection is created and then assigned to the field "orders" on this specific instance of Smartgrid.App (in this example, there's only one Smartgrid.App, but conceptually there could be many). After this collection has been attached, the fetch method is invoked, which instructs the collection to perform an AJAX call to the appropriate URL to populate itself. This is why the URL field's string was supplied on the OrderCollection definition. Models are now being updated client-side in their Order instances, but you'll also want to start persisting changes made using the grid to the server. Luckily, Backgrid's internal workings trigger an event on the model to which you can subscribe. Saving after an edit is as simple as hooking into this event: var Order = Backbone.Model.extend({ idAttribute: "OrderId", initialize: function() { this.on('backgrid:edited', this.didEdit, this); }, didEdit: function (model, cell, command) { model.save(); } }); Now that the Order and OrderCollection are set up, the code's ready to get the actual grid initialized. To do this, add an initGrid method to the root app object, which will be called in the existing initialize method: var App = Backbone.View.extend({ initialize: function () { this.orders = new Smartgrid.OrderCollection(); this.orders.fetch(); this.initGrid(); }, initGrid: function () { this.grid = new Backgrid.Grid({ collection: this.orders, columns: columnSettings }); this.grid.render(); this.$el.find('#tableWrap').append(this.grid.el); } }); As you can see, the initGrid method is fairly straightforward: attach a new instance of Backgrid.Grid to the object of interest (in this case the root app object), then tell the grid to render and subsequently append this new view's element to the appropriate place in the DOM. One part that should catch your attention is the mysterious column Settings variable. This is where you define the basic properties of each column: var columnSettings = [ { name: "OrderId", label: "Order ID", cell: "integer" }, { name: "CustomerName", label: "Customer Name", cell: "string" }, { name: "Freight", label: "Freight", cell: "number" }, { name: "ShipAddress", label: "Address", cell: "string" }, { name: "ShipCountry", label: "Country", cell: "string" }, { name: "ShipPostalCode", label: "Postal Code", cell: "string" } ]; This array literally tells Backgrid how to set up the columns. The name value should map to the corresponding attribute on the order model, the label value will serve as the column's "human" title, and the last value, cell, states the type of cell into which you would like that data rendered. Backgrid comes out of the box with many of the common data types you might need: String, Datetime, Time, Number, Integer, Uri, Email, Boolean and so on. More specialized cells are available through plugins built for Backgrid; you can also subclass Backgrid.Cell yourself to suit the specific needs of your grid. At this point, assuming the server-side REST API has been set up correctly, there's a working Grid View synchronizing edits back to the server in real time. There's one problem, however: there's no way to add a new entry. This can be solved with a quick addition to the page's markup, and a corresponding event on the root app object: events: { "click #addOrderButton": "addOrder" }, addOrder: function() { this.orders.create({}); }, } While a huge hurdle has been overcome with this relatively simple application, there's still a good deal of room for progress. The most obvious improvement would be to make this application work in real time in the other direction, perhaps by utilizing WebSockets and a NodeJS backend. The client-side world has come of age and is ready to start finding itself in the rigors of enterprise-level Web solutions. The idea of taking browser-based technologies seriously has been bubbling up through the world of development for a while, championed by some of the biggest players on the Web. It's getting as far from the JavaScript you loved to hate in the 1990s as C# is from C++. If you've been looking at client-side development but haven't figured out a good approach, we'd encourage you to consider looking into a Backgrid/Backbone-based data grid the next time this specific problem lands on your desk. About the Authors Nick Martin is Co-Founder of the Chicago Backbone Group, as well as a Front End Web Developer specializing in JavaScript development at Adage Technologies. His client list includes the Lyric Opera of Chicago, Boston Symphony Orchestra, LA Opera, the Adrienne Arsht Center for the Performing Arts, and more. Jeff Meyers is Co-Founder of the Chicago Backbone Group as well as a Developer specializing in JavaScript development at Adage Technologies. Jeff has used the Backbone framework in several client projects to deliver the performance and engaging interfaces that many have come to expect of the modern Web application.
https://visualstudiomagazine.com/articles/2013/11/01/better-enterprise-data-grids-with-backgrid.aspx?admgarea=features
CC-MAIN-2021-49
refinedweb
2,044
53.1