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 |
|---|---|---|---|---|---|
We haven’t fully immersed ourselves in Java 10 yet, and Java 11 is here. Java 11 is important for more than just a few reasons. Oracle has revamped its support model and come up with a release train that’ll bring rapid updates, about every 6 months.
They’ve changed the licensing and support model which means if you download the Java 11 Oracle JDK, it will be paid for commercial use.
NO. Not necessarily unless you download the Oracle JDK and use it in production.
Note: IntelliJ IDEA 2018.2.4 Community Edition already has support for Java 11.
Table of Contents
- 1 Why is Java 11 important?
- 2 Which JDK build should I download and what are the benefits of each of them?
- 3 How to download Java 11 Free Version?
- 4 Java 11 Features
- 4.1 Running Java File with single command
- 4.2 Java String Methods
- 4.3 Local-Variable Syntax for Lambda Parameters
- 4.4 Nested Based Access Control
- 4.5 JEP 309: Dynamic Class-File Constants
- 4.6 JEP 318: Epsilon: A No-Op Garbage Collector
- 4.7 JEP 320: Remove the Java EE and CORBA Modules
- 4.8 JEP 328: Flight Recorder
- 4.9 JEP 321: HTTP Client
- 4.10 Reading/Writing Strings to and from the Files
- 4.11 JEP 329: ChaCha20 and Poly1305 Cryptographic Algorithms
- 4.12 JEP 315: Improve Aarch64 Intrinsics
- 4.13 JEP 333: ZGC: A Scalable Low-Latency Garbage Collector (Experimental)
- 4.14 JEP 335: Deprecate the Nashorn JavaScript Engine
- 5 Conclusion
Why is Java 11 important?
Java 11 is the second LTS release after Java 8. Since Java 11, Oracle JDK would no longer be free for commercial use.
You can use it in developing stages but to use it commercially, you need to buy a license. If you don’t, you can get an invoice bill from Oracle any day!
Java 10 was the last free Oracle JDK that could be downloaded.
Oracle stops Java 8 support from January 2019. You’ll need to pay for more support.
You can continue using it, but won’t get any patches/security updates.
While Oracle JDK is no longer free, you can always download the Open JDK builds from Oracle or other providers such as AdoptOpenJDK, Azul, IBM, Red Hat etc. In my opinion, unless you are looking for Enterprise level usage with the appetite to pay for the support fees, you can use OpenJDK and upgrade them as and when necessary.
Which JDK build should I download and what are the benefits of each of them?
Since Oracle has created a release train in which a new version would come up every six months, if you are using the free Open JDK by Oracle, you will need to update it every six months, since Oracle won’t provide free updates once the new version is released. This can be challenging to adapt to a company.
Pay for commercial support to Oracle and migrate only from one LTS version to the next LTS version.
This way you’ll get all the updates and support for Java 11 till 2026. You can download Java 17 in 2022.
Stay on free Java version even after its support ends. Though you won’t get security updates and it can open up security loopholes.
Having understood the baggage Java 11 comes with, lets now analyze the important features in Java 11 for developers. We’ll discuss some important JEPs too.
Note: JavaFX will be available as a separate module and not tied to Java JDK’s 6-month release cycle schedule.
How to download Java 11 Free Version?
You can download production ready OpenJDK version from this link. The binaries are in tar or zip format, so just unzip them and set the environment variables to use java compiler and java commands.
Java 11 Features
Let’s discuss the new features introduced with Java 11 from the JEP Process.
Java 11 Features
Running Java File with single command
One major change is that you don’t need to compile the java source file with
javac tool first. You can directly run the file with java command and it implicitly compiles.
This feature comes under JEP 330.
Following is a sneak peek at the new methods of Java String class introduced in Java 11:
Java String Methods
isBlank() – This instance method returns a boolean value. Empty Strings and Strings with only white spaces are treated as blank.
Copyimport java.util.*; public class Main { public static void main(String[] args) throws Exception { // Your code here! System.out.println(" ".isBlank()); //true String s = "Anupam"; System.out.println(s.isBlank()); //false String s1 = ""; System.out.println(s1.isBlank()); //true } }
lines()
This method returns a string array which is a collection of all substrings split by lines.
Copyimport java.util.stream.Collectors; public class Main { public static void main(String[] args) throws Exception { String str = "JD\nJD\nJD"; System.out.println(str); System.out.println(str.lines().collect(Collectors.toList())); } }
The output of the above code is:
strip(), stripLeading(), stripTrailing()
strip() – Removes the white space from both, beginning and the end of string.
strip() is “Unicode-aware” evolution of
trim().
When
trim() was introduced, Unicode wasn’t evolved. Now, the new strip() removes all kinds of whitespaces leading and trailing(check the method
Character.isWhitespace(c) to know if a unicode is whitespace or not)
An example using the above three methods is given below:
Copypublic class Main { public static void main(String[] args) throws Exception { // Your code here! String str = " JD "; System.out.print("Start"); System.out.print(str.strip()); System.out.println("End"); System.out.print("Start"); System.out.print(str.stripLeading()); System.out.println("End"); System.out.print("Start"); System.out.print(str.stripTrailing()); System.out.println("End"); } }
The output in the console from the above code is:
repeat(int)
The repeat method simply repeats the string that many numbers of times as mentioned in the method in the form of an int.
Copypublic class Main { public static void main(String[] args) throws Exception { // Your code here! String str = "=".repeat(2); System.out.println(str); //prints == } }
Local-Variable Syntax for Lambda Parameters
JEP 323, Local-Variable Syntax for Lambda Parameters is the only language feature release in Java 11.
In Java 10, Local Variable Type Inference was introduced. Thus we could infer the type of the variable from the RHS –
var list = new ArrayList<String>();
JEP 323 allows
var to be used to declare the formal parameters of an implicitly typed lambda expression.
We can now define :
Copy(var s1, var s2) -> s1 + s2
This was possible in Java 8 too but got removed in Java 10. Now it’s back in Java 11 to keep things uniform.
But why is this needed when we can just skip the type in the lambda?
If you need to apply an annotation just as @Nullable, you cannot do that without defining the type.
Limitation of this feature – You must specify the type var on all parameters or none.
Things like the following are not possible:
Copy(var s1, s2) -> s1 + s2 //no skipping allowed (var s1, String y) -> s1 + y //no mixing allowed var s1 -> s1 //not allowed. Need parentheses if you use var in lambda.
Nested Based Access Control
Before Java 11 this was possible:
Copypublic class Main { public void myPublic() { } private void myPrivate() { } class Nested { public void nestedPublic() { myPrivate(); } } }
private method of the main class is accessible from the above-nested class in the above manner.
But if we use Java Reflection, it will give an
IllegalStateException.
CopyMethod method = ob.getClass().getDeclaredMethod("myPrivate"); method.invoke(ob);
Java 11 nested access control addresses this concern in reflection.
java.lang.Class introduces three methods in the reflection API:
getNestHost(),
getNestMembers(), and
isNestmateOf().
JEP 309: Dynamic Class-File Constants
The Java class-file format now extends support a new constant pool form, CONSTANT_Dynamic. The goal of this JEP is to reduce the cost and disruption of developing new forms of materializable class-file constraints, by creating a single new constant-pool form that can be parameterized with user-provided behavior.
This enhances performance
JEP 318: Epsilon: A No-Op Garbage Collector
Unlike the JVM GC which is responsible for allocating memory and releasing it, Epsilon only allocates memory.
It allocates memory for the following things:
- Performance testing.
- Memory pressure testing.
- VM interface testing.
- Extremely short lived jobs.
- Last-drop latency improvements.
- Last-drop throughput improvements.
Now Elipson is good only for test environments. It will lead to OutOfMemoryError in production and crash the applications.
The benefit of Elipson is no memory clearance overhead. Hence it’ll give an accurate test result of performance and we can no longer GC for stopping it.
Note: This is an experimental feature.
JEP 320: Remove the Java EE and CORBA Modules
The modules were already deprecated in Java 9. They are now completely removed.
Following packages are removed:
java.xml.ws,
java.xml.bind,
java.activation,
java.xml.ws.annotation,
java.corba,
java.transaction,
java.se.ee,
jdk.xml.ws,
jdk.xml.bind
JEP 328: Flight Recorder
Flight Recorder which earlier used to be a commercial add-on in Oracle JDK is now open sourced since Oracle JDK is itself not free anymore.
JFR is a profiling tool used to gather diagnostics and profiling data from a running Java application.
Its performance overhead is negligible and that’s usually below 1%. Hence it can be used in production applications.
JEP 321: HTTP Client
Java 11 standardizes the Http CLient API.
The new API supports both HTTP/1.1 and HTTP/2. It is designed to improve the overall performance of sending requests by a client and receiving responses from the server. It also natively supports WebSockets.
Reading/Writing Strings to and from the Files
Java 11 strives to make reading and writing of String convenient.
It has introduced the following methods for reading and writing to/from the files:
- readString()
- writeString()
Following code showcases an example of this
CopyPath path = Files.writeString(Files.createTempFile("test", ".txt"), "This was posted on JD"); System.out.println(path); String s = Files.readString(path); System.out.println(s); //This was posted on JD
JEP 329: ChaCha20 and Poly1305 Cryptographic Algorithms
Java 11 provides ChaCha20 and ChaCha20-Poly1305 Cipher implementations. These algorithms will be implemented in the SunJCE provider.
JEP 315: Improve Aarch64 Intrinsics
Improve the existing string and array intrinsics, and implement new intrinsics for the java.lang.Math sin, cos, and log functions, on AArch64 processors.
JEP 333: ZGC: A Scalable Low-Latency Garbage Collector (Experimental)
Java 11 has introduced a low latency GC. This is an experimental feature.
It’s good to see that Oracle is giving importance to GC’s.
JEP 335: Deprecate the Nashorn JavaScript Engine
Nashorn JavaScript script engine and APIs are deprecated thereby indicating that they will be removed in the subsequent releases.
Conclusion
We’ve gone through the important features and updates provided in Java 11. See you soon when Java 12 releases.
Sameh Yousufi says
For developing is ok but only for commercial use need to buy. Am I right?
Pankaj says
Not necessarily. You can use OpenJDK, which is completely free. Using OracleJDK in production is paid now.
Parbati Pati says
Thanks.Nice Article for learners..
Vimal Panchal says
Nice Article on Java 11. Thanks.
This is it or we have other features also released in Java 11?
Paul Bertino says
Really good write up on what is going on with Java 11 and the update train. Plus quite a few good notes on what has changed with the JDK that use to be free.
Raghavan alias Saravanan Muthu says
Thats interesting to see the API changes in Java 11. Of course unexpectedly Oracle has started charging the customers for the JDK Usage on Production, when Microsoft had announced the Dot Net codebase for Linux a few years ago 🙁
Anubhav says
Please answer the below queries :-
One of the important reason why Java is popular, because its freeware.So what do you think the future of Java. ? Are Companies ready to purchase license or move to some other technologies(understand, moving application to other technologies become an himalayan task).?
Are n’t you think by making it commercial Oracle destroy the very soul of JAVA ?
Anupam Chugh says
Hi Anubhav,
Coming to your first question, nobody can predict what lies ahead. Only the companies can tell you whether they plan to purchase a license or not.
With regards to your second question, definitely, it helps Oracle commercially. Besides, Java EE and related projects are now open sourced. This should help Java in the long term.
“Destroying the Soul of Java” – I think it’s too early to make any conclusions.
Thanks
Vishnu says
Yep, I feel that too, Making java as a commercial is really bad.
what could be the main difference b/w OpenJDK, OracleJDK and Amazon corretto. | https://www.journaldev.com/24601/java-11-features | CC-MAIN-2019-30 | refinedweb | 2,154 | 57.87 |
Bardur Arantsson wrote:
> Could we simply rename the UTF8 module to something like SimpleUTF8 to
> avoid confusion about whether it's supposed to 'emulate' Camomile's UTF8
> module?
I don't think there's any need to rename it, with all the consequent
breakage of existing code; there's no namespace clash since (by default)
Camomile's module is called Camomile.UTF8, not just UTF8, and it _is_
supposed to emulate Camomile's module! :)
Note that this incompatibility between ExtLib and Camomile's interfaces
has not been caused by a recent change; if I'm reading the CVS logs
correctly, Camomile.UTF8.first was added some two years ago, and the
Camomile.UTF8 interface has not changed at all since then. Keeping the
two modules synchronised (or, more precisely, keeping ExtLib's UTF8
module signature compatible with Camomile.UnicodeString.Type) should not
be problematic now that it has been identified as a desirable thing.
View entire thread | http://sourceforge.net/p/ocaml-lib/mailman/message/8324963/ | CC-MAIN-2015-35 | refinedweb | 157 | 64 |
Hi - Struts
Hi Hi Friends,
Thanks to ur nice responce
I have sub package in the .java file please let me know how it comnpile in window xp please give the command to compile
Hi
Hi I have got this code but am not totally understanding what...;
import java.util.Scanner;
private static int nextInt() {
public class MatchingPair{
private static class input {
private static int nextInt() {
throw new
getOutputStream() has already been called for this response
getOutputStream() has already been called for this response hi...;
</table>
<html:form
<div class... action class code:
public class RegionCustUserMapXlAction extends DownloadAction
Resources have been modified iPhone
Resources have been modified iPhone Hi,
My client is getting Resources have been modified error while installing AdHoc distribution on his iPhone. How to solve Resources have been modified iPhone error?
Thanks
Hi!
to to enter, like(int,double,float,String,....)
thanx for answering....
Hi,
Try this:
import java.util.*;
class ScannerExample
{
public static void...hi! how can i write aprogram in java by using scanner when asking've a project on railway reservation... i need to connect... for such a programme... plz help me...
Hi Friend,
Try this:
import java.awt.*;
import java.sql.*;
import javax.swing.*;
import java.awt.event.*;
class hi
Before asking question, i would like to thank you for clarifying my doubts.this site help me a lot to learn more & more technologies like servlets, jsp,and struts.
i am doing one struts application where i
hi sakthi prasanna here - Java Beginners
hi sakthi prasanna here import java.lang.*;
import java.awt.... javax.swing.border.LineBorder;
import javax.swing.*;
class Votec extends JFrame implements...;
if(ae.getSource()==r1){
try{//CODE SHUD COME HERE DA....CHECK THIZ
//String url... - Dear Sir ,
I am very new in Struts and want to learn about validation and custom validation. U have given in a such nice way... provide the that examples zip.
Thanks and regards
Sanjeev. Hi friend <p>hi here is my code can you please help me to solve...*;
import org.apache.struts.action.*;
public class LoginAction extends Action...;
<p><html>
<body></p>
<form action="login.do">
Struts 1 Tutorial and example programs
to the Struts Action Class
This lesson is an introduction to Action Class... programming.
Here are the tutorials of Struts 1:
Struts 1... struts ActionFrom class and jsp page.
Using
struts
struts <p>hi here is my code in struts i want to validate my...
}//execute
}//class
struts-config.xml
<struts...;gt;
<html:form
<pre>
Struts - Struts
Struts Hi,
I m getting Error when runing struts application.
i... resolve this.
Hi friend,
Create the web.xml file like...
/WEB-INF/struts-config.xml
Struts Hello
I like to make a registration form in struts inwhich... compelete code.
thanks Hi friend,
Please give details with full....
Struts1/Struts2
For more information on struts visit to : Hi
i am senthil, i am not good in javascripts.
i have... used in a struts aplication.
these are the conditions
1. when u entered....
..............here is the program..............
New Member Personal
Struts validation not work properly - Struts
Struts validation not work properly hi...
i have a problem... to advise, i face it for almost a week now...
this is my action class...
========================================
public class ExampleAction extends Action
Hi .Again me.. - Java Beginners
Hi .Again me.. Hi Friend......
can u pls send me some code on JPanel..
JPanel shoul have
1pic 1RadioButton
..
Like a Voter List...
REsponse me.. Hi friend,
import java.io.*;
import java.awt.
iPhone 3.0 is finally here!
iPhone 3.0 is finally here!
... for the iPhone. The popular features like MMS, SMS forwarding and others... in the latest iPhone software release. These and hundred other features have been
Redirection in struts - Struts
Redirection in struts
Hi Friends
Without sendredirect can we forward a page in struts Hi
There are more ways to forward one page to another page in struts.
For Details you can click here: http
Internationalization using struts - Struts
Internationalization using struts Hi, I want to develop a web application in Hindi language using Struts. I have an small idea... to convert hindi characters into suitable types for struts. I struck here please
Struts Projects
solutions:
EJBCommand
StrutsEJB offers a generic Struts Action class... projects?
Struts Projects will help you master the concepts like updating... the
database
Struts Projects explains here can be used as dummy project to learn
Hi friends
Hi friends How to create a guy based application for cryptography(encryption and decryption) with multiple algorithms like caesar, hash ..etc
using captcha with Struts - Struts
using captcha with Struts Hello everybody: I'm developping a web application using Struts framework, and i would like to use captcha Hi friend,Java Captcha in Struts 2 Application :
layer. Spring MVC, like Struts, uses a single shared instance for each Action...Is Singleton Default in Struts
Hi Friend,
Is Singleton default in Struts ,or should we force
any
Reg struts - Struts
Reg struts Please explain all the tags in Struts. Hi... have the struts jar also in your classpath, it should be like this:CLASSPATH... the name of the struts jar file
hi - Ajax
hour result. waiting for yours reply.. Hi vinoth
Here...hi hi, i am doing Web surfing project. i used start and end timepicker field.it works well. i want to display total hours by using start and end
please help me here
please please"
here is the problem
Automatic Teller Machine [B] Balance [D... then i should proceed here
if i choose b:
YOur Balance is __
if i chose D... display "insufficient Amount"
every after each of the choices a window like
Struts Tutorials
Struts application, specifically how you test the Action class.
The Action class... into a Struts enabled project.
5. Struts Action Class Wizard - Generates Java starter code for a Struts Action class.
7. BC4J JSP Struts Application Wizard
Reply - Struts
Reply
Thanks For Nice responce Technologies::--JSP
please write the code and send me....when click "add new button" then get the null value...its urgent... Hi
can u explain in details about your project
Tracklipse for Track+ Issue Tracker
Integrated
Development Environment. Tracklipse provides a nice user interface... account on that Track+ server
Tracklipse plugin (this is what you get here)
This is the first public release. It has been tested
extensively and provides all
Call-time pass-by-reference has been removed in
Call-time pass-by-reference has been removed in HI,
What is the solution for the error:
Call-time pass-by-reference has been removed in
Thanks
Struts 2 Tutorials - Struts version 2.3.15.1
Here we have discussed the improvements and
bug fixes in the Struts 2...
security issues and bugs that were present in the earlier version of Struts have
been... for making
developer work easy.
Removing default Struts 2 action suffix - How
Struts Project Planning - Struts
Struts Project Planning Hi all,
I am creating a struts application... palling of project like UI planning, classes and interface creation, POJOs... through and which manner.
Thanks in Advance
Casionvaguy Hi friend
Struts file uploading - Struts
Struts file uploading Hi all,
My application I am uploading files using Struts FormFile.
Below is the code.
NewDocumentForm... upload the file with nominal size like 1 mb. But this functionality is breaking when
Struts 2.0.0
of Apache Struts. Struts framework
has been the most popular and widely used...;
POJO Based Action class
Now the action class are POJO classes, which...
Struts 2.0.0
The Struts 2.0
Struts 2.0 - Struts
: people or people.{name}
here is the action:
public class WeekDay...Struts 2.0 Hi ALL,
I am getting following error when I am trying...;
}
public List getDay(){
return day;
}
}:
Here you will get lot of examples through which you
Like Team viewer
Like Team viewer As i am developing one small application, In that i... been displayed on another computer whatever i do in the myapplication that will display another system via all system has been connected through the lan
Understanding Struts - Struts
on is Mifos, it is an open-source application.
I have been reading some... something like a tutorial on such a complex application and which will explain
struts
struts Hi,
1) can we write two controller classes in struts
struts
struts Hi,... please help me out how to store image in database(mysql) using struts
Struts Books
features like Action interceptors and Inversion of Control (IoC) to Struts. ... to the Apache Foundation in 2001, Struts has been rapidly accepted as the leading... exagerate the negatives of Struts in the next section. I like Struts, and think
variable answer1 might not have been initialized
variable answer1 might not have been initialized import java .io.*;
public class Test{
public static void main(String[] args) throws...++;
}
}
}
We have modified your code. Here it is:
import java .io
Java - Struts
Java
Hi Good Morning,
This is chandra Mohan
I have a problem in DispatchAction in Struts.
How can i pass the method name in "action... reach the action.
*******It displays an error like action connot found?
Hi hriends,
Struts is a web page... developers, and everyone between.
Thanks.
Hi friends,
Struts is a web... developers, and everyone between.
Thanks.
Hi friends,
Struts
tiles - Struts
tiles hi friends i got some problem regarding the struts tile
i...
menu here body has to come but it is not displaying here
composemail check it is placed at the below of the menu if you
Struts
Struts Why struts rather than other frame works?
Struts... with other frameworks like Struts2 with Hibernate, Struts2 with Spring web MCV... by the application.
There are several advantages of Struts that makes it popular
exception - Struts
:
can anybody help me
regards,
Sorna
Hi friend,
Here...exception Hi,
While try to upload the example given by you in struts I am getting the exception
javax.servlet.jsp.JspException: Cannot
struts
struts Hi,
i am writing a struts application
first of all i am takeing one registration form enter the data into fileld that
will be saved perfectly.
but now i can apply some validations to that entry details
but with out | http://roseindia.net/tutorialhelp/comment/4071 | CC-MAIN-2016-18 | refinedweb | 1,685 | 67.76 |
Re: How to mix-in __getattr__ after the fact?
- From: dhyams <dhyams@xxxxxxxxx>
- Date: Mon, 31 Oct 2011 05:01:40 -0700 (PDT)
Thanks for all of the responses; everyone was exactly correct, and
obeying the binding rules for special methods did work in the example
above. Unfortunately, I only have read-only access to the class
itself (it was a VTK class wrapped with SWIG), so I had to find
another way to accomplish what I was after.
On Oct 28, 10:26 pm, Lie Ryan <lie.1...@xxxxxxxxx> wrote:
On 10/29/2011 05:20 AM, Ethan Furman wrote:
Python only looks up __xxx__ methods in new-style classes on the class
itself, not on the instances.
So this works:
8<----------------------------------------------------------------
class Cow(object):
pass
def attrgetter(self, a):
print "CAUGHT: Attempting to get attribute", a
bessie = Cow()
Cow.__getattr__ = attrgetter
print bessie.milk
8<----------------------------------------------------------------
a minor modification might be useful:
bessie = Cow()
bessie.__class__.__getattr__ = attrgetter
.
- References:
- How to mix-in __getattr__ after the fact?
- From: dhyams
- Re: How to mix-in __getattr__ after the fact?
- From: Lie Ryan
- Prev by Date: Re: ttk Listbox
- Next by Date: locate executables for different platforms
- Previous by thread: Re: How to mix-in __getattr__ after the fact?
- Next by thread: Fast recursive generators?
- Index(es): | http://coding.derkeiler.com/Archive/Python/comp.lang.python/2011-10/msg01047.html | CC-MAIN-2014-15 | refinedweb | 216 | 63.49 |
DevKit-ES6
A JS library to work with the Olapic API.
Built with ES6, and compiled with Babel, DevKit makes working with the Olapic API something really easy and simple. Forget about endpoints and query strings, just think about entities. Let's take a look at a simple example so you get the idea:
I want to list the photos from an specific stream:
// Import the required classes from DevKit import { OlapicDevKit, OlapicBatch } from 'DevKit-ES6'; // Connect the DevKit instance using your API KEY. OlapicDevKit.getInstance('<YOUR-API-KEY>').connect() .then((customer) => { // Search for a stream (it returns a Promise). return customer.searchStream('my-stream-key'); }) .then((stream) => { // Now that you have the stream, you can create a batch for that entity. // Fetch the media from the stream. return new OlapicBatch(stream).fetch(); }) .then((list) => { // Done, you have a list of media for the selected stream. list.forEach((media) => { console.log(media.get('images/mobile')); }); }) .catch((error) => { // An of course, if there's an error, show it!. console.log('Error ', error); })
That was easy right? Well, that the whole point of DevKit :)
Installation
You can install DevKit using npm.
npm install devkit-es6 --save_dev
Basic usage
This is a quick overview of how DevKit works, for the full documentation, you can go to our ESDoc page.
The classes
Before you do anything with DevKit, you need the load the DevKit JS classes index, which gives you an object with all the DevKit classes, so you can just import it and deconstruct the ones you need:
import { OlapicDevKit, OlapicBatch, OlapicEntity, OlapicEntitiesHandler, OlapicCategoriesHandler, OlapicCategoryEntity, OlapicCustomersHandler, OlapicCustomerEntity, OlapicMediaHandler, OlapicMediaEntity, OlapicMediaBatch, OlapicStreamsHandler, OlapicStreamEntity, OlapicUsersHandler, OlapicUserEntity, OlapicWidgetsHandler, OlapicWidgetEntity, OlapicRestClient, OlapicUtils, } from 'DevKit-ES6';
Before moving to the next part, let's do a quick review of each class:
Connection
In order to have access to the Olapic API entities, you first need to connect DevKit using your Olapic API Key:
import {OlapicDevKit} from 'OlapicDevKit'; OlapicDevKit.getInstance('<YOUR-API-KEY>').connect() .then((customer) => { console.log('Hello ', customer.get('name')); }) .catch((error) => { console.log('Error ', error); })
The
OlapicDevKit object it's the main singleton of the library and because it's a singleton, you can't instantiate it using the
new keyword, so you use the
getInstance() method. As you can see, this method can also be used to set the your API Key, and once that's set, just call
connect(), which will return a
Promise object that when resolve will give you your first entity: The customer.
If you read the example from the the first section, you'll probably be getting the idea for now: entities are connected, and once you have one (like the customer), you can use its methods to connect with other data sources (like streams).
Handlers
Handlers are abstract classes with a set of static methods that allows you to create, parse and obtain entities. For example, DevKit will connect the API and obtain a media entity, but it can't just return it directly to you, there's a lot of information that would be unnecessary for you and other that makes sense on a REST environment. So DevKit sends this raw API response to a handler and the handler takes care of parsing the data, wrapping it on an entity object and returning it to you when its ready to be used.
Most of the handlers methods are used internally by DevKit, but they also have a couple of methods that can help you access entities that are not directly related to the ones you have access to:
get{Entity}ByID() and
get{Entity}ByUrl(). Those methods go directly to the API without needing any other entity.
There are currently six handler classes, one for each entity type:
OlapicCategoriesHandler
OlapicCustomersHandler
OlapicMediaHandler
OlapicStreamsHandler
OlapicUsersHandler
OlapicWidgetsHandler
Entities
These are the most basic type of data in DevKit and represent singular objects from the API. Entities objects have two different types of methods:
- Methods that are just a reflex of the handlers methods. Like
OlapicMediaEntity.getUser(), which it's actually a call to
OlapicMediaHandler.getMediaUser().
- The
get()method. This one doesn't use the handler and it's just a friendly interface for accessing properties using a path-like format. For example, assuming
mit's an
OlapicMediaEntity,
m.get('images/mobile')would be the same as calling
m.data.images.mobile(
datait's where all the entity properties are stored).
Batches
Batches are entities collections, and right now there's only one type of batches: The media batch. Most of the entities have a media batch associated, so you just need an entity in order to instantiate a media batch:
const batch = new OlapicMediaBatch(entity);
The way batches work it's very simple, you have three methods to get the media, and they all return the same promise, an
Array of
OlapicMediaEntity:
.fetch(): This loads the first page of the batch.
.next(): It loads the next page of the batch.
.prev(): It loads the previous page of the batch.
Extra
ES5
Yes, DevKit was built to work with ES6, but if you are still transitioning, we also generate an ES5 build, you just need to
require('DevKit-ES6/es5') and you'll be good to go!.
Development
Install Git hooks
./hooks/install
npm tasks
Quick start
- Run
npm start.
- Open
./demo/index.jsand start playing.
Built with...
- Babel: Compile ES6 code to ES5 compatible.
- Gulp: Manage the project tasks (
build,
serve,
lint, and
docs).
- Jest: Facebook test suite for ES6 built in top of jasmine.
- Coveralls: Track the code coverage generated by Jest.
- Bundlerify: A set of tools for easy running and deployment of ES6 apps.
- :heart: from the Olapic Frontend team.
Version History
1.0.0
Initial version of DevKit.
License
MIT. License file. | https://doc.esdoc.org/github.com/Olapic/DevKit-ES6/ | CC-MAIN-2021-17 | refinedweb | 954 | 52.29 |
Other AliasNs_ConnGets, Ns_ConnFlushHeaders, Ns_ConnReadHeaders, Ns_ConnReadLine
SYNOPSIS
#include "ns.h"
char *
Ns_ConnGets(buf, bufsize, conn)
int
Ns_ConnFlushContent(conn)
int
Ns_ConnRead(conn, vbuf, toread)
int
Ns_ConnReadHeaders(conn, set, nreadPtr)
int
Ns_ConnReadLine(conn, dsPtr, nreadPtr)
ARGUMENTS
-
- char *buf (in)
Pointer to string buffer of length bufsize.
-
- int bufsize (in)
Length of buffer pointer to by buf.
-
- Ns_Conn conn (in)
Pointer to open connection.
-
- Ns_DString dsPtr (out)
Pointer to initialized dstring to receive copied line.
-
- int *nreadPtr (out)
Pointer to integer to receive number of bytes copied.
-
- Ns_Set set (in/out)
Pointer to initialized Ns_Set to copy headers.
-
- int toread (in)
Number of bytes to copy to location starting at vbuf
-
- void *vbuf (in)
Pointer to memory location to copy content.
DESCRIPTION
These routines support copying content from the connection. They all operate by copying from the content buffer returned by a call to Ns_ConnContent, maintaining a private, shared offset into the content. This means that these routines are not actually reading directly from the network and thus will not block waiting for input. See the man page on Ns_ConnContent for details on how the content is pre-read by the server and how resources are managed for small and large content requests.
- char *Ns_ConnGets(buf, bufsize, conn)
- Copies the next available line of text from the content to the given buf string, up to the given bufsize less space for a trailing null (\0). The result is a pointer to buf or NULL if an underlying call to Ns_ConnRead fails.
- int Ns_ConnFlushContent(conn)
- Performs a logical flush of the underlying content available to these routines. It simply moves the private offset to the end of the content. The result is NS_OK unless an underlying call to Ns_ConnContent failed in which case NS_ERROR is returned.
- int Ns_ConnRead(conn, vbuf, toread)
- Copies up to toread bytes from the content to the memory location pointed to by vbuf. The result is the number of bytes copied which will match toread unless less bytes are available in the input or -1 if an underlying call to Ns_ConnContent failed.
- int Ns_ConnReadHeaders(conn, set, nreadPtr)
- Copies lines up to the first blank line or end of content up to the maximum header read size specified with the communication driver "maxheader" parameter (default: 32k). Each line is parsed into "key: value" pairs into the given Ns_Set pointed to be the set argument using the Ns_ParseHeader routine with the Ns_HeaderCaseDisposition specified by the "headercase" server option (default: Preserve). The result is NS_OK if all lines were consumed or NS_ERROR on overflow beyond the max header limit or if there was an error with the underlying call to Ns_ConnRead (including an error of a single line beyond the max line limit as described below). The integer pointed to by the nreadPtr argument, if given, is updated with the total number of bytes consumed. This routine can be useful when parsing multipart/form-data content to collect headers for each part.
- int Ns_ConnReadLine(conn, dsPtr, nreadPtr)
- Copies the next available line to the given dsPtr dstring. The integer pointed to by nreadPtr, if present, is updated with the number of bytes copied. The line will not include the trailing \r\n or \n if present. The function will return NS_OK unless an underlying call to Ns_ConnContent failed or the line exceeds the maximum line read size specified by the communication driver "maxline" parameter (default: 4k). This routine differs from Ns_ConnGets in that it copies the result to a dstring instead of a character buffer, requires a full or end-of-content terminated line, and enforces the maxline limit.
KEYWORDSconnection, read, content | https://manpages.org/ns_connread/3 | CC-MAIN-2022-21 | refinedweb | 598 | 51.89 |
Title: Language detection using character trigrams
Submitter: Douglas Bagnall
(other recipes)
Last Updated: 2004/11/07
Version no: 1.1
Category:
Algorithms
2 vote(s)
Description:
The.
Source: Text Source
#!/usr/bin/python
import random
from urllib import urlopen
class Trigram:
"""From one or more text files,)
0.4
>>> unknown.similarity(reference_en)
0.95
would indicate the unknown text is almost cetrtainly English. As
syntax sugar, the minus sign is overloaded to return the difference
between texts, so the above objects would give you:
>>> unknown - reference_de
0.6
>>> reference_en - unknown # order doesn't matter.
Beware when using urls: HTML won't be parsed out.
Most methods chatter away to standard output, to let you know they're
still there.
"""
length = 0
def __init__(self, fn=None):
self.lut = {}
if fn is not None:
self.parseFile(fn)
def parseFile(self, fn):
pair = ' '
if '://' in fn:
print "trying to fetch url, may take time..."
f = urlopen(fn)
else:
f = open(fn)
for z, line in enumerate(f):
if not z % 1000:
print "line %s" % z
# \n's are spurious in a prose context
for letter in line.strip() + ' ':
d = self.lut.setdefault(pair, {})
d[letter] = d.get(letter, 0) + 1
pair = pair[1] + letter
f.close()
self.measure()
def measure(self):
"""calculates the scalar length of the trigram vector and
stores it in self.length."""
total = 0
for y in self.lut.values():
total += sum([ x * x for x in y.values() ])
self.length = total ** 0.5
def similarity(self, other):
"""returns a number between 0 and 1 indicating similarity.
1 means an identical ratio of trigrams;
0 means no trigrams in common.
"""
if not isinstance(other, Trigram):
raise TypeError("can't compare Trigram with non-Trigram")
lut1 = self.lut
lut2 = other.lut
total = 0
for k in lut1.keys():
if k in lut2:
a = lut1[k]
b = lut2[k]
for x in a:
if x in b:
total += a[x] * b[x]
return float(total) / (self.length * other.length)
def __sub__(self, other):
"""indicates difference between trigram sets; 1 is entirely
different, 0 is entirely the same."""
return 1 - self.similarity(other)
def makeWords(self, count):
"""returns a string of made-up words based on the known text."""
text = []
k = ' '
while count:
n = self.likely(k)
text.append(n)
k = k[1] + n
if n in ' \t':
count -= 1
return ''.join(text)
def likely(self, k):
"""Returns a character likely to follow the given string
two character string, or a space if nothing is found."""
if k not in self.lut:
return ' '
# if you were using this a lot, caching would a good idea.
letters = []
for k, v in self.lut[k].items():
letters.append(k * v)
letters = ''.join(letters)
return random.choice(letters)
def test():
en = Trigram('')
#NB fr and some others have English license text.
# no has english excerpts.
fr = Trigram('')
fi = Trigram('')
no = Trigram('')
se = Trigram('')
no2 = Trigram('')
en2 = Trigram('')
fr2 = Trigram('')
print "calculating difference:"
print "en - fr is %s" % (en - fr)
print "fr - en is %s" % (fr - en)
print "en - en2 is %s" % (en - en2)
print "en - fr2 is %s" % (en - fr2)
print "fr - en2 is %s" % (fr - en2)
print "fr - fr2 is %s" % (fr - fr2)
print "fr2 - en2 is %s" % (fr2 - en2)
print "fi - fr is %s" % (fi - fr)
print "fi - en is %s" % (fi - en)
print "fi - se is %s" % (fi - se)
print "no - se is %s" % (no - se)
print "en - no is %s" % (en - no)
print "no - no2 is %s" % (no - no2)
print "se - no2 is %s" % (se - no2)
print "en - no2 is %s" % (en - no2)
print "fr - no2 is %s" % (fr - no2)
print "\nmaking up English"
print en.makeWords(30)
print "\nmaking up French"
print fr.makeWords(30)
if __name__ == '__main__':
test(): | http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/326576 | crawl-001 | refinedweb | 619 | 75.4 |
Henry Kroll wrote:
--enable-cross now installs x86_64-win32-tcc and i386-win32-tcc installs 3 versions of libtcc1.a with different names: /usr/lib64/[TCCDIR]/libtcc1.a /usr/lib64/[TCCDIR]/lib/libtcc1-win64.a /usr/lib64/[TCCDIR]/lib/libtcc1-win32.a
I'd suggest to use a more meaningful directory name. In particular something with "win32" in the name to indicate that the directory is meant for the win32 cross-compiler support. Also "libtcc1-win64.a" is not nice. It should be just "libtcc1.a" in a different folder IMO. You could use [TCCDIR]/win32/lib/32/libtcc.a and [TCCDIR]/win32/lib/64/libtcc.a and of course [TCCDIR]/win32/include
fixme: I can not make alloca work with x86_64-win32-tcc :(
True, alloca_64 for linux does not work on win64. It uses different registers: #ifdef TCC_TARGET_PE mov %rcx,%rax #else mov %rdi,%rax #endif Are you still trying to make the same files in the same directory for more than one platform? ;-) Btw, a good test is to use the cross-tcc to compile a tcc.exe and then verify that it is able to compile itself under the native platform. Same config.h provided, this tcc.exe and it's output from compiling itself should be identical. --- grischka | http://lists.gnu.org/archive/html/tinycc-devel/2010-12/msg00005.html | CC-MAIN-2017-04 | refinedweb | 212 | 60.41 |
should not affect OWA accessibility or the BES environment per se but an interruption in mail delivery system wide would most likely imply that mail delivery through these alternate means is affected as well. As you suggested, worse case you back out all of your changes and go back to where you were.
Steps to follow
- Setup a new routing group
- Migrate Non US servers to it
- Wait about 15 mins for replication
- Create Routing Group connector between Original First Routing Group and Non US (New Routing group).
- Create new SMTP connector for Non US, with MAIL2 SMTP virtual server as Bridgehead and scope it to the Routing Group.
- Check original SMTP connector (used for US servers). Make sure MAIL SMTP virtual server is bridgehead and make sure it is scoped to the routing group as well.
- Remove Smarthost setting on all BE servers.
YOu might want to also verify SMTP security on all of your virtual servers to make sure they can talk to each other.
Once you've completed the configuration then I'd give replication a little time and do the Microsoft salute (reboot).
- Test mail flow from each back end out to the internet.
- Test mail flow between BE servers in different routing groups
- Ensure mail is taking expected paths by checking the header information.
- Test your other applications (OWA, BES, etc..)
So you would have two separate routing groups
- "US Routing Group" - would have server MAIL, and Servers A-D as members
- "Overseas Routing Group" - would have Server MAIL2, and Servers E-F as members
You would need to setup a Routing group Connector between the two Routing Groups
You would then also need two SMTP connectors to divide the traffic
Mail - US Frontend - Houses SMTP connector with * namespace and is scoped to the US Routing Group
Mail2 - Overseas Frontend - Houses an SMTP connector with the * namespace and is scoped to the Overseas Routing Group
You could then remove the smart host definitions on the BE SMTP Virtual servers.
Watch this video to see how easy it is to make mass changes to Active Directory from an external text file without using complicated scripts.
FYI - There are 2 domains within the Exchange org.
- Move MAIL2, Server E and Server F to that new routing group (drag and Drop).
- Create a Routing group connector between the two RG's.
- Create a new SMTP connector with a Description of something like "Overseas", and add the SMTP Virtual Server of MAIL2 to the Bridgehead section. On the addresspace tab add the * namespace and at the bottom of that tab set the scope to "Routing Group".
- Change the existing SMTP connector to scope to the Routing group as well.
- Remove your smarthost definitions on the BE servers.
- Restart your SMTP services and Routing Engines.
Any problems with this setup for OWA access or Blackberry Enterprise server? I guess worst case I can place it back to the same config I have now.
Can you take a look at my steps and let me know if you see a flaw in my plan?
Steps to follow.
Setup a new routing group.
Migrate the Non US servers to it.
Wait for replication and reboot moved servers (It is Microsoft after all) to be safe.
Setup SMTP connectors between the routing groups.
Setup Outbound SMTP Connectors in each routing group.
Final Config. 2 Routing groups. US Based (original First Routing Group) and Non US (new Routing Group) Both FE servers can still deliver external inbound email to all BE servers via the SMTP connector between groups. Same connector allows internal email to flow between BE servers. The other SMTP connectors (1 in each routing group) route outbound email to the proper FE server for delivery.
Full points to you of course and many thanks. | https://www.experts-exchange.com/questions/23771699/Setup-a-SMTP-Connector-for-Outbound-Email-to-multiple-Front-End-Servers.html | CC-MAIN-2018-22 | refinedweb | 632 | 70.73 |
UNIT 2: Recursion
Table of Contents
1 Recursion Review
1.1 Recursion!
Yes, it's back! You all learned about recursion in IC210, and you might have thought that it's pretty useless because you could do all the same things with iteration. And because recursion is so confusing.
Well, Data Structures (and most especially, trees) is where recursion becomes really, really useful. When we have more sophisticated data structures and algorithms, we need recursion to write simple code that works and we can understand.
The simple fact is this: with many, many data structures, recursion is WAY easier to cope with than iteration is. Embrace it, because it's about to make your life easier. Today, then, is an IC210-level reminder of what recursion is, and how it works
Recursion is a function calling itself. So, if we understand how function calls work, we'll understand recursion a lot better. Imagine the following set of functions (in pseudocode):
f1() { print "inside f1" } f2() { print "starting f2" f1() print "leaving f2" } main() { print "starting main" f2() print "leaving main" }, recursion. Let's consider the standard first-recursion-example of finding a factorial using recursion:
int fac(int n) { if (n == 0) return 1; return n * fac(n-1); }, which is
what
fac(0),} \\ } \]
1.2.
2 Linked List traversal
Let's define a Linked Linked List of
int's as follows:
public class LinkedList{ private class Node{ private int data; private Node next; //... remaining methods } private Node head,tail; //head and tail of the list //... remaining methods }
Using that definition, a traversal of the list iteratively would look something like this:
void traverse(){ Node n = head; while (n != null){ //... perform some action on n n = n.next; } }
and here is a similar process, this time using recursion:
void traverse(){ traverse(head); } void traverse(Node n) { if (n == null) //Empty next is a good base case return; //... perform some action on n traverse(n.next) }
If we were to start the traversal at the head, like
traverse(head) in the
traverse() method,
then the two code snippets would perform identical operations.
Make sure you understand how this works.
Soon, there will be data
structures where the iterative version is pages long, and the
recursive version is five lines. You want to know and understand
this.
As an example of a recursive traversal and action that we can take is a
length() method.
public int length(Node cur) { if (cur == null) return 0; return 1+length(cur.next); }
Another example is to add to a sorted linked list. For example, if we
have a linked list holding the integers 1, 2, and 4, after running
addInOrder(3), we would have a linked list with the
Integers 1, 2,
3, and 4.
public void addInOrder(int element) { head = addInOrder(element, head); if (tail == null) //first item inserted tail = head; } //This is a helper method, so our user doesn't have to know or care //about nodes. private Node addInOrder(int element, Node n) { if (n==null) return new Node(element); if (n.data > element) { Node t = new Node(element); t.next = n; return t; } n.next = addInOrder( element, n.next); return n; }
Make some examples to try the above on, and understand why it works! Your homework will go better.
3 Big-O with Recursion
3.1 Determining the Big-O of a Recursive Function
We have some practice identifying the Big-O of iterative algorithms. However, now that we're (again) experts on recursion, it's important that we be able to identify the Big-O of recursive algorithms. We're not going to spend a huge amount of time on this; that's Algorithms' job (note for IT people: consider taking Algorithms. It's an Important Class). However, it is important that you can identify some of the most common patterns.
Let's start with an example: linked-list traversal.
void traverse(Node node) { if (node == null) //base case return; //... perform some action on n traverse(n.next) //recursive case }
Obviously, we have two cases; a base case, and a recursive case.
We're going to write a function \(T\) that describes the number of
steps taken in each case as a function of the input. The input for
this example will be length of the remaining list, if we were to
assume that
node were the head. The base case can then easily be
defined as when \(n=0\), or the length of the list of nodes following the
current node is 0, as would occur when
node is null. The base
case is easily defined then as:
\[T(0) = 2\]
This is because when \(n=0\), there is a constant amount of work to do (namely, do the comparison in the if-statement, and perform the return statement). Ultimately, this constant 2 won't really matter in the big-O, but when we're dealing with recursion it's safer not to do big-O until the end.
Now what about the other case - if \(n > 0\)?
\[T(n) = 2 + T(n-1)\]
That is, it is two constant steps plus doing the work of performing
the work on the next node in the list. This is because when \(n > 0\),
we do some constant amount of work (if statement comparison, function
call to
traverse, etc), then run it all again on the remainder of
the list.
The two of these functions together are known as a recurrence relation. So the recurrence relation of this algorithm is:
\[\begin{align*} T(0) &= 2 \\ T(n > 0) &= 2 + T(n-1) \end{align*} \]
The same exact thing can also be written as
\[ T(n) = \begin{cases} 2,& n=0 \\ 2 + T(n-1), & n > 0 \end{cases} \]
3.2 Solving Recurrence Relations
Our five-step process for solving a recurrence relation is:
- Write down the recurrence relation.
- Expand the recurrence relation, for several lines.
- Figure out what you would write for the \(i\)-th line.
- Figure out what value of \(i\) would result in the base case.
- In your equation from (3), replace \(i\) with the solution from (4).
OK, so we've written it. Let's do step 2.
\[\begin{align*} T(n) &= 2 + T(n-1)\\ &= 2 + \underbrace{2 + T(n-2))}_{T(n-1)}\\ &= 2 + 2 + \underbrace{2 + T(n-3)}_{T(n-2)}\\ \end{align*}\]
And so on. But this is probably enough to recognize the pattern. Let's do step 3. Hopefully you agree that on the i-th line, we'd have:
\[T(n) = 2i + T(n-i)\]
So when does this stop? Well, that's where the other part of our recurrence relation comes in: our base case equation tells us that when \(n=i\), it's just \(2\). So, we figure out what value of \(i\) makes the \(T(n-i)\) equal to our base case of \(T(0)\). In this case, that happens when \(i=n\) because when \(i=n\) then \(n-i=0\).
Finally, we do step five, and take our equation \(T(n) = 2i + T(n-i)\), and replace \(i\) with our solution of step 4 (\(i=n\)), to get \(T(n) = 2n + T(0)\). Because \(T(n-n) = T(0)=2\), the runtime of that equation is
\[2n+2\]
which is \(O(n)\).
3.3 A Simpler Example!
Let's do one more, and this time, let's do the simple recursive sum function:
int sum(int n){ if(n==0) return 0; else return n+sum(n-1); }
In the base case, we can say one step occurs, since all we are doing is returning 0 and this occurs when \(n=0\).
\[ T(0) = 1 \]
The number of steps in the recursive case (when \(n>0\)) is one sum, one subtraction, and the function call — so three steps plus the number of steps in the recursive call.
\[ T(n) = 3 + T(n-1) \]
We can now write the recursive relation:
\[ T(n) = \begin{cases} 1,& n=0 \\ 3 + T(n-1), & n > 0 \end{cases} \]
Let's now identify the pattern:\begin{array} TT(n) &= 3 + T(n-1) \\ &= 3 + 3 + T(n-2) \\ &= 3 + 3 + 3 + T(n-3) \\ & \ldots \\ T(n) & =3i + T(n-i) \end{array}
Substituting for \(i\) the value \(n\), we get
\[ 3n + T(n-n) = 3n+T(0) = 3n+1 \]
And clearly, \(3n+1\) is \(O(n)\)
3.4 A Harder Example!
Before you saw an iterative version of binary search. Here's a slightly different recursive version, but the principle is the same. Let's now use recurance relations to identify the Big-O.
int binarySearch(int[] A, int toFind) { return binarySearch(A, 0, A.length-1, toFind); } boolean binarySearch(int[] A, int left, int right, int toFind) { if(right-left <= 1){ if(toFind == A[right] && right > 0) return right; else if(toFind == A[left]) return left; else return -1; //not found } int mid = (left + right) / 2; if (toFind < A[mid]) return binarySearch(A, left, mid-1, toFind); else if (toFind > A[mid]) return binarySearch(A, mid+1, right); else return mid; //it must be equal, so we found it }
Let's say that \(n\) is defined as the distances between
left and
right, so the base case is when \(n \le 1\). There are two recursive
cases, though, but the worst case for both is the same number. So we if we
count steps
\[T(n) = \begin{cases} 7,& n = 1 \\ 6 + T\left(\tfrac{n}{2}\right),& n > 1 \end{cases}\]
(*If you disagree or come up with different values for 6 and 7, remember that those constants do not actually matter at all for the big-O, as long as they're constant! If you were solving this for a HW or exam and put down 3 and 9 instead of 6 and 7, no problem!)
So let's figure out the Big-O. Step 2 is to get the pattern for the \(i\)th step:
\[\begin{align*} T(n) &= 6 + T\left(\frac{n}{2}\right) \\ &= 6 + \underbrace{6 + T\left(\frac{n}{4}\right)}_{T\left(\frac{n}{2}\right)} \\ &= 6 + 6 + \underbrace{6 + T\left(\frac{n}{6}\right)}_{T\left(\frac{n}{4}\right)} \\ &= 6i + T\left(\frac{n}{2^i}\right)\\ \end{align*}\]
The next step is to determine how big \(i\) has to be to hit the base case:
\[\begin{align*} \frac{n}{2^i} & \le 1 \\ 2^i &\ge n \\ i &\ge \log_2 n \end{align*}\]
Finally, we substitute our discovered value of \(i\) into the formula.
\[ T(n) = 6(\log_2 n) + T\left(\frac{n}{2^{\log_2 n}}\right) \\ \]
Notice that \(2^{\log_2 n}\) is \(n\) by the definition of logorithms, so we can now solve to get the non-recursive total cost:
\[\begin{align*} T(n) &= 6(\log_2 n) + T\left(\frac{n}{2^{\log_2 n}}\right) \\ &=6\lg n + T(n/n) \\ &= 6\lg n + T(1) \\ & = 6\lg n + 7 \end{align*}\]
which of course is \(O(\log n)\) as we expected.
(* From now on, I'm going to write \(\lg n\) instead of \(\log_2 n\), because I'm lazy. You should feel free to do the same.)
Hopefully, before the last line, it was clear to you at a minimum that this was sublinear, that is, faster than linear time as we identified before.
Credit: Ric Crabbe, Gavin Taylor and Dan Roche for the original versions of these notes. | https://www.usna.edu/Users/cs/aviv/classes/ic312/f16/units/02/unit.html | CC-MAIN-2018-09 | refinedweb | 1,908 | 69.82 |
How to Make a Flash Animation in Adobe Flash Professional / CC
This tutorial covers a step-by-step process on how to make Flash animation. We will draw a jetpack with a thrusting animation in Flash and give it vertical flight with some simple actionscript code.
The actionscript code is short, giving just vertical mouse control over the animation. So you are free to experiment with additional code for horizontal movement, and even add more animation. You will see that creating a simple flash animation is not that hard after all. So give it a try!
At least basic knowledge of Flash is required to follow the tutorial smoothly. But you can learn from this Flash animation tutorial, even if you are an absolute beginner. Watch the video for a quick preview of what to do.
Download Flash files
Watch the Video:
Step 1)
Start Adobe Flash and create 3 Layers:
One for the background, one for the jetpack and one for Actions.
Put any kind of simple background.
Step 2)
In the layer Jetpack, draw a vertical rectangle shape and convert it to a Symbol. Give it any name.
The bottom section here is what will become of the rectangle.
The top 2 points of the rectangle should be stretched apart to make the top part wider and the bottom 2 points should be brought closer to each other.
With the black cursor, slightly curve the left and right sides.
Curve towards the bottom at the top.
And curve upwards at the bottom.
Now the top part.
Select the line tool and from both sides draw 2 vectors and connect them. It will look like a cone.
Now use the black cursor tool once more and curve these 2 lines to make them more round.
Important: Using the bucket tools, fill in these shapes with any colour(I used white).
Again with the line tool draw 2 straps for the rocket.
Fill them with a very dark gray colour.
If you want you can slightly curve the left of these straps with the black cursor tool, as shown in the picture.
Make the top area red coloured as in the picture.
Select the inner red shape with the black cursor tool, copy it(Command + C), then right click outside it -> paste in place. This will create a shape identical to it.
Keep the shape selected and go to Modify -> Shape -> Expand Fill… as shown in the picture.
Choose inset and use 5.
You will notice that the new Shape has shrunk. Give it a white colour.
Repeat these steps with the new, white shape.
When you get the new shape give it a gradient fill – exactly as shown in the picture:
Now move on to the bottom section.
Fill in the white sections with a linear blue gradient exactly as shown in the picture:
In case the lines by any chance aren’t straight, use the gradient tool to align them properly.
Convert this whole drawing into another symbol and add the following filters to give it a nice effect.
Step 3)
Convert that to a new symbol once more. It will look like this.
In this new symbol, copy and paste the inner symbol to get 2 of these tanks.
If you’d like you can use the transform tool to slightly rotate the tanks to their co-responding directions.
Add a new layer and put it behind the tanks’ layer. Lock the tanks’ Layer and in the new Layer, draw 2 black rectangles to represent the straps.
Now, select both tanks and give them an Adjust Color filter with a Contrast value of 24.
And once again, convert this whole thing to yet another new Symbol and call it Jetpack. Finally, this is the main Symbol. Insert a keyframe on frame 2. Create a new Layer with 2 empty keyframes.
On those 2 empty keyframes, right click -> Actions and write in stop();
Step 4)
Now, on to the fire animation.
In the Jetpack symbol, on keyframe 2, right click on the object and press Duplicate Symbol. Give it a name like mcAnimation.
Duplicate its inner symbols 2 more times until you get to the one with 2 layers(Where you drew the straps).
Here, select the tank symbol on the left and duplicate it as well and call it PartNew.
Now, select the tank on the right and right click -> Swap symbol and choose PartNew.
It is IMPORTANT to follow these steps accurately.
Go inside Animated Tank and create a new Layer called Fire.
Choose the deco tool.
In the preferences use these under Fire Animation:
Just below the tank, in the layer fire, click with your mouse.
And at the end you will get 70 frames.
You will need to remove most of them.
Select the first 50 or so, right click -> Remove frames.
Add a regular frame in the Tank layer on the frame the fire ends.
Now select the “Edit multiple frames” icon as in the picture:
Click anywhere on the stage outside the fire and press Control + A.
This will select all frames.
Now, using the Transform tool, rotate the fire towards the bottom and position it exactly below the jetpack’s tank.
Step 5)
Go back to the stage.
If the jetpack is too big, using the transform tool and holding down shift, or in the properties panel, resize it.
This is what it should look like:
Step 6)
The last step involves writing some actionscript code to test it all out.
In the main stage, give the jetpack instance the name mcJetpack.
In the actions layer, right click -> Actions and paste in the following code:
import flash.events.MouseEvent; import flash.events.Event; var mouseDown:Boolean = false; var speed:uint = 4; const DOWN_Y:uint = 300; const UP_Y:uint = 100; mcJetpack.x = stage.stageWidth / 2; mcJetpack.y = DOWN_Y; stage.addEventListener(MouseEvent.MOUSE_DOWN, mdh); stage.addEventListener(MouseEvent.MOUSE_UP, muh); addEventListener(Event.ENTER_FRAME, efh); function mdh(event:MouseEvent):void { mouseDown = true; mcJetpack.gotoAndStop(2); } function muh(event:MouseEvent):void { mouseDown = false; mcJetpack.gotoAndStop(1); } function efh(event:Event):void { if (mouseDown) { if (mcJetpack.y > UP_Y) { mcJetpack.y -= speed; } } else { if (mcJetpack.y < DOWN_Y) { mcJetpack.y += speed; } } }
So now, using the mouse button you can fly up with the jetpack and activate its fire animation.
Hint: You can put a character with the jetpack as shown in the example:
Check out this simple Flash animation below. Click and hold mouse to accelerate up:
I hope you learned something from this Flash animation tutorial. Try modifying the code to make the character move in other directions. See, you can learn some actionscript programming here too! Check out this actionscript programming tutorial for more.
More Flash tutorials:
If you liked this Flash tutorial, please share with your friends: | http://www.tutorialboneyard.com/simple-flash-animation/ | CC-MAIN-2015-32 | refinedweb | 1,131 | 76.01 |
Ross Gardler wrote:
> David Crossley wrote:
> >Ross Gardler wrote:
> >
> >>Some of the confusion over Views seems to have come about because they
> >>do much more than just replace skins. They add a whole new feature set.
> >>We therefore decided to define some terminology to help clarify the
> >>situation.
> >
> >The sooner that we get this settled the better.
>
> +1, especially since Thorsten is refactoring things now. I'm not going
> to comment on the thread just yet since I started it, I'd like to hear
> other views first.
>
> I will add one more point though. We are using the "ft:" namespace
> identifier for templates, this is the same identifier used for
> forms-templates in Cocoon. We should think about a different identifier
> (I know we can change it if there is ever a clash, but wouldn't it be
> better to plan forward there is already an occasion where forms are
> being used in an experimental Forrest site).
That name "templates" was missing from your overview.
We need to define its role and perhaps find a better name.
-David | http://mail-archives.apache.org/mod_mbox/forrest-dev/200508.mbox/%3C20050819131759.GB24691@igg.indexgeo.com.au%3E | CC-MAIN-2016-40 | refinedweb | 179 | 72.26 |
When is a string not a string?
As part of my “work” on the ECMA-334 TC49-TG2 technical group, standardizing C# 5 (which will probably be completed long after C# 6 is out… but it’s a start!) I’ve had the pleasure of being exposed to some of the interesting ways in which Vladimir Reshetnikov has tortured C#. This post highlights one of the issues he’s raised. As usual, it will probably never impact 99.999% of C# developers… but it’s a lovely little problem to look at.
Relevant specifications referenced in this post:
– The Unicode Standard, version 7.0.0 – in particular, chapter 3
– C# 5 (Word document)
– ECMA-335 (CLI specification)
What is a string?
How would you define the
string (or
System.String) type? I can imagine a number of responses to that question, from vague to pretty specific, and not all well-defined:
- “Some text”
- A sequence of characters
- A sequence of Unicode characters
- A sequence of 16-bit characters
- A sequence of UTF-16 code units
The last of these is correct. The C# 5 specification (section 1.3) states:
Character and string processing in C# uses Unicode encoding. The
chartype represents a UTF-16 code unit, and the
stringtype represents a sequence of UTF-16 code units.
So far, so good. But that’s C#. What about IL? What does that use, and does it matter? It turns out that it does… Strings need to be represented in IL as constants, and the nature of that representation is important, not only in terms of the encoding used, but how the encoded data is interpreted. In particular, a sequence of UTF-16 code units isn’t always representable as a sequence of UTF-8 code units.
I feel ill (formed)
Consider the C# string literal
"X\uD800Y". That is a string consisting of three UTF-16 code units:
- 0x0058 – ‘X’
- 0xD800 – High surrogate
- 0x0059 – ‘Y’
That’s fine as a string – it’s even a Unicode string according to the spec (item D80). However, it’s ill-formed (item D84). That’s because the UTF-16 code unit 0xD800 doesn’t map to a Unicode scalar value (item D76) – the set of Unicode scalar values explicitly excludes the high/low surrogate code points.
Just in case you’re new to surrogate pairs: UTF-16 only deals in 16-bit code units, which means it can’t cope with the whole of Unicode (which ranges from U+0000 to U+10FFFF inclusive). If you want to represent a value greater than U+FFFF in UTF-16, you need to use two UTF-16 code units: a high surrogate (in the range 0xD800 to 0xDBFF) followed by a low surrogate (in the range 0xDC00 to 0xDFFF). So a high surrogate on its own makes no sense. It’s a valid UTF-16 code unit in itself, but it only has meaning when followed by a low surrogate.
Show me some code!
So what does this have to do with C#? Well, string constants have to be represented in IL somehow. As it happens, there are two different representations: most of the time, UTF-16 is used, but attribute constructor arguments use UTF-8.
Let’s take an example:
using System; using System.ComponentModel; using System.Text; using System.Linq; [Description(Value)] class Test { const string Value = "X\ud800Y"; static void Main() { var description = (DescriptionAttribute) typeof(Test).GetCustomAttributes(typeof(DescriptionAttribute), true)[0]; DumpString("Attribute", description.Description); DumpString("Constant", Value); } static void DumpString(string name, string text) { var utf16 = text.Select(c => ((uint) c).ToString("x4")); Console.WriteLine("{0}: {1}", name, string.Join(" ", utf16)); } }
The output of this code (under .NET) is:
Attribute: 0058 fffd fffd 0059 Constant: 0058 d800 0059
As you can see, the “constant” (
Test.Value) has been preserved as a sequence of UTF-16 code units, but the attribute property has U+FFFD (the Unicode replacement character which is used to indicate broken data when decoding binary to text). Let’s dig a little deeper and look at the IL for the attribute and the constant:
.custom instance void [System]System.ComponentModel.DescriptionAttribute::.ctor(string)
= ( 01 00 05 58 ED A0 80 59 00 00 )
.field private static literal string Value
= bytearray (58 00 00 D8 59 00 )
The format of the constant (
Value) is really simple – it’s just little-endian UTF-16. The format of the attribute is specified in ECMA-335 section II.23.3. Here, the meaning is:
- Prolog (01 00)
- Fixed arguments (for specified constructor signature)
- 05 58 ED A0 80 59 (a single string argument as a SerString)
- 05 (the length, i.e. 5, as a PackedLen)
- 58 ED A0 80 59 (the UTF-8-encoded form of the string)
- Number of named arguments (00 00)
- Named arguments (there aren’t any)
The interesting part is the “UTF-8-encoded form of the string” here. It’s not valid UTF-8, because the input isn’t a well-formed string. The compiler has taken the high surrogate, determined that there isn’t a low surrogate after it, and just treated it as a value to be encoded in the normal UTF-8 way of encoding anything in the range U+0800 to U+FFFF inclusive.
It’s worth noting that if we had a full surrogate pair, UTF-8 would encode the single Unicode scalar value being represented, using 4 bytes. For example, if we change the declaration of
Value to:
const string Value = "X\ud800\udc00Y";
then the UTF-8 bytes in the IL are 58 F0 90 80 80 59 – where F0 90 80 80 is the UTF-8 encoding for U+10000. That’s a well-formed string, and we get the same value for both the description attribute and the constant.
So in our original example, the string constant (encoded as UTF-16 in the IL) is just decoded without checking whether or not it’s ill-formed, whereas the attribute argument (encoded as UTF-8) is decoded with extra validation, which detects the ill-formed code unit sequence and replaces it.
Encoding behaviour
So which approach is right? According to the Unicode specification (item C10) both could be fine:
When a process interprets a code unit sequence which purports to be in a Unicode character encoding form, it shall treat ill-formed code unit sequences as an error condition and shall not interpret such sequences as characters.
and
Conformant processes cannot interpret ill-formed code unit sequences. However, the conformance clauses do not prevent processes from operating on code unit sequences that do not purport to be in a Unicode character encoding form. For example, for performance reasons a low-level string operation may simply operate directly on code units, without interpreting them as characters. See, especially, the discussion under D89.
It’s not at all clear to me whether either the attribute argument or the constant value “purports to be in a Unicode character encoding form”. In my experience, very few pieces of documentation or specification are clear about whether they expect a piece of text to be well-formed or not.
Additionally,
System.Text.Encoding implementations can often be configured to determine how they behave when encoding or decoding ill-formed data. For example,
Encoding.UTF8.GetBytes(Value) returns byte sequence 58 EF BF BD 59 – in other words, it spots the bad data and replaces it with U+FFFD as part of the encoding… so decoding this value will result in X U+FFFD Y with no problems. On the other hand, if you use
new UTF8Encoding(true, true).GetBytes(Value), an exception will be thrown. The first constructor argument is whether or not to emit a byte order mark under certain circumstances; the second one is what dictates the encoding behaviour in the face of invalid data, along with the
EncoderFallback and
DecoderFallback properties.
Language behaviour
So should this compile at all? Well, the language specification doesn’t currently prohibit it – but specifications can be changed :)
In fact, both csc and Roslyn do prohibit the use of ill-formed strings with certain attributes. For example, with
DllImportAttribute:
[DllImport(Value)] static extern void Foo();
This gives an error when
Value is ill-formed:
error CS0591: Invalid value for argument to 'DllImport' attribute
There may be other attributes this is applied to as well; I’m not sure.
If we take it as read that the ill-formed value won’t be decoded back to its original form when the attribute is instantiated, I think it would be entirely reasonable to make it a compile-time failure – for attributes. (This is assuming that the runtime behaviour can’t be changed to just propagate the ill-formed string.)
What about the constant value though? Should that be allowed? Can it serve any purpose? Well, the precise value I’ve given is probably not terribly helpful – but it could make sense to have a string constant which ends with a high surrogate or starts with a low surrogate… because it can then be combined with another string to form a well-formed UTF-16 string. Of course, you should be very careful about this sort of thing – read the Unicode Technical Report 36 “Security Considerations” for some thoroughly alarming possibilities.
Corollaries
One interesting aspect to all of this is that “string encoding arithmetic” doesn’t behave as you might expect it to. For example, consider this method:
// Bad code! string SplitEncodeDecodeAndRecombine (string input, int splitPoint, Encoding encoding) { byte[] firstPart = encoding.GetBytes(input.Substring(0, splitPoint)); byte[] secondPart = encoding.GetBytes(input.Substring(splitPoint)); return encoding.GetString(firstPart) + encoding.GetString(secondPart); }
You might expect that this would be a no-op so long as everything is non-null and
splitPoint is within range… but if you happen to split in the middle of a surrogate pair, it’s not going to be happy. There may well be other potential problems lurking there, depending on things like normalization form – I don’t think so, but at this point I’m unwilling to bet too heavily on string behaviour.
If you think the above code is unrealistic, just imagine partitioning a large body of text, whether that’s across network packets, files, or whatever. You might feel clever for realizing that without a bit of care you’d get binary data split between UTF-16 code units… but even handling that doesn’t save you. Yikes.
I’m tempted to swear off text data entirely at this point. Floating point is a nightmare, dates and times… well, you know my feelings about those. I wonder what projects are available that only need to deal with integers, and where all operations are guaranteed not to overflow. Let me know if you have any.
Conclusion
Text is hard.! | https://codeblog.jonskeet.uk/2014/11/07/when-is-a-string-not-a-string/?like_comment=14819&_wpnonce=b472bdb42b | CC-MAIN-2020-45 | refinedweb | 1,802 | 62.07 |
Daniel Nielsen is an Embedded Software Engineer. He is currently using D in his spare time for an unpublished Roguelike and warns that he “may produce bursts of D Evangelism”.
I remember one day in my youth, before the dawn of Internet, telling my teachers about “my” new algorithm, only to learn it had been discovered by the ancient Greeks in ~300 BC. This is the story of my life and probably of many who are reading this. It is easy to “invent” something; being the first, not so much!
Anyway, this is what all the fuss is about this time:
template from(string moduleName) { mixin("import from = " ~ moduleName ~ ";"); }
The TL;DR version: A new idiom to achieve even lazier imports.
Before the C programmers start running for the hills, please forget you ever got burned by C++ templates. The above snippet doesn’t look that complicated, now does it? If you enjoy inventing new abstractions, take my advice and give D a try. Powerful, yet an ideal beginner’s language. No need to be a template archwizard.
Before we proceed further, I’d like to call out Andrei Alexandrescu for identifying that there is a problem which needs solving. Please see his in depth motivation in DIP 1005. Many thanks also to Dominikus Dittes Scherkl, who helped trigger the magic spark by making his own counter proposal and questioning if there really is a need to change the language specification in order to obtain Dependency-Carrying Declarations (DIP 1005).
D, like many modern languages, has a fully fledged module system where symbols are directly imported (unlike the infamous C
#include). This has ultimately resulted in the widespread use of local imports, limiting the scope as much as possible, in preference to the somewhat slower and less maintainable module-level imports:
// A module-level import import std.datetime; void fun(SysTime time) { import std.stdio; // A local import ... }
Similar lazy import idioms are possible in other languages, for instance Python.
The observant among you might notice that because
SysTime is used as the type of a function parameter,
std.datetime must be imported at module level. Which brings us to the point of this blog post (and DIP 1005). How can we get around that?
void fun(from!"std.datetime".SysTime time) { import std.stdio; ... }
There you have it, the Scherkl-Nielsen self-important lookup.
In order to fully understand what’s going on, you may need to learn some D-isms. Let’s break it down.
- When instantiating a template (via the
!operator), if the TemplateArgument is one token long, the parentheses can be omitted from the template parameters. So
from!"std.datetime"is the same as
from!("std.datetime"). It may seem trivial, but you’d be surprised how much readability is improved by avoiding ubiquitous punctuation noise.
- Eponymous templates. The declaration of a template looks like this:
template y() { int x; }
With that, you have to type
y!().xin order to reach the int. Oh, ze horror! Is that a smiley? Give me
xalready! That’s exactly what eponymous templates accomplish:
template x() { int x; }
Now that the template and its only member have the same name,
x!().xcan be shortened to simply
x.
- Renamed imports allow accessing an imported module via a user-specified namespace. Here,
std.stdiois imported normally:
void printSomething(string s) { import std.stdio; writeln(s); // The normal way std.stdio.writeln(s) // An alternative using the fully qualified // symbol name, for disambiguation }
Now it’s imported and renamed as
io:
void printSomething(string s) { import io = std.stdio; io.writeln(s); // Must be accessed like this. writeln(s); // Error std.stdio.writeln(s); // Error }
Combining what we have so far:
template dt() { import dt = std.datetime; } void fun(dt!().SysTime time) {}
It works perfectly fine. The only thing which remains is to make it generic.
- String concatenation is achieved with the
~operator.
string hey = "Hello," ~ " World!"; assert(hey == "Hello, World!");
- String mixins put the power of a compiler writer at your fingertips. Let’s generate code at compile time, then compile it. This is typically used for domain-specific languages (see Pegged for one prominent use of a DSL in D), but in our simple case we only need to generate one single statement based on the name of the module we want to import. Putting it all together, we get the final form, allowing us to import any symbol from any module inline:
template from(string moduleName) { mixin("import from = " ~ moduleName ~ ";"); }
In the end, is it all really worth the effort? Using one comparison made by Jack Stouffer:
import std.datetime; import std.traits; void func(T)(SysTime a, T value) if (isIntegral!T) { import std.stdio : writeln; writeln(a, value); }
Versus:
void func(T)(from!"std.datetime".SysTime a, T value) if (from!"std.traits".isIntegral!T) { import std.stdio : writeln; writeln(a, value); }
In this particular case, the total compilation time dropped to ~30% of the original, while the binary size dropped to ~41% of the original.
What about the linker, I hear you cry? Sure, it can remove unused code. But it’s not always as easy as it sounds, in particular due to module constructors (think
__attribute__((constructor))). In either case, it’s always more efficient to avoid generating unused code in the first place rather than removing it afterwards.
So this combination of D features was waiting there to be used, but somehow no one had stumbled on it before. I agreed with the need Andrei identified for Dependency-Carrying Declarations, yet I wanted even more. I wanted Dependency-Carrying Expressions. My primary motivation comes from being exposed to way too much legacy C89 code.
void foo(void) { #ifdef XXX /* needed to silence unused variable warnings */ int x; #endif ... lots of code ... #ifdef XXX x = bar(); #endif }
Variables or modules, in the end they’re all just symbols. For the same reason C99 allowed declaring variables in the middle of functions, one should be allowed to import modules where they are first used. D already allows importing anywhere in a scope, but not in declarations or expressions. It was with this mindset that I saw Dominikus Dittes Scherkl’s snippet:
fun.ST fun() { import someModule.SomeType; alias ST = SomeType; ... }
Clever, yet for one thing it doesn’t adhere to the DRY principle. Still, it was that tiny dot in
fun.ST which caused the spark. There it was again, the Dependency-Carrying Expression of my dreams.
Criteria:
- It must not require repeating
fun, since that causes problems when refactoring
- It must be lazy
- It must be possible today with no compiler updates
Templates are the poster children of lazy constructs; they don’t generate any code until instantiated. So that seemed a good place to start.
Typically when using eponymous templates, you would have the template turn into a function, type, variable or alias. But why make the distinction? Once again, they’re all just symbols in the end. We could have used an alias to the desired module (see Scherkl’s snippet above); using the renamed imports feature is just a short-cut for import and alias. Maybe it was this simplified view of modules that made me see more clearly.
Now then, is this the only solution? No. As a challenge to the reader, try to figure out what this does and, more importantly, its flaw. Can you fix it?
static struct STD { template opDispatch(string moduleName) { mixin("import opDispatch = std." ~ moduleName ~ ";"); } }
3 thoughts on “A New Import Idiom”
I’d like to say, this could be a language feature instead of a design pattern. Make the compiler read imports that occur at the beginning of the function before parsing the function declaration. e.g.:
void fun(SysTime time) {
import std.datetime;
import std.stdio;
…
}
Actually, the D Improvement Proposal linked in the blog post (DIP 1005) was about adding a language feature to handle this. The idiom the post describes came about as part of a debate on the DIP (it’s not so simple a thing as just letting the compiler parse the local imports first — there was a lot of discussion on it). If it can be done cleanly in the library, there’s no need to add a feature.
The original forum discussion: | https://dlang.org/blog/2017/02/13/a-new-import-idiom/ | CC-MAIN-2017-17 | refinedweb | 1,383 | 67.15 |
This article presents a simple stock explorer application which demonstrates how a publish/subscribe mechanism can be used to write classic request/response style applications. More specifically, how to build a simple financial query service that uses Yahoo Finance along with Morningstar financial information to present a simple querying API. We are going to use emitter.io service to handle our publish/subscribe communication. Emitter source-code can can be seen on GitHub.
Now, emitter is a distributed, publish-subscribe, MQTT broker. In this article we assume some basic knowledge of MQTT and we won’t go in detail through the specifications of the protocol and how to use it, however, here’s a couple of important points:
sensor/1/temperature/
We are going to implement a simple request-response topology in this article on top of a publish/subscribe protocol. The strategy is quite simple:
quote-request
{ symbol: "MSFT", reply: "1234"}
quote-response/xxx
xxx
reply
We are going to start with first building the server which can receive requests on quote-request channel and reply on quote-response/... channel. We start by importing emitter along with other business logic that handles.
quote-response/...
import (
"./finance/provider"
emitter "github.com/emitter-io/go"
)
In our main() function we start by initializing a new Provider which will handle the financial querying of the data. Since I’d like to keep this article short, we’re not going to explore in depth how this is implemented, but feel free to explore the source code for this on GitHub.
main()
Provider
p := provider.NewProvider()
o := emitter.NewClientOptions()
In the options we set the message handler, which is a function which will get called every time the server receives a message. Every time we receive a request, we parse it using json.Unmarshal() and call GetQuotes() method on the provider, which will return a response containing the stock and financial information for the ticker symbol along with the dividend history. We then simply serialize the result and publish it to the quote-response/ channel with a subchannel specified in the request, making sure that only a the requester receives this response.
json.Unmarshal()
GetQuotes()
quote-response/
// Set the message handler
o.SetOnMessageHandler(func(c emitter.Emitter, msg emitter.Message) {
fmt.Printf("Received message: %s %v\n", msg.Payload(), msg.Topic())
// Parse the request
var request map[string]string
if err := json.Unmarshal(msg.Payload(), &request); err != nil {
fmt.Println("Error: Unable to parse the request")
return
}
quotes, err := p.GetQuotes(request["symbol"])
if err != nil {
fmt.Println("Error: Unable to process the request")
return
}
response, _ := json.Marshal(quotes[0])
c.Publish(key, "quote-response/"+request["reply"], response)
})
Finally, we need to simply start the server by creating a new emitter client using NewClient() function, connect to it and subscribe to the quote-request channel so that we can receive the requests.
NewClient()
// Create a new emitter client and connect to the broker
c := emitter.NewClient(o)
sToken := c.Connect()
if sToken.Wait() && sToken.Error() != nil {
panic("Error on Client.Connect(): " + sToken.Error().Error())
}
c.Subscribe("FKLs16Vo7W4RjYCvU86Nk0GvHNi5AK8t", "quote-request")
The client we’re going to build uses VueJs data binding framework to bind the results we receive from our server to the HTML DOM. Of course, you could use any other data binding framework such as React, Angular or Durandal to do so.
Our model, as shown below consists of a symbol property which is bound to the input box, and the result will be bound using simple handlebar tags. For more information, check out the index.html page which contains all the layouting and data binding. The model itself is rather simple, as you can see.
symbol
result
index.html
var vue = new Vue({
el: '#app',
data: {
symbol: 'AAPL',
result: new Object()
},
methods: {
query: function () {
// publish a query
},
},
});
We continue by implementing the networking part using emitter. First order of business is to connect to the emitter broker. We simply call emitter.connect() and it will connect us to api.emitter.io:8080 endpoint, which is a free sandbox.
emitter.connect()
api.emitter.io:8080
var emitter = emitter.connect({
secure: true
});
Once we’re connected to the server, we need to subscribe to the quote-response/ channel with the suffix which represents a unique id of the current browser. The idea here is that we subscribe to channel unique for this user session. That way only one user gets notified with the response.
emitter.on('connect', function(){
// once we're connected, subscribe to the 'quote-response' channel
console.log('emitter: connected');
emitter.subscribe({
key: resKey,
channel: "quote-response/" + getPersistentVisitorId()
});
})
We then add a query method which we will call every time the search button is pressed. In this method, we will simply publish a message (e.g.: { symbol: "AAPL", reply: "12345" }) to quote-request channel, where we provide a reply parameter so our server knows where to reply. This will simply be appended to the channel where our server will publish the response, e.g. quote-response/12345 in the example above.
{ symbol: "AAPL", reply: "12345" }
quote-response/12345
query: function () {
// publish a message to the chat channel
console.log('emitter: publishing ');
emitter.publish({
key: reqKey,
channel: "quote-request",
message: JSON.stringify({
symbol: this.$data.symbol,
reply: getPersistentVisitorId()
})
});
Finally, every time we will receive a message, we will simply convert it from JSON format to an objet using msg.asObject() method, do some work on the data and bind the result to our view.
msg.asObject()
emitter.on('message', function(msg){
// log that we've received a message
var data = msg.asObject();
console.log('emitter: received ', msg.asObject());
// do some work
// ...
// bind the result to the screen
vue.$data.result = data;
});
We are going to show a couple of graphs in our stock explorer results page:
For the first graph, we are going to simply use Yahoo Finance graph API. This can be used by simply providing the ticker in the chart.finance.yahoo endpoint which returns an image, for example will show us the graph for Tesla Motors Inc., with moving average for 50 and 200 days (green and red line). As shown below, we can just replace the ticker with the data from our model by using {{result.Symbol}}.
chart.finance.yahoo
{{result.Symbol}}
<img class="col-sm-12 yahoo-chart" src="{{result.Symbol}}&t=6m&q=l&l=on&z=l&p=m50,m200" />
The second graph we want to present is the dividend history. We are going to use chartist javascript library to do the visualisation. The function below draws the dividend chart when we receive the data as a response from emitter broker. We simply iterate through the dividends and push labels (month/day values) in one array and series (corresponding values) to series array. Once this is done, we call Chartist.Line() function to trigger the rendering of the chart.
series
Chartist.Line()
function drawDividendChart(data){
labels = [];
series = [];
data.DividendHistory.forEach(function(d){
labels.push(formatDate(d.Date));
series.push(d.Value);
});
// apply the chart
new Chartist.Line('#dividends-chart', {
labels: labels,
series: [series]
}, {
fullWidth: true,
axisX: {
showGrid: false,
labelInterpolationFnc: function(value, index) {
return index % 2 === 0 ? value : null;
}
}
});
}
You might wonder why you’d want to use a publish/subscribe system for simple request-response communication. It is a bit like a foundation of a house: if you want to build a house of just one floor high, you could decide to have a foundation that can only support one floor. That will work just fine. However, if you ever want to extend your house with an extra floor, you are in trouble - there are no easy ways to expand. You can imagine publish/subscribe as the foundation of your application. Request-response is your first floor. Perhaps request-response is the only thing you need right now, but at a later stage you might want to add other ways of communication. In the stock explorer application presented in this article, suppose you want to send push notifications to users based on specific events, such as stock levels going through certain thresholds. Ideally, this will also work if a receiver is offline, he should be able to receive the message upon connecting. This can easily be done in the following way with emitter in 2 simple steps.
// publish a message over the stocks/msft channel and store it
emitter.publish({
key: "<channel key>",
channel: "stocks/msft",
ttl: 86400, // message will be deliverd max 86400 sec (one day) later if receiver was offline
message: "microsoft stock up by 1.0%"
});
// connect, retrieve all messages that have been stored related to ticker MSFT
// also, subscribe to receive all newly created messages
emitter.on('connect', function(){
emitter.subscribe({
key: "<channel key>",
channel: "stocks/msft"
});
});
By using the pubsub system you now in fact did the following: You implemented one-to-many communication, you decoupled sender and receiver, you used message storage to deliver messages with delay if a receiver was offline, you created message filtering based on (sub)channels. All of that with just a couple of lines of code. Isn’t it awesome?
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) | https://www.codeproject.com/Articles/1159256/Stock-Explorer-Using-Pub-Sub-for-Request-Response | CC-MAIN-2021-39 | refinedweb | 1,535 | 57.37 |
1- At commented // 1 main thread creates a new thread and makes it wait at the thread pool
2- At commented // 2
main thread sleeps for 100 milisecond .so, the new thread crated gets its turn and sleeps for 1000 milisec by executing doDelay(1000) inside run method
3-At commented // 3 (i.e after 100 milisecond ) the main thread calls interrupt(); , thus interrupting the sleeping thread .
so Ex-tA should come in output.
Ireneusz Kordal wrote:Line 21:
this.wait(); must be within a synchronized block (or synchronized method).
You need to interrupt t, which is the actual Thread running the commands
public class tA extends Thread
Adwin Lorance wrote:That is correct , Thread implements Runnable .. But it is always a good practice to implement the interface Runnable than extending Thread , as it gives you flexibility to inherit from other classes.. Anyways , it wont make a difference if you extend from Thread or implement Runnable ..
Adwin | http://www.coderanch.com/t/497361/java/java/Executing-Thread | CC-MAIN-2014-41 | refinedweb | 157 | 62.98 |
XML::RDB - Perl extension to convert XML files into RDB schemas and populate, and unpopulate them. Works with XML Schemas too."); # See the 'README' file for a LOT more information...
XML::RDB - Perl extension to convert XML files into RDB schemas and populate, and unpopulate them. Works with XML Schemas too. Analyzes relationships within either an XML file or an XML Schema to create RDB tables to hold that document (or any XML document that conforms to the XML Schema).
XML/RDB version 1.0 ====================
A long-arse how-to & explanation:
An XML document is an ideal transport for data between heterogeneous systems. XML documents are also an ideal way to represent hierarchical data generically. Yet when it comes time to store, query, compare, edit, delete, and even create these data-centric documents, few mature XML tools exist. Fortunately, there is an older technology that has been successfully handling these tasks for years. It also has (fairly) standard syntax and a standard query language (in fact it has _the_ Standard Query Language (1)). Everyone's got one - your pal and mine - the Relational Database Management System (RDBMS). While native XML Databases are best suited for storing document- centric data like XHTML files, data-centric documents, like a Juniper Network's(tm) router configuration, are best stored within a RDBMS, a system which is tuned for data storage and manipulation (2). By bringing these two technologies together, we can leverage each system's strengths, minimize their weaknesses, and learn that by using Perl, two seemingly opposed technologies can become friends. An example of hierarchical data is a router's configuration. Using a Perl module, an XML-ified version of a Juniper router's configuration can be retrieved easily. Almost any bit of router information can be requested and received in XML using Juniper Network's JUNOScript (3) technology. Using a standard set of XML libraries, these XML documents are easily manipulated at a low level. Unfortunately, higher-level tools to manipulate XML are either immature, unproven, unknown, or simply non-existent. But by putting XML documents into a RDBMS we have access to all of the robust, mature data manipulation tools we need. The ability to map XML to RDBMSs (and then back into XML) plays to both system's strengths: XML provides self-describing data transport, and the RDBMS provides data managing and manipulating tools. But how should we put an XML document into a RDBMS? The quick and dirty answer is to store the entire XML document in a RDBMS as a Binary Large Object (BLOB) or Character Large Object (CLOB) - but these approaches solve very little and certainly do not take full advantage of the RDBMS. Other existing tools force you to pre-create your RDBMS schema to match your XML Documents, or require you to create either an XML or proprietary template to define the mapping between your XML documents and your RDBMS table sets. But I thought XML was self-describing - why should we have to describe our data twice? Fortunately we don't have to. Using the self-describing nature of XML documents, and Perl, there is a better way.
Relationships
The key to transforming XML into a RDBMS is analyzing the relationships in an XML document and then mapping those relationships into a RDBMS. Let's examine the kinds of relationships utilized by a RDBMS - there are three: 1. 1 to 1 relationship (1:1) We are only interested in the simplest case - the primary entity must participate in the relationship but the secondary entity may not. e.g. I own 1 car but my 1 car does not own me (or does it????) This relationship is modeled by storing the secondary entity's primary key as a foreign key in the primary entity's table. 2. 1 to N relationship (1:N) There is only one case for our purposes - the primary entity may possess multiple secondary entities. e.g. I own zero or more books. This relationship is modeled by storing the primary entity's (the '1') primary key as a foreign key in the secondary entity's (the 'N') table. 3. N to N relationship (N:N) For the purposes of transforming XML we do not need these! e.g. the relationship between students and classes - each student can have multiple classes and each class can have multiple students. This relationship is modeled by creating a new table whose rows hold the primary key from each foreign table. XML documents can be distilled into just the first two kinds of RDBMS relationships. Let's look at some XML:
<address-book> <name>My Address Book</name> <entry> <name type="Person">Mark</name> <street>Perl Place</street> </entry> <entry> <name>Bob</name> <street>Heck Ave.</street> <state>F"state" </entry> </address-book>
Here <address-book> is the 'root' entity in this XML fragment and has two sub-entities, <name> and <entry>. <address-book> and <name> form a 1:1 relationship and <address-book> and <entry> form a 1:N relationship. Similarly there are 1:1 relationships between <entity> and <name>, <street>, and <state>. That's all we need to know! Without further ado, let's put Perl to work.
Module #1 - MakeTables
Our first Perl script does exactly what we just did - it analyzes the relationships between the entities in an XML document and outputs those relationships as a set of RDB tables. It takes one required argument - the XML file you want to analyze. Optionally a second parameter may be passed containing a filename in which to write the RDB Schema, if not passed then it's output to STDOUT. Here's the generated table that corresponds to the <address-book> entity:
CREATE TABLE gen_address_book ( gen_name_id integer NULL, id integer NOT NULL, PRIMARY KEY (id) );
Lots to note here - first, all table names are prefixed by a user-supplied string - in this case 'gen' (for 'generated'). Also, some characters that offend RDBMSs are transformed into underscores (don't worry, the real names are also stored in the database for exporting back to XML). Finally, a generated primary key column is added to each table (named 'id'). One to one relationships So what we've got is a table that contains a reference to a row in the 'gen_name' table to model our 1:1 relationship between <address-book> and <name>. The primary key of a 'gen_name' row (the 'id' value) becomes a foreign key in a 'gen_address_book' row (the 'gen_name_id' value). One to many relationships But what about the 1:N relationship between <address-book> and <entry>? As good RDBMS design tells us, it is modeled by placing the primary key of the '1' part of the relationship as a foreign key in the 'N' part of the relationship. Let's look at the table generated for the <entry> entity:
CREATE TABLE gen_entry ( gen_address_book_fk integer NOT NULL, gen_name_id integer NULL, gen_state_id integer NULL, gen_street_id integer NULL, id integer NOT NULL, PRIMARY KEY (id) );
The interesting bit is the 'gen_address_book_fk' column. This column will contain the primary key of a gen_address_book row that contains this <entry>. The other columns you will recognize as parts of a 1:1 relationship between <entry> and <name>, <state>, and <street>. And of course the generated primary key column 'id'. Plain old text Let's now look at the gen_name table:
CREATE TABLE gen_name ( gen_name_type_attribute text NULL, gen_name_value text NULL, id integer NOT NULL, PRIMARY KEY (id) );
The column 'gen_name_value' holds the text associated with this entity. The column 'gen_name_type_attribute' holds the text associated with the attribute 'type' in the entity <name>. Again, there is a generated table that contains the mappings between RDBMS column and table names and XML names. The other tables gen_state and gen_street simply consist of a '_value' column and a generated primary key. Note we did not have to do anything to generate these tables! We simply fed our XML document to MakeTables. Meta tables To help keep track of everything, MakeTables creates four extra tables to hold meta-information about this XML document. These tables are only used internally, so you do not have to worry about them. Two of the tables are used to create primary keys in a generic, database-independent fashion and are not very interesting for our purposes. The table 'gen_element_names' contains the mappings between table and column names to XML names - this is table we alluded to earlier. It looks like this:
CREATE TABLE gen_element_names ( db_name text NOT NULL , xml_name text NOT NULL );
Every time MakeTables has to generate a RDBMS equivalent name for an XML tag (every tag and attribute name must be converted), another row gets added to this table. Here are the rows that get inserted into this table from our example (generated by MakeTables of course):
INSERT INTO gen_element_names VALUES ('gen_street','street'); INSERT INTO gen_element_names VALUES ('gen_address_book','address-book'); INSERT INTO gen_element_names VALUES ('gen_name_type_attribute','type'); INSERT INTO gen_element_names VALUES ('gen_entry','entry'); INSERT INTO gen_element_names VALUES ('gen_name','name'); INSERT INTO gen_element_names VALUES ('gen_state','state');
Using this table we can accurately re-create our XML document. The final generated meta table is called 'gen_link_tables'. This table contains a list of all of the 1:N relationships in the XML document. Like the 'gen_element_names' table it is only used internally for bookkeeping. Here's what it looks like:
CREATE TABLE gen_link_tables ( one_table text NOT NULL , many_table text NOT NULL );
And here's the row that gets inserted into it using our example:
INSERT INTO gen_link_tables VALUES ('gen_address_book','entry');
There is only one 1:N relationship in our XML document, so there's only one row in this table. This table is used by later scripts to populate and unpopulate the data into and out of our RDBMS. Now that our tables have been generated, it's time to import them into our database and populate them. The output of MakeTables is a bunch of 'CREATE TABLE' and 'INSERT' statements. Each RDBMS has its own way to import these statements - check your documentation. Later we'll see an real live example using MySQL (10).
Module #2 - PopulateTables
Once our tables exist in our database we need to actually pull the data out of our XML document and put it into our RDBMS. Remember, MakeTables only analyzes the relationships between elements in an XML document - the actual data is ignored. The actual data parsing is the job of module #2, PopulateTables. It takes only one argument, the name of the XML document that was passed to MakeTables. The data contained within that XML document will be transformed and stored into your RDBMS. Let's take a look at our RDBMS after we've run PopulateTables. (using MySQL) using our example:
mysql> select * from gen_address_book; +-------------+----+ | gen_name_id | id | +-------------+----+ | 1 | 1 | +-------------+----+
Ok, not too exciting. Let's see the 'gen_name' table:
mysql> select * from gen_name; +-------------------------+-----------------+----+ | gen_name_type_attribute | gen_name_value | id | +-------------------------+-----------------+----+ | NULL | My Address Book | 1 | | Person | Mark | 2 | | NULL | Bob | 3 | +-------------------------+-----------------+----+
Now things get a little more interesting! We see our 1:1 relationship between <address-book> and <name> via the 'gen_name_id' in the gen_address_book table matching the 'id' in the gen_name table, and sure enough its value is our <address-book>'s name, 'My Address Book'. You'll notice that the 'gen_name_type_attribute' column is null for the two <name>'s that don't possess this attribute and is set to 'Person' for the <name> that does. Let's see the 1:N relationships in the 'gen_entry' table:
mysql> select * from gen_entry; +---------------------+-------------+--------------+---------------+----+ | gen_address_book_fk | gen_name_id | gen_state_id | gen_street_id | id | +---------------------+-------------+--------------+---------------+----+ | 1 | 2 | NULL | 1 | 1 | | 1 | 3 | 1 | 2 | 2 | +---------------------+-------------+--------------+---------------+----+
The two <entry>'s associated with this <address-book> are linked by the foreign key column. The 'gen_address_book_fk' column matches the 'id' column in our gen_address_book row. You can also see the 1:1 relationship between each entry and its name (via the 'gen_name_id' column). The state and street 1:1 relationships are similar. It's in! We've transformed our XML document into our RDBMS. At this point we can take a break, sip some coffee, and rest assured that our RDBMS has our data under its watchful eye. We can use any of the mature RDBMS utilities and tools to massage, view, change, add, backup, and delete our information. For some people this could indeed be the end of the line - but not for us!
Modules #3 - UnpopulateTables
Our XML is in our RDBMS - now we want to get it out! We've put our data through the RDBMS tool's ringer, doing all the zany things to it we wanted - but now we want our XML back. Say hello to module #3, UnpopulateTables. But before we get too acquainted there is one piece about script #2, PopulateTables that I have not yet mentioned, that makes our life easier. After PopulateTables finishes populating our tables, it returns a handy 2 element array containing the root table name & a primary key uniquely identifying a row in that table that corresponds to the XML file we just inserted into our DB. It has told us all we need to know to re-create the XML we just RDBMS-ized. UnpopulateTables takes that very same two element array - the name of the 'root' table and the generated primary key for the row we're interested in. I'll discuss what that second bit of output is later. In our example the root table is 'gen_address_book', and since it's the first one we added to our database its primary key is one. This tells UnpopulateTables where to start unwinding from our RDBMS back into XML. If you knew the table name and primary key of any other row you could create just a fragment of your XML by specifying those values to UnpopulateTables (all easily gleaned from your RDBMS). And out goes your XML.
Bonus Module #4 - UnpopulateSchema
We've come full circle. What a not-so-long-but-definitely strange trip it's been. We've gone from an XML document into a RDBMS and back out again. Yet something is still missing. The problem lies with not-fully-specified XML documents. What if another <address-book> document had a <zip-code> tag within the <entry> tag? Two different table sets would be generated. That makes it impossible to put two different-yet-related XML documents into the same set of tables. What is needed, when generating RDBMS tables from MakeTables, is a 'fully-specified' XML document containing all possible tags and attributes in all possible configurations. Then all 1:1 and 1:N relationships could be correctly identified and all attributes could be accounted for. But how can we get a 'fully-specified' XML document? We can generate one using XML Schema (4). Written in XML themselves, XML Schemas fully specify what may be contained within a conforming XML document. The bonus fourth script - UnpopulateSchema - will 'unpopulate' an XML Schema stored in your RDBMS as a fully-specified XML document. This XML document can then be fed to MakeTables to generate fully-specified RDBMS tables. Now that's quite a mouthful, but if you have an XML Schema for your documents, you can use that, and not a specific instantiation of that Schema (which might not have all of the allowed entities in all possible configurations) to create your RDBMS tables. Then all conforming XML documents can be fed to PopulateTables to populate your RDBMS without worrying about table mismatch. The secret is that XML Schemas are well-formed XML documents themselves. Running MakeTables on your Schema itself and then importing those tables into your RDBMS gets the ball rolling. Then you populate your RDBMS the usual way by running PopulateTables with the XML Schema as the supplied XML Document. Finally running UnpopulateSchema instead of UnpopulateTables against that data will output a fully-specified XML document, instead of just your XML Schema back again. Since all XML Schemas must follow strict guidelines, UnpopulateSchema only needs to know the primary key of the XML Schema in your RDBMS. This is the second bit of information output by PopulateTables. XML Schema is a very complicated specification. Not all of the nooks and crannies of the specification are supported by UnpopulateSchema - which is by far the longest and most complicated for the four scripts. Here's what's supported - the numbers in parentheses correspond to sections in the XML Schema Primer (5): Named Simple and Complex types (2.2 & 2.3) Simple type restrictions and enumerations (2.3) List types (2.3.1) Unions types (2.3.2) Anonymous Type Definitions and choices (2.4) Complex Types from Simple Types (simpleContent) (2.5.1) Mixed content (2.5.2) Empty content (2.5.3) Choice and Sequence groups (including xsd:group) (2.7) 'All' group (2.7) Attribute groups (2.8) Nil Values (2.9) Deriving Types by Extension (4.2) Deriving Complex Types by Restriction (4.4) Abstract Elements & Types (partially) (4.7) Here's what's not: anyType (2.5.4) (not applicable) Target Namespaces & Unqualified locals (3.1) Qualified locals (3.2) Importing & Multiple documents (4.1) Redefining Types & Groups (4.5) Substitution Groups (4.6) Abstract Elements & Types (partially) (4.7) Controlling the Creation & Use of Derived Types (4.8) (not applicable) Specifying Uniqueness (5.1) (not applicable) Defining Keys & their References (5.2) (not applicable) Importing Types (5.4) Any Element, Any Attribute (5.5) (not applicable) Schema Location (5.6) The namespace and importing can be handled by collecting all referenced Schemas by hand and creating one large document from them. This list is subject to change - especially the namespace and importing functions.
Now Things Get Interesting!
Let your mind go! Not only can _any_ XML document be stored in your RDBMS, but you don't even have to have a XML document to start with. All you need is an XML Schema. Use that to create your table set. You don't have to use PopulateTables to populate the database - use whatever tool you want. When you're ready, use UnpopulateTables and you've magically got well-formed, valid XML to pass on to whomever you choose. Any XML document -- SOAP (6), SVG (7), XSLT (8), whatever, can easily be intelligently imported into your RDBMS. Once XML Schema really gets going and all XML documents are defined using it, you've got a ready-made RDBMS system just waiting for conforming XML documents.
What You Need To Make It Work
In your constructor call to XML::RDB you provide the path to your configuration file. The format of the file is key/values pairs - one per line - delimited by '='. See 'config.test' in the base directory for all of the options.
the most important (& only) variable you must set is 'DSN':
DSN=DBI:mysql:database=TEST This is a MySQL DSN - alter it to fit your needs. You can The _only_ thing you need to change is the DSN, after that you are ready to rumble. See the 'config.test' file in this directory for all the other options.
Module Dependencies
As Sir Isaac Newton stood on the shoulders of giants, so have I. These scripts could not function without these great modules available from the CPAN (9): DBI and DBD::<your RDBMS> You need these to talk to your RDBMS at a low level. DBIx::Recordset The scripts use this awesome module to talk to your RDBMS as a higher level. DBIx::Sequence This module provides RDBMS-independent unique primary key generation. DBIx::DBSchema This module provides MakeTables with a RDBMS-independent way to generate tables. XML::DOM The workhorse - parses all the XML so I don't have to! URI::Escape Only used by UnpopulateTables to keep the XML clean.
Tested platforms
The scripts were developed using Perl 5.6.0 and also run under 5.6.1. There's no reason why the scripts should not run on any recent Perl5 distribution. Both MySQL and PostgreSQL(11) have been tested - MySQL on FreeBSD 4.2 and Linux (RedHat 7.1) and PostgreSQL on Linux (RedHat 7.1). Note column lengths can get long, and PostgreSQL is by default limited to 31-character long columns. I had to recompile PostgreSQL with a more reasonable 64-character length limit to keep everything happy.
A Sample Run using MySQL");
Limitations and Future Directions
There is a program written in Java that generates XML Schemas from DTDs. This provides a clear migration path. However, DTDs do not provide as much information as XML Schemas do, so it would be wise not to count on automated tools to do the complete conversion for you. Also, once XML Schema parsers become readily available, UnpopulateSchema should take advantage of them, since the current 'parsing' it does is pretty basic. Finally, all XML Schemas must pass through your RDBMS, which is not optimal. Some XML documents rely on the order of the entities, but after under-going into an RDBMS and back out again the order is lost. A 'nice' way to preserve entity order would be a grand addition. Both UnpopulateTables and UnpopulateSchema utilize the same intermediary format from going from a RDBMS to XML. The modularization of these modules allow XML stored in a RDBMS to be extracted to any other format, such as HTML. Future work in this area will produce very interesting transformations. Also, using something like XML::Writer (10) to output XML would probably be cleaner and lead to further benefits down the road. Finally, both MakeTables and PopulateTables use XML::DOM, which loads the entire XML document tree into memory. Investigation into using the Simple API for XML (SAX) (12) to reduce memory consumption could prove very fruitful. Also both UnpopulateTables and UnpopulateSchema load the entire RDB into memory before outputting their transformations, so investigations into lowering the memory footprint of these scripts will yield beneficial results.
Acknowledgments
Rob Enns and Phil Shafer for having the foresight to use XML in our routers that eventually led to these scripts, and Cynthia Tham, fellow member of the Juniper JUNOScript team!
References
1. Standard SQL ISO/IEC 9075:1992, "Information Technology --- Database Languages --- SQL" 2. For a discussion of XML and RDBMSs see "XML Database Products" by Ronald Bourret, 3. JUNOScript Guide 4. XML Schema 5. XML Schema Primer 6. SOAP 7. SVG 8. XSL and XSLT 9. CPAN 10. MySQL 11. PostgreSQL 12. SAX
Juniper Networks is a registered trademark of Juniper Networks, Inc. Internet Processor, Internet Processor II, JUNOS, JUNOScript, M5, M10, M20, M40, and M160 are trademarks of Juniper Networks, Inc. All other trademarks, service marks, registered trademarks, or registered service marks may be the property of their respective owners. All specifications are subject to change without notice. Copyright © 2001, Juniper Networks, Inc. All rights reserved.
XML Schema
Mark Trostler, <trostler@juniper.net>
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. | http://search.cpan.org/~metzzo/XML-RDB-1.1/RDB.pm | crawl-002 | refinedweb | 3,814 | 55.34 |
Hello Chad, Thursday, January 19, 2006, 9:52:59 PM, you wrote: SC> Thanks, Bulat. Taking a look at Hal's FastIO library now... SC> Hal, it looks like your library could be helpful, especially if there is SC> a way to construct a FastIO.Handle from stdin. Can this be done, or do I SC> need to start with an actual file? add the following to fastio.c: void* openStdin() { return stdin; } and this to FastIO.hs: openStdin :: IO Handle openStdin = do h <- c__openStdin return (H h) foreign import ccall "openStdin" c__openStdin :: IO (Ptr ()) btw, id this is a test for shootout - is using C code acceptable? this way you can rewrite the whole program :) -- Best regards, Bulat mailto:bulatz at HotPOP.com | http://www.haskell.org/pipermail/haskell-cafe/2006-January/014032.html | CC-MAIN-2014-15 | refinedweb | 124 | 66.84 |
This week there was a bug at work, and I learned something new about memory & swap & cgroups!
Understanding how memory usage works has been an ongoing project for a while – back in December, I wrote How much memory is my process using? which explains how memory works on Linux.
So I felt surprised and worried yesterday when something was happening with memory on Linux that I didn’t understand! Here’s the situation and why I was confused:
We had some machines running builds. They were swapping. They had say 30GB of RAM in total. 15GB was being used by some processes and 15GB by the filesystem cache. I was really confused about why these machines were swapping, because – I know about memory! If 15GB of memory is being used by the filesystem cache, the OS can always free that memory! There’s no reason to swap!
I then learned about the “swappiness” setting, and that if “swappiness”
is high, then the OS is more likely to swap, even if it doesn’t
absolutely need to. We tried setting
sysctl vm.swappiness=1, which
lets you tell the operating system “no, really, please don’t swap, just
take memory away from the filesystem cache instead”. The machine
continued to swap. I was confused.
After a while, we turned off swap and things got worse. Some processes started being OOM killed. (the OOM killer on Linux will kill processes if you run out of memory) But why? The boxes had free memory, didn’t they? In my head I had an axiom “if a computer has free memory, there is no reason the processes on it should get OOM killed”. Obviously there was something I did not understand.
I finally looked at the output of
dmesg (which is how you see messages the Linux
kernel prints about what it’s up to) to understand why the
processes were being OOM killed. And then there was this magic word:
cgroups. Everything became clear pretty quickly:
- the processes that were being killed were in a cgroup (which we talked about back in this namespaces & groups post)
- cgroups can have memory limits, which are like “you are only allowed to use 15GB of memory otherwise your processes will get killed by the OOM killer”
- and this memory limit was the reason the processes were being killed even though there was free memory!
swap + cgroup memory limits = a little surprising
My model of memory limits on cgroups was always “if you use more than X memory, you will get killed right away”. It turns out that that assumptions was wrong! If you use more than X memory, you can still use swap!
And apparently some kernels also support setting separate swap limits. So you could set your memory limit to X and your swap limit to 0, which would give you more predictable behavior. Swapping is weird and confusing.
Anyway, we found out through all this that the processes in question had recently started using much more memory for very understandable reasons, and rolled back that change, and everything made sense again.
And more importantly than everything making sense, the build system was happy again.
does swap even make sense?
It’s not completely clear to me under what circumstances having swap on a computer at all even makes sense. It seems like swap has some role on desktop computers.
I am not sure though if any of the servers we operate benefit by having swap enabled? This seems like it would be a good thing to understand.
Like I hear the advice “no, just always turn off swap, it will be better overall” a lot and maybe that is the right thing! I think the reason that swap is considered bad in production systems is that it has weird/unpredictable effects and predictability is good.
Somewhat relately, this swap insanity article looks really interesting.
understanding memory models is cool
I learned
- the vm.swappiness exists and you can use it to make a machine more or less likely to swap
- that when Linux OOM kills a process in a cgroup (“container”), it actually prints a bunch of very useful stuff about the memory usage of everything else in the cgroup at the time. I should remember to look at dmesg earlier on!
It’s really important to me to understand what’s happening on the computers that I work with – when something happens like “this computer is swapping and I don’t know WHY” it bothers me a lot.
Now if I ever see a process mysteriously swapping hopefully I will remember about memory limits! | https://jvns.ca/blog/2017/02/17/mystery-swap/ | CC-MAIN-2022-21 | refinedweb | 771 | 71.75 |
In my previous article on OpenID 2.0, I mentioned the new Attribute Exchange extension. To me this is one of the more interesting benefits of moving to OpenID 2.0, so it deserves a more in depth look.
As mentioned previously, the extension is a way of transferring information about the user between the OpenID provider and relying party.
Why use Attribute Exchange instead of FOAF or Microformats?
Before deciding to use OpenID for information exchange, it is worth looking at whether it is necessary at all.
There are existing solutions for transferring user data such as FOAF and the hCard microformat. As the relying party already has the user’s identity URL, it’d be trivial to discover a FOAF file or hCard content there. That said, there are some disadvantages to this method:
- Any information published in this way is available to everyone. This might be fine for some classes of information (your name, a picture, your favourite colour), but not for others (your email address, phone number or similar).
- The same information is provided to all parties. Perhaps you want to provide different email addresses to work related sites.
- The RP needs to make an additional request for the data. If we can provide the information as part of the OpenID authentication request, it will reduce the number of round trips that need to be made. In turn, this should reduce the amount of time it takes to log the user in.
Why use Attribute Exchange instead of the Simple Registration extension?
There already exists an OpenID extension for transferring user details to the RP, in the form of the Simple Registration extension. It has already been used in the field, and works with OpenID 1.1 too.
One big downside of SREG is that it only supports a limited number of attributes. If you need to transfer more attributes, you basically have two choices:
- use some other extension to transfer the remaining attributes
- make up some new attribute names to send with SREG and hope for the best.
The main problem with (2) is that there is no way to tell between your own extensions to SREG and someone else’s which will likely create interoperability problems if when an attribute name conflict occurs. So this solution is not a good idea outside of closed systems. This leaves (1), for which Attribute Exchange is a decent choice.
What can I do with Attribute Exchange?
There are two primary operations that can be performed with the extension:
- fetch some attribute values
- store some attribute values
Both operations are performed as part of an OpenID authentication request. Among other things, this allows:
- The OP to ask the user which requested attributes to send
- If the OP has not stored values for the requested attributes, it could get the user to enter them in and store them for next time.
- The OP could use a predefined policy to decide what to send the RP. One possibility would be to generate one-time email addresses specific to a particular RP.
- For store requests, the OP can ask the user to confirm that they want to store the attributes.
Fetching Attributes
An attribute fetch request is a normal authentication request with a few additional fields:
- openid.ax.mode: this needs to be set to “fetch_request”
- openid.ax.required: a comma separated list of attribute aliases that the RP needs (note that this does not guarantee that the OP will return those attributes).
- openid.ax.if_available: a comma separated list of attribute aliases that the RP would like returned if available.
- openid.ax.type.alias: for each requested attribute alias, the URI identifying the attribute type
- openid.ax.count.alias: the number of values the RP would like for the attribute.
- openid.ax.update_url: a URL to send updates to (will be discussed later).
The use of URIs to identify attributes makes it trivial to define new attributes without conflicting with other people (and as with XML namespaces, the attribute aliases are arbitrary). However, the extension is only useful if the OP and RP can agree on attribute types. To help with this, there is a collection of community defined attribute types at axschema.org.
As an example, imagine a web log that uses OpenID to authenticate comment posts. Rather than just printing the OpenID URL for the commenter, it could use attribute exchange to request their name, email, website and hackergotchi. The authentication request might contain the following additional fields:
openid.ns.ax= openid.ax.mode=fetch_request openid.ax.required=name,hackergotchi openid.ax.if_available=email,web openid.ax.type.name= openid.ax.type.email= openid.ax.type.hackergotchi= openid.ax.type.web=
In the successful authentication response, the following fields will be included (assuming the OP supports the extension):
- openid.ax.mode: must be “fetch_response”
- openid.ax.type.alias: specify the type URI for each attribute being returned.
- openid.ax.count.alias: the number of values being returned for the given attribute alias (defaults to 1).
- openid.ax.value.alias: the value for the given attribute alias, if no corresponding openid.ax.count.alias field was sent.
- openid.ax.value.alias.n: the nth value for the given attribute alias, if a corresponding openid.ax.count.alias field was sent. The first attribute value is sent with n = 1.
- openid.ax.update_url: to be discussed later.
For the web log example given above, the response might look like:
openid.ns.ax= openid.ax.mode=fetch_response openid.ax.type.name= openid.ax.type.email= openid.ax.type.hackergotchi= openid.ax.value.name=John Doe openid.ax.value.email=john@example.com openid.ax.count.hackergotchi=0
In this response, we can see the following:
- The user has provided their name and email
- They have not provided any information about their web site. Either the OP does not support the attribute or the user has declined to provide it.
- The use has explicitly stated that they have no hackergotchi (i.e. it is a zero-valued attribute).
Storing Attributes
Using the Attribute Exchange fetch request, it is possible to outsource management of pretty much all the user’s profile information to the OP. That said, the user will still need to update their profile data occasionally. Telling them to go to their OP to change things and then log in again is not particularly user friendly though.
Using the store request, the RP can let the user update their profile on site and then transfer the changes back to the OP. Like the fetch request, a store request is performed as part of an OpenID authentication request. The additional request fields are pretty much identical to a store response, except that openid.ax.mode is set to “store_request”.
In the positive authentication response, the RP can see whether the data was successfully stored by checking the openid.ax.mode response field. If the data was stored, then it will be set to “store_response_success”. If the data was not stored it will be set to “store_response_failure” and an error message may be found in openid.ax.error.
Asynchronous Attribute Updates
One downside of the Simple Registration extension is that it only transferred user details on login. This means that it is only possible to get updates to attribute values by asking the user to log in again. The Attribute Exchange extension provides a way to solve this problem in the form of the openid.ax.update_url request field.
When a “fetch_request” is issued with the openid.ax.update_url field set, a compliant OP will record the following:
- the claimed ID and local ID from the authentication request
- the list of requested attributes
- the update_url value (after verifying that it matches the openid.realm value of the authentication request).
The OP will then include openid.ax.update_url in the authentication response as an acknowledgement to the RP. When any of the given attributes are updated the OP will send an unsolicited positive authentication response to the given update URL. This will effectively be the same as the original authentication response (i.e. for the same claimed ID and local ID), but with new values for the changed attributes.
As there is no mention of unsolicited authentication responses in the main OpenID authentication specification, it is worth looking at what checking the RP should do. This includes:
- Is this OP still authoritative for the claimed ID? This is checked by performing discovery on the claimed ID and verifying that it results in the same server URL and local ID as given in the response.
- Did the message come from the OP? As with a standard response, there should be a signature for the fields. Since the OP does not know what association to use for the signature, a new private association will be used. By issuing a “check_authentication” request to the OP, the RP can verify that the message originated from the OP.
If these checks fail the RP should respond with a 404 HTTP error code, which tells the OP to stop sending updates. If the message is valid, the RP can update the user’s profile data.
Caveats
While the Attribute Exchange extension provides significant features above those provided by Simple Registration, but it still has its limitations:
- Any attribute values provided to the RP are self-asserted.
- Related to the above, there is no way for a third party to make assertions about attribute values.
For (1), the solution is to perform the same level of verification on the attribute value as if the user had entered it directly. So an OpenID enabled mailing list manager should verify the email address provided by attribute exchange before subscribing the user. In contrast, an OpenID enabled shop probably doesn’t need to do further verification of the user’s shipping address (since it is in the user’s best interest to provide correct information).
The exception to this rule is when there is some other trust relationship between the OP and RP. For instance, if the RP knows that the OP will only send an email address if it has first been validated, then it may decide to trust the email address without performing its own validation checks. This is most likely to be useful in closed systems that happen to be using OpenID for single sign-on.
4 thoughts on “OpenID Attribute Exchange”
Excellent explanation of AX, James. I’m quite curious to see how RP will try to use attribute storage down the road… I imagine there will need to be some best practices from the community as to what is and is not appropriate to push back to the OP to store. I can easily imagine an RP going crazy with it and basically treat the OP as its database. I would also be careful about limiting the scope of AX, particularly your first caveat — “Any attribute values provided to the RP are self-asserted.” I’ve been doing some work on bringing OpenID to college campuses, and initially I imagine that *none* of the attributes will be self-asserted unless the campus has alternate means for modifying the data… they will all come for the university’s enterprise data store. AX is just a format for carrying attributes on the wire… it says nothing about where the data came from. But I guess your point is that if there isn’t a pre-existing trust relationship, the attributes may as well be self-asserted because you simply don’t know.
James,
This is a great review of Attribute Exchange, thanks for taking the time to write it up! A few comments:
Re: unsolicited positive assertion
They are mentioned in the spec in a couple of places:
10. Responding to Authentication Requests
“Relying Parties SHOULD accept and verify assertions about Identifiers for which they have not requested authentication. OPs SHOULD use private associations for signing unsolicited positive assertions.”
11.2. Verifying Discovered Information
.”
(this clarification was added after draft12, so it’s only in SVN, not yet published)
Re: verified attributes
Attribute Exchange deals only with the transport of the attributes, not with their content, acquisition, source, trust. There’s a separate extension proposal that deals exactly with the trust issue for attributes:
OpenID Signed Assertions
A demonstrative implementation of this (using verification of emails as the example) is available at:
(retrieve a signed assertion saying that Sxip has verified your email address)
(present the signed assertion to an OpenID 2.0 RP using Attribute Exchange, which trusts Sxip with the verification process)
Johnny
I’m not sure that 404 is the most applicable HTTP status code to use here. 403 might be clearer.
Will: one thing to keep in mind is that some OPs may only have limited support for attribute exchange: they may support a set of well known attributes, but not arbitrary attributes. Furthermore, it is going to be a while before RPs can depend on the presence of this extension (outside of closed systems, that is).
Johnny: that looks pretty interesting. Including enough information in the value to perform verification does partially solve the problem. It pushes the need for a special RP ↔ OP trust relationship and changes it to an RP ↔ attribute signer trust relationship. It still isn’t clear how to handle these trust relationships on the open internet.
LionsPhil: the specification mentions the 404 status code. If you think 403 is better, consider joining the OpenID specs mailing list and suggesting the change. | https://blogs.gnome.org/jamesh/2007/11/26/openid-ax/ | CC-MAIN-2017-51 | refinedweb | 2,250 | 62.48 |
Create UML Class Diagrams from Code
To add C# classes from code to your UML class diagram in Visual Studio Ultimate, drag those classes or namespaces from Solution Explorer, dependency graphs, or Architecture Explorer to your UML class diagram.
Any classes on which they depend also appear in UML Model Explorer. See How the Models Represent Types.
You’ll need Visual Studio Ultimate for this.
To add classes from program code to a UML model
Open a C# project.
Add a UML class diagram to your solution:
On the Architecture menu, choose New Diagram. In the Add New Diagram dialog box, select UML Class Diagram. A modeling project will be created, if you don’t already have one.
Open Architecture Explorer:
On the Architecture menu, choose Windows, Architecture Explorer.
See Find code with Architecture Explorer.
Drag namespaces or types from Architecture Explorer to the UML class diagram surface.
To see a type, expand Class View in the first column of Architecture Explorer, and then expand a namespace in the next column. You’ll see the types in the third column.
You can also drag namespaces or types from dependency graphs. See Map dependencies across your code on dependency graphs. You can drag classes from Solution Explorer.
This feature might run more quickly after you install Windows Automation API 3.0.
To open the C# code associated with a UML class
Double-click a class shape, attribute, or operation on the UML class diagram.
The source code appears.
Types that you explicitly move onto the diagram are represented directly in the model and on the diagram.
Types on which these explicit types depend are represented as placeholders in the model. Their details are not represented, and nor are their dependencies.
However, if you subsequently drag a placeholder type from Architecture Explorer or dependency graphs onto the diagram, the placeholder will be replaced by a full type. | http://msdn.microsoft.com/en-us/library/ff657806.aspx | CC-MAIN-2014-52 | refinedweb | 315 | 57.77 |
Originally posted by A Alqtn: Here is an example: public class A { private int bonus; public boolean setBonus(int bonus) { if( bonus > 0 ) { this.bonus = bonus; return true; } return false; } } public class B { public static void main(String [ ] args) { A a = new A(); int bonus = read from the user the bonus value; if( a.setBonus( bonus ) == false ) System.out.println("invalid bonus value); } }
if( a.setBonus( bonus ) == false )
System.out.println("invalid bonus value);
}
Originally posted by Michael Duffy:
public class A
{
private int bonus;
/**
* Write access to the bonus value
* @param bonus new value
* @throws IllegalArgumentException if the input value is negative
* (Where I can I get an employement application? I want to work there.)
*/
public void setBonus(int bonus)
{
if (bonus < 0)
throw new IllegalArgumentException("bonus values cannot be negative");
this.bonus = bonus;
}
}
Now clients don't have to check a value to see if the set succeeds, and they'll be told if the operation fails. Exceptions can be expensive, and there's an argument that says they shouldn't be used for normal program flow. But you've documented the proper use of your class in javadocs, so any user who wants to use your class will be fully-informed as to its proper use. I think it's a better alternative.
Originally posted by Layne Lund: IllegalArgumentException is a runtime exception. Generally, runtime exceptions indicate a programmer error and not a system error. This means that such an exception should NOT occur in a production environment. Persumably, the exception is thrown to facilitate testing so that such programming errors can be easily found and fixed. I think in most cases this would be an acceptable solution as long as the whole system is thoroughly tested to ensure that such exceptions are not thrown after the program has been distributed for production. I also agree with Ilja that the way to handle this type of situation might not be entirely universal and depends on the exact situation. Don't get stuck into one solution so much that you are not flexible enough to modify it when there are reasons to do so. Layne
Originally posted by A Alqtn: Layne, When reading a value from a text field, a runtime error might happen and it is not a programmer error. Such a exception can happen a production environment. What I mean is that not all run time errors represent progrmmaer error. Alqtn
Originally posted by Mike Noel: A slightly more complex example would be where the bonus has to be >= 0 and <= 10% of another field, (maybe "gross"). Now the client has to know a bit of the business logic that the class is implementing. You can imagine even more complicated cases. Following the "check for validity first" path can mean that the client ends up replicating a lot of the class's own logic. IMHO this defeats the purpose of setters.
I suggest that the class provide a method that can test for valid values or throw an exception. Making a checked exception seems like a reasonable idea for a class that's a bit complex. The client can wrap all the setter calls in a single try block and create appropriate catch code to deal with invalid input.
Originally posted by Ilja Preuss: I think there are better solutions to this, such as the Builder pattern, or a Collecting Parameter. Code doesn't *have* to be complex, it's always a choice we make. | http://www.coderanch.com/t/401920/java/java/Setters | CC-MAIN-2015-35 | refinedweb | 579 | 62.38 |
Example Vapor Provider
Great web frameworks make it simple to develop third party plugins that can be easily added to any project.
The Vapor Swift web framework is no exception and allows
developers to create and share plugins called
Providers
This example demonstrates how to create a
Vapor Provider with functionality
that would be required by real Providers, such as Admin backends, Debug toolbars
and Job Queue management, including:
- Default configuration with optional overrides using
json
- Example Route that returns a view using the Leaf Swift templating language.
- Example Middleware.
The purpose of this repo is simply is to provide some guidance on how to build Providers that extend Vapor's core functionality.
Adding the Example Provider
To add this example provider to a Vapor project include it as a dependency in
your
Packages.swift file.
let package = Package( name: "MyApp", dependencies: [ .Package(url: "", majorVersion: 1), .Package(url: "", majorVersion: 1), ] )
Then enable the provider in
main.swift:
import Vapor import VaporDemoProvider let drop = Droplet(providers: [ VaporDemoProvider.Provider.self ] ) drop.run()
Then run
vapor build && vapor run and visit to
see the providers welcome page.
Configuration Example
This provider includes a basic view that is available at
/_demo.
This route can be overridden by simply adding a
demo_provider.json file in the
Config folder of a Vapor project, which contains a
path key, as follows:
{ "path": "/mypath", }
Then run
vapor build && vapor run and visit to
see the HTML page.
Middleware Example
This demo provider also includes middleware that simply adds a header
DemoProvider: Installed to all responses.
Currently it does not seem possible for a provider to enable middleware automatically - you must do this manually.
//Other config let drop = Droplet( availableMiddleware: [ "demoprovider" : VaporDemoProvider.Middleware() ], providers: [ VaporDemoProvider.Provider.self ] ) drop.run()
Then enable the middleware in your
Config/middleware.json file:
{ "server": [ ... "demoprovider" ], ... }
Then run
vapor build && vapor run.
Thoughts
While building this demo, a few things came to mind that could help make it easier for the community to build Providers.
- The Vapor toolkit could be extended to allow the creation of skeletons, for example
vapor generate provider
- Currently middleware can only be initialized in the
Dropletand is a
letconstant. This means that third party middleware cannot be added when the providers are initialized. It would be nice to be able to do something like
drop.middleware.append(["demoprovider" : DemoProvider.Middleware()])
- Many third party packages in popular frameworks include routes and views. I may have missed something, but the only way I can see how a Provider can (easily) return views is to copy the Provider views into the
drop.resourcesDir. Perhaps Providers could have a default resource dir of their own, which could be overridden on
initto allow custom templates to be used in there place?
Next Steps
Creating a Vapor Provider is pretty straightforward and the core team deserves kudos for making this so simple at this early stage in the framework's development.
Now, let's build a vibrant Vapor community by crafting some truly useful Providers.
Get Forking!
Github
Help us keep the lights on
Dependencies
Used By
Total: 0 | http://swiftpack.co/package/mpclarkson/vapor-demo-provider | CC-MAIN-2018-39 | refinedweb | 514 | 54.32 |
Hello im kinda new with C++ and im trying to have a program that reads in a keyboard press while the programs continues to run. i seem to have that part of it ok but im trying to create a string with each new key pressed but i get a error that i cant seem to get around. Any help would be good
Code:#include <iostream> #include <conio.h> #include <ctype.h> //please do not worrry about all these headers #include <cstring> // i have been trying different commands #include <stdio.h> using namespace std; int main(void) { char string[256]; int kb; while(kb!= 27) { if (_kbhit()) { kb =_getch(); _putch(kb); if (kb != 13) { string[0] = '\0'; char c = char(kb); strcat(string, c); // problem is here. i get a error which is //" cannot convert parameter 2 from 'char' to 'const char *'" } } } } | https://cboard.cprogramming.com/cplusplus-programming/124032-problem-strcat.html | CC-MAIN-2017-09 | refinedweb | 142 | 82.04 |
--
mats
Printable View
1. How would the statement ...1. How would the statement ...Code:
#include "FleetMenu.h"
// Class MenuContext
class MenuContext
{
public:
bool fquit;
FleetMenu *menuPtr;
MenuContext() : fquit(false) {}
~MenuContext() {};
};
... outside menucontext say in FleetMenu.cpp initialize the member (menuPtr) of menucontex? Besides, why can't i just do this inside menucontext as i declare is, by this i won't have to worry every time i use it.... outside menucontext say in FleetMenu.cpp initialize the member (menuPtr) of menucontex? Besides, why can't i just do this inside menucontext as i declare is, by this i won't have to worry every time i use it.Code:
FleetMenu *menuPtr = new FleetMenu();
2. I get an error when i compile the above because: FleetMenu.h includes Menu.h which includes MenuContext.h... So i'm including FleetItem in MenuContext but FleetMenu which also includes MenuContext.h through Menu.h....
3. Since menucontext is passed to all my Menu functions, can't i just do the following in each of the function ...
then i don; have to worry about the first question?then i don; have to worry about the first question?Code:
function(MenuContext &ctxt)
{
ctxt.menuPtr = new FleetMenu();
}
Right, you should only ever have ONE FleetMenu object [at least, I don't see any reason to have more]. So 3 is the wrong solution, as you would create a new FleetMenu object for each menu.
So, if you useThen you would want to pass menuPtr to the MenuContext constructor and store a copy of the pointer in the MenuContext object being constructed.Then you would want to pass menuPtr to the MenuContext constructor and store a copy of the pointer in the MenuContext object being constructed.Code:
FleetMenu *menuPtr = new FleetMenu();
There are other ways to do this, particularly the SingleTon pattern may be a good fit here.
--
Mats
Alright, here's an example of singleton
Q.Q.Code:
class Singleton
{
public:
static Singleton* Instance();
protected:
Singleton();
Singleton(const Singleton&);
Singleton& operator= (const Singleton&);
private:
static Singleton* pinstance;
};
1. Is this your idea of singleton
2. Should this Class be MenuContext or FleetMenu?, if it's MenuContex, how does FleetMenu object fit in since the example itself has an object of its own class?
It depends. There is only ever need for ONE FleetMenu object and only one MenuContext object, so technically both of those can be singletons.
I'm a little bit confused about the purpose of the FleetMenu. It makes sense to have a collection of functions within a class. But I don't quite see why it should hold data or have functions that take parameters inside it. Those probably belong somewhere else (and possibly not all in the same place).
Note that no one said that object oriented design is easy, and what goes in which object is definitely not easy to decide, and the decision is often arbitrary, a compromise and/or subject to personal preferences.
--
Mats
1. View the list of available cars
2. Sort the list
3. Search for a specific car in a database
4. Delete car from the database
5. Add new car in a database
Well, i'm thinking i should take most of these operation to class Car since they all deal with car... What do you think?
By the way, item 2 seems like something that should be done [temporarily?] during the listing [and possibly with different sorting criteria]. Or perhaps you want to use a sorting type of container class (e.g a binary tree structure).
--
Mats
However, since a short can be different sizes depending on compiler and platform, it's better and more common to use integer traits such as boost to specify the maximum size the short can hold and pass it to the function.
Boost is very popular in other areas, as well. It provides implementations of smart pointers such as shared_ptr and weak_ptr (both part of TR1). Also provides a static array in C++ style (boost::array), also part of TR1.
Boost contains lots and lots of meta programming help, such as boost::mpl::if(_c).
It also provides common operators such as implementing operator + simply deriving from boost::addable (there are more operators). It can also make a class non-copyable by deriving from another class.
It contains common libraries for file system, threads, and more. It also contains regular expressions, very powerful lambda expressions and function binders.
A lot of this is above your current knowledge, but I would advise you check the boost site for a detailed explanation of the boost libraries and what they all can do. | http://cboard.cprogramming.com/cplusplus-programming/104968-please-check-my-cplusplus-18-print.html | CC-MAIN-2014-42 | refinedweb | 771 | 66.94 |
In this tutorial, we will check how to setup a socket server on the ESP32 and how to contact it using Putty as a socket client. The code will be implemented on the Arduino core for the ESP32.
Note that we have already covered in greater detail how to set up a socket server on the ESP32 on this previous post. Nonetheless, we had to implement a Python socket client to reach the server and thus test the code.
Although Python is a very easy to use language, using Putty is even easier and doesn’t need any kind of programming to implement the client, allowing us to focus on the ESP32 code.
Among st many other features, Putty allows us to establish a raw socket connection to a server, making it a very useful tool for testing. Putty is a free and open source tool and you can download it here.
The tests were performed using a DFRobot’s ESP32 module integrated in a ESP32 development board.
To get started, we need to include the WiFi.h library, so we can connect the ESP32 to a Wireless network. We will also need to store the network credentials (network name and password), so we can connect to it.
#include "WiFi.h" const char* ssid = "yourNetworkName"; const char* password = "yourNetworkPassword";
In order to setup the server, we will need an object of class WiFiServer, which we will store in a global variable so we can use it on the Arduino setup and loop functions.
As we have seen in previous posts, the constructor of this class receives the port where the server will be listening. I will be using port 80, but you can test with other values.
WiFiServer wifiServer(80);
Moving on to the setup function, we will start by opening a serial connection so we can later output the results of our program. Followed by that, we will connect the ESP32 to the WiFi network to which we have previously declared the credentials.
At the end of the setup function and after the WiFi connection procedure is finished, we will call the begin method on our WiFiServer object so the server starts listening to incoming socket clients.
You can check the full setup function code below, which already includes the mentioned connection to the WiFi network and the call to the begin method to start the socket server.
void setup() { Serial.begin(115200); delay(1000); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi.."); } Serial.println("Connected to the WiFi network"); Serial.println(WiFi.localIP()); wifiServer.begin(); }
We will handle the connection of clients and the reception of data on the Arduino main loop function.
The first thing we need to do is calling the available method on our WiFiServer object. This method takes no arguments and returns as output an object of class WiFiClient.
Note that by default this is a non-blocking method, which means it will return an instance of the WiFiClient class even if there is no client connected.
Thus, we need to check if the client is indeed connected, either by calling the connected method on the returned object and checking its value or directly using the returned object on a IF condition. This second option is only possible because the WiFiClient class overrides the C++ bool operator to return the same value as the connected method.
WiFiClient client = wifiServer.available(); if (client) { // Code for handling the client }
Inside the IF block we need to handle the reception of data sent from the client. Nonetheless, we will only try to get data while the client is connected and we need to detect when the client is no longer detected. So, we will do a inner loop that will keep running only while the client is connected.
To check if the client is connected, we simply need to call the connected method on the WiFiClient object, as already mentioned before. The return of this function can be used as the stopping condition of the while loop.
while (client.connected()) { // Data received handling code }
Now, inside that loop, to check if the client sent data, we call the available method on the WiFiClient object.
This method takes no arguments and returns as output the number of bytes available for reading. This is also a non-blocking method which will return 0 if there is no data to read.
So we need to check if the returned value is greater than zero and if it is, we can get a byte by calling the read method on the WiFiClient object. Note that since the client may send more that 1 byte at each time, we can optimize this polling by doing a loop and keep reading bytes while the available method returns an output greater than 0.
We will print each byte read to the serial port, so we can confirm that the data sent by the client is reaching the ESP32.
When there are no more bytes to read, we do a small delay and we go back to the beginning of the outer loop to check for more data.
while (client.connected()) { while (client.available()>0) { char c = client.read(); Serial.write(c); } delay(10); }
Once we detect that the client has disconnected, then we no longer try to read more bytes and we simply call the stop method on the WiFiClient object, in order to free all the resources from that connection.
The final source code can be seen below.
(); Serial.write(c); } delay(10); } client.stop(); Serial.println("Client disconnected"); } }
To test the code, we first need to compile it and upload it to the ESP32 using the Arduino IDE. Once the procedure finishes, simply open the IDE serial monitor.
As shown in figure 1, it should print the IP assigned to the ESP32 as soon as the connection to the WiFi network finishes. Copy that IP, since we are going to need to use it on Putty.
Figure 1 – IP address assigned to the ESP32 on the WiFi network.
Next, after downloading Putty, simply open it. You should get a window similar to the one shown in figure 2. As highlighted, you should set the connection type as “Raw” and then, on the “Host Name (or IP address)” text input, you should put the IP copied from the serial monitor.
On the “Port” text input you should put the value 80, which was the number of the port we defined for our server to be listening on. Once all the configurations are done, click on the “Open” button.
Figure 2 – Configuring Putty as a socket client.
After that a command line should appear. There, you can type content and send it to the ESP32. If you go back to the Arduino IDE serial monitor, the content sent with Putty should get printed, as shown in figure 3.
Figure 3 – Printing the content sent from Putty.
If you close the Putty command window, then the socket connection should be stopped and the event detected in the ESP32, as shown in figure 4.
Figure 4 – Socket client disconnected. | https://www.dfrobot.com/blog-995.html | CC-MAIN-2020-29 | refinedweb | 1,190 | 70.43 |
Copyright © 2002 W3C® (MIT, INRIA, Keio), All Rights Reserved. W3C liability, trademark, document use, and software licensing rules apply.
SOAP Version 1.2 is a lightweight protocol intended for exchange of structured information in a decentralized, distributed environment. Part 2: Adjuncts defines a set of adjuncts that may be used with Part1: SOAP Messaging Framework. This specification depends on SOAP Version 1.2 Part 1: Messaging Framework fourth Computing the Type Name property
3.1.4.1 itemType Attribute Information Item
3.1.5 Unique identifiers
3.1.5.1 id Attribute Information Item
3.1.5.2 ref Attribute Information Item
3.1.5.3 Constraints on id and ref attribute information items
3.1.6 arraySize Attribute Information Item
3.2 Decoding Faults
4. SOAP RPC Representation
4.1 RPC and SOAP Body
4.2 RPC and SOAP Header
4.3 RPC Faults
5. A Convention for Describing Features and Bindings
5.1 Model and Properties
5.1.1 Properties
5.1.2 Property Scope
5.1.3 Properties and Features
6. SOAP-Supplied Message Exchange Patterns
6.1 Property Conventions for MEPs
6.2 Single-Request-Response MEP
6.2.1 Message Exchange Pattern Name
6.2.2 Informal Description
6.2.3 Formal Description
6.2.4 Fault Handling
7. SOAP HTTP Binding
7.1 Introduction
7.2 Binding Name
7.3 Supported Message Exchange Patterns
7.4 Single-Request-Reponse Message Exchange Operation
7.4.1 Behaviour of Requesting SOAP Node
7.4.1.1 Requesting
7.4.1.2 Waiting
7.4.1.3 Receiving
7.4.1.4 Success and Fail
7.4.2 Behaviour of Responding SOAP Node
7.4.2.1 Receiving
7.4.2.2 Processing
7.4.2.3 Responding
7.4.2.4 Success and Fail
7.5 Features Expressed External to the Message Envelope
7.5.1 SOAP Action
7.6 Security Considerations
8. References
8.1 Normative References
8.2 Informative References
A. Mapping Application Defined
Names to XML Names
A.1 Rules for mapping application defined names to XML Names (SOAP) is a lightweight protocol intended for exchange of structured information between peers in a decentralized, distributed environment. The SOAP specification consists of two parts. Part 1 [1] defines the SOAP messaging framework. Part 2 (this document) defines a set of adjuncts that MAY be used with the SOAP messaging framework:
The SOAP Data Model represents application-defined data as a directed, edge-labeled graph of nodes (see 2. The SOAP Data Model).
The SOAP Encoding defines a set of rules for encoding instances of data that conform to the SOAP Data Model for inclusion in SOAP messages (see 3. SOAP Encoding).
The SOAP RPC Representation defines a convention for how to use the SOAP Data Model for representing RPC calls and responses (see 4. SOAP RPC Representation).
A convention for describing features and bindings (see 5. A Convention for Describing Features and Bindings).
A request response message exchange pattern definition (see 6. SOAP-Supplied Message Exchange Patterns).
The SOAP HTTP Binding defines a binding of SOAP to HTTP [2] following the rules of the SOAP Protocol Binding Framework (see 7. SOAP HTTP Binding).
Note:
In previous versions of this specification the SOAP name was an acronym. This is no longer the case.
The keywords "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC2119 [3].
As a convention, the namespace prefixes "env" and "enc" used in the prose sections of this document are associated with the SOAP namespace names "" and "" respectively.
The namespace name "" is defined by Part 1 [1]. A normative XML Schema [4], [5] document for the "" namespace can be found at.
As an additional convention, the namespace prefixes "xs" and "xsi" used in the prose sections of this document are associated with the namespace names "" and "" respectively, both of which are defined in the W3C XML Schema specification [4], [5].
Note that for all the namespace conventions listed above, the choice of any namespace prefix is arbitrary and not semantically significant (see [10]).
Namespace names of the general form "..." and "..." represent application or context-dependent URIs [6].
This specification uses the Extended Backus-Naur Form (EBNF) as described in [8].
With the exception of examples and sections explicitly marked as "Non-Normative", all parts of this specification are normative..
An edge in the graph is said to originate at a graph node and terminate at a graph node. An edge that originates at a graph node is known as an outbound edge with respect to that graph node. An edge that terminates at a graph node is known as an inbound edge with respect to that graph node. An edge MAY originate and terminate at the same graph node.
The outbound edges of a given graph node MAY be distinguished by label or by position, or both. Position is a total order on such edges; thus any outbound edge MAY be identified by postiion. An edge label is an XML e Schema Qualified Name (QName) ( see XML Schema Part 2: Datatypes [5] ). Two edge labels are equal if and only if both of the following are true:
Their local name values are the same.
Either of the following is true:
Their namespace name values are missing.
Their namespace name values are present and the same
A graph node is either a terminal or a non-terminal. A non-terminal graph node has zero or more outbound edges. A terminal graph node has a lexical value and no outbound edges. Both types of graph node have an optional unique identifier ( of type ID in the namespace named "", ( see XML Schema Part2: DataTypes [5] )) and an optional type name ( of type QName in the namespace named "" ( see XML Schema Part2: DataTypes [5] )).
A simple value is represented as a terminal graph node.
A compound value is represented as a non-terminal graph node as follows:
If the labels of a non-terminal graph node's outbound edges are not unique ( i.e. they can be duplicated ), the non-terminal graph node is known as a "generic". Outbound edges of a generic MAY be distinguished by label and/or position, according to the needs of the application.
A non-terminal graph node whose outbound edges are distinguished solely by their labels is known as a "struct". The outbound edges of a struct MUST be labeled with distinct names ( see 2.1.1 Edge labels ).
A non-terminal graph node whose outbound edges are distinguished solely by position is known as an "array". The outbound edges of an array MUST NOT be labelled.).
The serialization rules defined in this section are identified
by the URI "". SOAP messages
using this particular serialization SHOULD indicate this using the
SOAP
encodingStyle attribute information item (see SOAP Encoding
Attribute).. SOAP RPC Representation.
To describe the graph node at which an edge terminates is determined as follows:
If the element information item representing the edge
does not have a
ref attribute information
item (see 3.1.5.2 ref Attribute
Information Item) amongst its attributes then that
element information item is said to represent a
node in the graph and the edge terminates at that node.
If the element information item representing the edge
does have a
ref attribute information item
(see 3.1.5.2 ref Attribute Information
Item), then the value of that attribute information
item MUST be identical to the value of exactly one
id attribute information item ( see 3.1.5.1 id Attribute Information Item ) in the
same envelope. In this case the edge terminates at the graph node
represented by the element information item on which the
id attribute information item appears. That
element information item MUST be in the scope of an
encodingStyle attribute with a value of
"".
All nodes in the graph are encoded as described in 1 above. Additional inbound edges for multi reference graph nodes are encoded as described in 2 above.
The "lexical value" of a terminal graph node is the sequence of Unicode characters identified by the character information item children of the element information item representing that node.
An outbound edge of a graph node is encoded as an element information item child of the element information item that represents the node (see 3.1.1 Encoding graph edges and nodes). Particular rules apply depending on what kind of compound value, "generic", "struct" or "array", the graph Names to XML Names).
If the edge label is globally scoped, the non-URI part of the edge label is the local name. (see A. Mapping Application Defined Names to XML Names)..attribute information item.
The type name property of a graph node is a {namespace name, local name} pair in the namespace named "" ( see XML Schema Part 2: Datatypes [5] ); graph to describe named
"". The value of the
itemType attribute information item is used
to compute the type name property (see 3.1.4 Computing the Type Name property)
of members of an array.
The
id attribute information item has the
following Infoset properties:
A local name of
id ;
A namespace name which is empty
A specified property with a value of "true".
The type of the
id attribute information
item is ID in the namespace named
"". The value of the
id attribute information item is a unique
identifier that can be refered to by a
ref
attribute information item (see 3.1.5 named
"". The value of the
ref attribute information item is a reference
to a unique identifier defined by an
id attribute
information item (see 3.1.5.1 id
Attribute Information Item).
The value of a
ref attribute information
item MUST also be the value of exactly one
id
attribute information item.
A
ref attribute information item and an
id attribute information item MUST NOT appear
on the same element information item.
The
arraySize attribute information item
has the following Infoset properties:
A local name of
arraySize ;
A namespace name of "".
A default value of "*"
The type of the
arraySize attribute information
item is arraySize in the namespace named
""..5.3 Constraints on id and ref
attribute information items).
MAY generate an
env:Sender SOAP fault with a
subcode of
enc:UntypedValue if the type name property
of an encoded graph node is unspecified..
The encoding specified must support the "struct" and/or "array
compound" value constructions from the SOAP data model 2. The SOAP Data Model.
Use of the SOAP RPC Representation is orthogonal to the SOAP protocol binding. In the case of using HTTP as the protocol binding, an RPC invocation maps naturally to an HTTP request and an RPC response maps to an HTTP response. However, use of the SOAP RPC Representation is not limited to the SOAP HTTP Binding (see 7. SOAP HTTP Binding).
To invoke an RPC, the following information is needed:
The binding-specific address of the target SOAP node
A procedure or method name
The identities (which may be either positional or by name) and values of any arguments to be passed]
section SOAP Body) using
the following representation:
An RPC invocation is modeled as a struct where parameter access is by name or as an array where parameter access is by position.
The invocation is represented by a single struct or array containing an outbound edge for each [in] or [in/out] parameter. The struct is named identically to the procedure or method name (see A. Mapping Application Defined Names to XML Names).
Each outbound edge either has a label corresponding to the name of the parameter (see A. Mapping Application Defined Names to XML Names) or a position corresponding to the position of the parameter.
An RPC response is modeled as a struct where parameter access is by name or as an array where parameter access is by position.
The response is represented by a single struct or array containing an outbound edge for the return value and each [out] or [in/out] parameter. The return value outbound edge SHOULD be the first outbound edge.
Each outbound edge has a label corresponding to the name of the parameter (see A. Mapping Application Defined Names to XML Names) or a position corresponding to the position of the parameter. The label of the return value outbound edge is "result" and it is namespace-qualified with the namespace name "".. a SOAP envelope carrying an RPC invocation or response. Such additional information MUST be expressed as SOAP header blocks.
The SOAP RPC Representation introduces additional SOAP fault
subcode values to be used in conjunction with the fault codes
described in [1] section Fault Codes. The namespace name):
A fault with a
value of "env:Receiver" for
faultcode SHOULD be generated when the receiver cannot
handle the message because of some temporary condition, e.g. when
it is out of memory.
A fault with a
value of "env:DataEncodingUnknown"
for
faultcode SHOULD be generated when the arguments
are encoded in a data encoding unknown to the receiver.
A fault with a
value of "env:Sender" for
faultcode and a
value of
"rpc:ProcedureNotPresent" for
subcode MUST be
generated when the receiver does not support the procedure or
method specified.
A fault with a
value of "env:Sender" for
faultcode and a
value of
"rpc:BadArguments" for
subcode MUST be generated when
the receiver cannot parse the arguments or when there is a mismatch
between what the receiver expects and what the sender has sent.
Other faults arising in an extension or from the application SHOULD be generated as described in Part 1 [1] section SOAP Faults.
In all cases the values of the
detail and
faultstring element information items are
implementation defined. Details of their use.2 Single-Request-Response MEP and the SOAP HTTP Binding 7. SOAP. by the Responding SOAP node while it is in the Processing state, the generated SOAP fault replaces the abstraction of the Response Message that is used to set the "context:CurrentMessage" property and the state machine transitions to the Responding state.
This MEP specification makes no claims as to the disposition or handling of SOAP faults generated by the Requesting SOAP node during the processing of the Response Message that follows the Success state in the Requesting SOAP node's state transition table.
The SOAP HTTP Binding presented here provides a binding of SOAP to HTTP. This binding conforms to the SOAP Binding Framework (see [1]SOAP Protocol Binding Framework) and uses abstract properties as a descriptive tool for defining the functionality of certain features.
The SOAP Protocol Binding Framework (see [1]SOAP Protocol Binding Framework), Message Exchange Pattern Specifications (see ) and Feature Specifications (see 5. A Convention for Describing Features and Bindings) each describe the properties they expect to be present in a message exchange context when control of that context passes between the local SOAP Node and a binding instance.
Properties are named with XML qualified names (QNames). Property values are determined by the Schema type of the property, as defined in the specification which introduces the property. The following table lists the XML namespace prefix mappings that are used throughout this specification:
HTTP applications MUST use the media type "application/soap+xml" according to [12] when including SOAP 1.2 messages in HTTP exchanges. See [12] for parameters defined by this media type and their recommended use.
Note:
Use of the SOAP HTTP Binding is optional; nothing precludes the specification of different bindings to other protocols or other bindings to HTTP. Because of the optionality of using the SOAP HTTP Binding, it is NOT a requirement to implement it as part of a SOAP node. A node that does correctly and completely implement the HTTP binding may to be said to "conform to the SOAP 1.2 HTTP binding."
The binding described here is identified with the URI:
""
An implementation of the SOAP HTTP Binding MUST support the following message exchange pattern:
"" (see 6.2 Single-Request-Response MEP)
The "" message exchange pattern is described in 6.2 Single-Request-Response MEP.
For binding instances conforming to this specification:
A SOAP Node instantiated at an HTTP client may assume the role
(i.e. the property
single:Role ) of
RequestingSOAPNode .
A SOAP Node instantiated at an HTTP server may assume the role
(ie. the property
single:Role ) of
RespondingSOAPNode .
The remainder of this section describes the MEP state machine
and its particular relation to the HTTP protocol. In the state
tables below, the states are defined as values for the property
single:State (see 6.2
Single-Request-Response MEP), and are of type
single:StateType (an enumeration over
xs 6.2 Single-Request-Response MEP. The following subsections describe each state in more detail..2 Single-Request-Response MEP. The following subsections describe each state in detail.
This underlying protocol Receiver:
The SOAP HTTP Binding (see 7. SOAP HTTP Binding) can be considered as an extension of the HTTP application protocol. As such, all of the security considerations identified and described in section 15 of the HTTP specification[2] apply to the SOAP HTTP Binding in addition to those described in Part 1 [1] "Security Considerations". Implementers of the SOAP HTTP Binding should carefully review this material.U2 ... U8 in the UCS-4 encoding.
Case:
If U1=0, U2=0, U3=0, and U4=0, then let Xi="_x"U5U6 U7U8"_".
This case implies that Ti has a UCS-2 encoding, which is U+U5U6U7 U8.
Otherwise, let Xi be "_x"U1U2U3 U4U5U6 U7U]
As noted in 3.1 [4]),:Header> <t:Transaction xmlns:="true" >. | http://www.w3.org/2000/xp/Group/2/04/11/soap12-part2-1.55.html | CC-MAIN-2014-10 | refinedweb | 2,931 | 57.57 |
This forum is no longer active. Please post your questions to our new community site
4 post(s),
2 voice(s)
Hi,
I just downloaded the BitNami installer for windows and succesfully completed it. However, I already had python 2.7 installed and if I run the command line
import django
from my existing python install I get
ImportError:No module named django
I looked in
C:\Program Files\BitNami DjangoStack
and it looks like BitNami installed python again within its own directory, but it installed version 2.6. Couple questions:
1. Why did it install version 2.6?
2. Should I just delete my existing install and use the one created by BitNami?
Thanks.
BitNami Stacks are self-contained so it includes their own Python files. Are you running the command from the use_djangostack from the Start Menu shortcuts?
Yes, thanks. I figured out the correct command prompt.
I am still curious why BitNami ships with python 2.6 rather than 2.7
We will update Python in the future. It is in our TODO list. | https://bitnami.com/forums/forums/djangostack/topics/confused-by-install-procedure | CC-MAIN-2016-22 | refinedweb | 177 | 67.86 |
Do’s and Don’ts of Analyzing Time Series
When handling time series data in your Data Science analysis work, a variety of common mistakes are made that are basic, but very important, to the processing of this type of data. Here, we review these issues and recommend the best practices.
Photo by Nathan Dumlao on Unsplash.
The examples in this article use the Starbucks data stock market dataset, available to download here.
Helpful Techniques in Analyzing Time-Series Data
1 . Visualizing Time Series and Data Exploration
- Line Graph
Line plots are some of the most simple and basic types of plots, which can show the change of a feature over time.
In Pandas, we can do it as follows.
df['Close'].plot(color='blue', figsize=(12,8))
Here, we can see that the closing value of the stocks of Starbucks is increasing over time. We can see some ups and downs in it, but generally, the company is performing well.
Now, we can observe from the plot that the closing value is decreasing from 2018 January to 2018 July. We can have a closer look as follows.
df['Close']['2018-01':'2018-09'].plot( figsize=(12,8), marker='o') plt.ylabel('Closing Value')
Here, we can see that stocks were around 60 in 2018–01 but reduced to 48 in 2018–07. The good news is that company managed to raise itself some months back to near 60.
- Histograms
Histograms are a good way to tell how often each different value in a set of data occurs.
Here, in our case, we can check that what is the most occurred value of our stock via
df['Close'].plot.hist(figsize=(15,8), bins=20, edgecolor='black')
And here, we can see that the closing value of our stock is mostly at 53–58.
2. Decomposition of Time Series
We can decompose our Time Series into 4 parts. These are
- Level:The measure of Average of the value in the time series.
- Trend: The general trend in your time series, which tells increasing or decreasing value in the series.
- Seasonality: Characteristic of a time series in which the data experiences regular and predictable changes that recur every calendar year.
- Noise: The random variation in the series.
Trend
Finding trends in your time series can give you a lot of awareness about your data, and it can help you know that the value at any certain point is above the trend or below the trend.
You can find the trend via some methods, such as ETS Decomposition. Now to understand more and in-depth about ETS Decomposition and how it works, you need to refer to some book or a teacher as it involves some maths and stats to understand how it works.
But the good news is that you can easily do it in Python using statsmodel library.
from statsmodels.tsa.seasonal import seasonal_decompose
Now, if you can see that your feature is increasing or decreasing at a non-linear rate, by line plotting it, we have to use a multiplicative model. Otherwise, if the feature is increasing or decreasing by a linear rate, then you have to use the additive model.
For example, in this case, we can see that our trend is non-linear and almost exponential for the number of passengers on flights, so we have to use the multiplicative model.
We can then find the trend for the number of passengers via the following code.
result = seasonal_decompose(df[‘Thousands of Passengers’], model=’multiplicative’)
Here, we have to pass the column name for which we want to find the trend. We can then observe the trend by calling the plot function on trend the attribute, which is basically a Pandas Series.
Now the returning value result consists of 4 components. Those are Residual, Seasonal, Trend, and Observed.
You can check the values for each component by calling them from result,
i.e.,
result.trend
And to plot it, you can simply call plot function over this series.
result.trend.plot()
To plot all of these, we can simply call plot function the result.
result.plot()
If we want to see the trend of a specific period, let’s say from 1955 to 1999, we can do it by,
result.trend['1955':'1959'].plot(figsize=(12,5))
If we want to compare the value of Passengers with the current trend, we can do it by plotting the value for the column and the trend in the same figure.
result.trend['1955':'1959'].plot(figsize=(12,5), label='Trend') df['Thousands of Passengers']['1955':'1959'].plot(label='Thousands of Passengers') plt.legend()
Here we can see that from 1955 to 1960, at specific intervals, the number of passengers drop(maybe during Work months) and increase(summer vacations maybe).
Seasonality
The seasonality component explains the periodic ups and downs in a time series.
Image Credits: Towards Data Science.
A time series can contain multiple seasonal periods or one single seasonal periods depending upon the nature and quality of the dataset.
As we have already found the result component from ETA decomposition, it comes with Seasonality component, and we can plot it via
result.seasonal.plot()
This can show us the periodic pattern repeating in the dataset.
Noise
Residual is composed of 2 parts: Noise and Error.
Noise is that part of the residual, which is in-feasible to model by any other means than a purely statistical description. Note that such modeling limitations which arise due to limitations of the measurement device (e.g., finite bandwidth & resolution).
We can reduce residual by either reducing noise or by reducing error.
As discussed earlier, it is the part of result and we can achieve it via
result.resid
and plot it via
result.resid.plot()
Mistakes to Avoid
1. Ignoring The Timestamp Column
A lot of beginners seem to completely ignore the timestamp or time series column and just drop it. This might result in not understanding the data correctly and might result in a model that is not good.
2. Using Normal Average instead of Exponentially Weighted Moving Average
A lot of times, you have to plot the average of any feature to check it’s behavior, and it is a lot beneficial to use EWMAs instead of the normal average. You can check the details and maths in this video by Professor NG, where he explains why EWMA is better than normal averages.
Luckily, you can achieve it in Pandas in a single line by using ewm function.
df['EWMA-12'] = df['Thousands of Passengers'].ewm(span=12).mean()
Here, we are finding EWMA for 12 months span in our dataset.
We can plot it by
df[['Thousands of Passengers', 'EWMA-12']].plot(figsize=(12,6))
3. Defining Trend as a Linear growth over time
Suppose I have a dataset for GDP of a country over time and related features, and if I plot the trend for 1 year and it is linear, it does not mean that it might be a linear trend because most real-world datasets are not linear. And 1 year is a really short span to see and observe any trend.
For example, the Trend of GDP for 1 year is
df['trend_gdp']['2005'].plot(figsize=(12,5))
It seems quite linear, but when we plot it on a long dataset, with a lot of data, we can see the actual trend, which is not fully linear.
df['trend_gdp'].plot()
Related: | https://www.kdnuggets.com/2020/11/analyzing-time-series.html | CC-MAIN-2021-04 | refinedweb | 1,246 | 62.58 |
Tuples and records are examples of creating new types by “multiplying” existing types together. At the beginning of the series, I mentioned that the other way of creating new types was by “summing” existing types. What does this mean?
Well, let’s say that we want to define a function that works with integers OR booleans, maybe to convert them into strings. But we want to be strict and not accept any other type (such as floats or strings). Here’s a diagram of such as function:
How could we represent the domain of this function?
What we need is a type that represents all possible integers PLUS all possible booleans.
In other words, a “sum” type. In this case the new type is the “sum” of the integer type plus the boolean type.
In F#, a sum type is called a “discriminated union” type. Each component type (called a union case) must be tagged with a label (called a case identifier or tag) so that they can be told apart (“discriminated”). The labels can be any identifier you like, but must start with an uppercase letter.
Here’s how we might define the type above:
type IntOrBool = | I of int | B of bool
The “I” and the “B” are just arbitrary labels; we could have used any other labels that were meaningful.
For small types, we can put the definition on one line:
type IntOrBool = I of int | B of bool
The component types can be any other type you like, including tuples, records, other union types, and so on.
type Person = {first:string; last:string} // define a record type type IntOrBool = I of int | B of bool type MixedType = | Tup of int * int // a tuple | P of Person // use the record type defined above | L of int list // a list of ints | U of IntOrBool // use the union type defined above
You can even have types that are recursive, that is, they refer to themselves. This is typically how tree structures are defined. Recursive types will be discussed in more detail shortly.
At first glance, a sum type might seem similar to a union type in C++ or a variant type in Visual Basic, but there is a key difference. The union type in C++ is not type-safe and the data stored in the type can be accessed using any of the possible tags. An F# discriminated union type is safe, and the data can only be accessed one way. It really is helpful to think of it as a sum of two types (as shown in the diagram), rather than as just an overlay of data.
Some key things to know about union types are:
type IntOrBool = I of int | B of bool // without initial bar type IntOrBool = | I of int | B of bool // with initial bar type IntOrBool = | I of int | B of bool // with initial bar on separate lines
type IntOrBool = int of int| bool of bool // error FS0053: Discriminated union cases // must be uppercase identifiers
Personor
IntOrBool) must be pre-defined outside the union type. You can’t define them “inline” and write something like this:
type MixedType = | P of {first:string; last:string} // error
or
type MixedType = | U of (I of int | B of bool) // error
Int32and
Booleantypes (from the
Systemnamespace) were used instead, and the labels were named the same, we would have this perfectly valid definition:
open System type IntOrBool = Int32 of Int32 | Boolean of Boolean
This “duplicate naming” style is actually quite common, because it documents exactly what the component types are.
If you find this site useful, you can download it as a ebook/PDF here.
To create a value of a union type, you use a “constructor” that refers to only one of the possible union cases. The constructor then follows the form of the definition, using the case label as if it were a function. In the
IntOrBool example, you would write:
type IntOrBool = I of int | B of bool let i = I 99 // use the "I" constructor // val i : IntOrBool = I 99 let b = B true // use the "B" constructor // val b : IntOrBool = B true
The resulting value is printed out with the label along with the component type:
val [value name] : [type] = [label] [print of component type] val i : IntOrBool = I 99 val b : IntOrBool = B true
If the case constructor has more than one “parameter”, you construct it in the same way that you would call a function:
type Person = {first:string; last:string} type MixedType = | Tup of int * int | P of Person let myTup = Tup (2,99) // use the "Tup" constructor // val myTup : MixedType = Tup (2,99) let myP = P {first="Al"; last="Jones"} // use the "P" constructor // val myP : MixedType = P {first = "Al";last = "Jones";}
The case constructors for union types are normal functions, so you can use them anywhere a function is expected. For example, in
List.map:
type C = Circle of int | Rectangle of int * int [1..10] |> List.map Circle [1..10] |> List.zip [21..30] |> List.map Rectangle
If a particular case has a unique name, then the type to construct will be unambiguous.
But what happens if you have two types which have cases with the same labels?
type IntOrBool1 = I of int | B of bool type IntOrBool2 = I of int | B of bool
In this case, the last one defined is generally used:
let x = I 99 // val x : IntOrBool2 = I 99
But it is much better to explicitly qualify the type, as shown:
let x1 = IntOrBool1.I 99 // val x1 : IntOrBool1 = I 99 let x2 = IntOrBool2.B true // val x2 : IntOrBool2 = B true
And if the types come from different modules, you can use the module name as well:
module Module1 = type IntOrBool = I of int | B of bool module Module2 = type IntOrBool = I of int | B of bool module Module3 = let x = Module1.IntOrBool.I 99 // val x : Module1.IntOrBool = I 99
For tuples and records, we have seen that “deconstructing” a value uses the same model as constructing it. This is also true for union types, but we have a complication: which case should we deconstruct?
This is exactly what the “match” expression is designed for. As you should now realize, the match expression syntax has parallels to how a union type is defined.
// definition of union type type MixedType = | Tup of int * int | P of Person // "deconstruction" of union type let matcher x = match x with | Tup (x,y) -> printfn "Tuple matched with %i %i" x y | P {first=f; last=l} -> printfn "Person matched with %s %s" f l let myTup = Tup (2,99) // use the "Tup" constructor matcher myTup let myP = P {first="Al"; last="Jones"} // use the "P" constructor matcher myP
Let’s analyze what is going on here:
The label for a union case does not have to have to have any type after it. The following are all valid union types:
type Directory = | Root // no need to name the root | Subdirectory of string // other directories need to be named type Result = | Success // no string needed for success state | ErrorMessage of string // error message needed
If all the cases are empty, then we have an “enum style” union:
type Size = Small | Medium | Large type Answer = Yes | No | Maybe
Note that this “enum style” union is not the same as a true C# enum type, discussed later.
To create an empty case, just use the label as a constructor without any parameters:
let myDir1 = Root let myDir2 = Subdirectory "bin" let myResult1 = Success let myResult2 = ErrorMessage "not found" let mySize1 = Small let mySize2 = Medium
Sometimes it is useful to create union types with only one case. This might be seem useless, because you don’t seem to be adding value. But in fact, this a very useful practice that can enforce type safety*.
* And in a future series we’ll see that, in conjuction with module signatures, single case unions can also help with data hiding and capability based security.
For example, let’s say that we have customer ids and order ids which are both represented by integers, but that they should never be assigned to each other.
As we saw before, a type alias approach will not work, because an alias is just a synonym and doesn’t create a distinct type. Here’s how you might try to do it with aliases:
type CustomerId = int // define a type alias type OrderId = int // define another type alias let printOrderId (orderId:OrderId) = printfn "The orderId is %i" orderId //try it let custId = 1 // create a customer id printOrderId custId // Uh-oh!
But even though I explicitly annotated the
orderId parameter to be of type
OrderId, I can’t ensure that customer ids are not accidentally passed in.
On the other hand, if we create simple union types, we can easily enforce the type distinctions.
type CustomerId = CustomerId of int // define a union type type OrderId = OrderId of int // define another union type let printOrderId (OrderId orderId) = // deconstruct in the param printfn "The orderId is %i" orderId //try it let custId = CustomerId 1 // create a customer id printOrderId custId // Good! A compiler error now.
This approach is feasible in C# and Java as well, but is rarely used because of the overhead of creating and managing the special classes for each type. In F# this approach is lightweight and therefore quite common.
A convenient thing about single case union types is you can pattern match directly against a value without having to use a full
match-with expression.
// deconstruct in the param let printCustomerId (CustomerId customerIdInt) = printfn "The CustomerId is %i" customerIdInt // or deconstruct explicitly through let statement let printCustomerId2 custId = let (CustomerId customerIdInt) = custId // deconstruct here printfn "The CustomerId is %i" customerIdInt // try it let custId = CustomerId 1 // create a customer id printCustomerId custId printCustomerId2 custId
But a common “gotcha” is that in some cases, the pattern match must have parens around it, otherwise the compiler will think you are defining a function!
let custId = CustomerId 1 let (CustomerId customerIdInt) = custId // Correct pattern matching let CustomerId customerIdInt = custId // Wrong! New function?
Similarly, if you ever do need to create an enum-style union type with a single case, you will have to start the case with a vertical bar in the type definition; otherwise the compiler will think you are creating an alias.
type TypeAlias = A // type alias! type SingleCase = | A // single case union type
Like other core F# types, union types have an automatically defined equality operation: two unions are equal if they have the same type and the same case and the values for that case is equal.
type Contact = Email of string | Phone of int let email1 = Email "bob@example.com" let email2 = Email "bob@example.com" let areEqual = (email1=email2)
Union types have a nice default string representation, and can be serialized easily. But unlike tuples, the ToString() representation is unhelpful.
type Contact = Email of string | Phone of int let email = Email "bob@example.com" printfn "%A" email // nice printfn "%O" email // ugly! | https://fsharpforfunandprofit.com/posts/discriminated-unions/ | CC-MAIN-2018-13 | refinedweb | 1,839 | 61.4 |
JUnit Categories are only applicable for JUnit 4.8 and above. In this java interfaces are used to make different categories and add your test cases in different categories. This allows you to run your test cases as per different categories.
Whenever we are creating a automation framework. We write all the test cases covering the entire application but at the time execution we realize that we want to run some test cases during Feature Testing, Some test cases while User Acceptance Testing and some test cases during production release so in this case you can categories your test case and execute as per categories.
Let us see an example of JUnit categories as shown below -
public interface FastTests { /* category created */ } public interface SlowTests { /* category created */ } public class A { @Test public void a() { fail(); } @Category(Feature1Tests.class) @Test public void b() { } } @Category({ Feature1Tests.class, Feature2Tests.class }) public class B { @Test public void c() { } } @RunWith(Categories.class) @IncludeCategory(Feature1Tests.class) @SuiteClasses({ A.class, B.class }) // Note that Categories is a kind of Suite public class Feature1TestSuite { // Will run A.b and B.c, but not A.a } @RunWith(Categories.class) @IncludeCategory(Feature1Tests.class) @ExcludeCategory(Feature2Tests.class) @SuiteClasses({ A.class, B.class }) // Note that Categories is a kind of Suite public class Feature1TestSuite { // Will run A.b, but not A.a or B.c } | http://www.qaautomated.com/2016/09/junit-categories.html | CC-MAIN-2018-51 | refinedweb | 222 | 51.24 |
Atomic file writes.
Project description
Atomic file writes.
from atomicwrites import atomic_write with atomic_write('foo.txt', overwrite=True) as f: f.write('Hello world.') # "foo.txt" doesn't exist yet. # Now it does.
Features that distinguish it from other similar libraries (see Alternatives and Credit):
- Race-free assertion that the target file doesn’t yet exist. This can be controlled with the overwrite parameter.
- Windows support, although not well-tested. The MSDN resources are not very explicit about which operations are atomic.
- Simple high-level API that wraps a very flexible class-based API.
- Consistent error handling across platforms.
How it works. On Windows, it uses MoveFileEx through stdlib’s ctypes with the appropriate flags.
Note that with link and unlink, there’s a timewindow where the file might be available under two entries in the filesystem: The name of the temporary file, and the name of the target file.
Also note that the permissions of the target file may change this way. In some situations a chmod can be issued without any concurrency problems, but since that is not always the case, this library doesn’t do it by itself.
fsync
On POSIX, fsync is invoked on the temporary file after it is written (to flush file content and metadata), and on the parent directory after the file is moved (to flush filename).
fsync does not take care of disks’ internal buffers, but there don’t seem to be any standard POSIX APIs for that. On OS X, fcntl is used with F_FULLFSYNC instead of fsync for that reason.
On Windows, _commit is used, but there are no guarantees about disk internal buffers.
Alternatives and Credit
Atomicwrites is directly inspired by the following libraries (and shares a minimal amount of code):
- The Trac project’s utility functions, also used in Werkzeug and mitsuhiko/python-atomicfile. The idea to use ctypes instead of PyWin32 originated there.
- abarnert/fatomic. Windows support (based on PyWin32) was originally taken from there.
Other alternatives to atomicwrites include:
- sashka/atomicfile. Originally I considered using that, but at the time it was lacking a lot of features I needed (Windows support, overwrite-parameter, overriding behavior through subclassing).
- The Boltons library collection features a class for atomic file writes, which seems to have a very similar overwrite parameter. It is lacking Windows support though.
License
Licensed under the MIT, see LICENSE.
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/atomicwrites/ | CC-MAIN-2018-30 | refinedweb | 421 | 66.94 |
Why Scala introduces lazy parameters. Shouldn't it be managed by the JVM (invisible for the user) how the value is initialized? What is the real world use case in which it is worth to give the control into developers hand and define values as lazy?
The by-name parameters: one of the primary motivations was to support dsls. They allow you to have a really nice syntax in APIs, that almost feel as if they're built into the language. For example, you can very easily define your own custom
repeat-loop:
def repeat(body: =>Unit)(until: =>Boolean): Unit = { body if (until) {} else repeat(body)(until) }
And then use it as if it were a part of the language.
var i = 0 repeat { println(i) i += 1 } (i < 3)
Or you could similarly spawn a new thread like this:
spawn { println("on the new thread!") }, or you could do automatic resource management of your
FileInputStreams like this:
withFile("/home/john/.bashrc") { println(_.contents) }.
The
lazy values - the motivations here are:
Streams that are popular in functional languages that you can use to implement efficient data-structure a-la Okasaki's functional queues.
class A { object B }
becomes something like:
class A { class A$B$ lazy val B = new A$B$ } | https://codedump.io/share/OuVk22XMjlvw/1/when-to-use-lazy-values-in-scala | CC-MAIN-2017-17 | refinedweb | 212 | 60.45 |
tag:blogger.com,1999:blog-50580843999751427132016-05-04T08:31:59.673-07:00Marketing My Life: Branding Darren WithersThis blog has evolved to become a place where I share my career and professional philosophies, rants, common sense and anything else I feel worthy of sharing. One day, these posts may be the basis for a book chronicling my growth and knowledge.Darren Withers Development Series: Never Have to Look For a Job<strong style="color: rgb(51, 0, 51);"><span style="font-size:180%;"><span style="color: rgb(51, 0, 51);">Marketing, Money and More (</span><em><span style="color: rgb(51, 0, 51);">Issue 15)</span><br /></em></span></strong><p style="margin: 0in 0in 0pt; color: rgb(51, 0, 51);" class="MsoNormal"><br /></p><p style="margin: 0in 0in 0pt; color: rgb(51, 0, 51);" class="MsoNormal"><span style="font-size:130%;"><br /><strong></strong></span></p><span style="color: rgb(51, 0, 51);font-size:130%;" ><strong>Take this Job and...</strong></span><br /><br /><p style="margin: 0in 0in 0pt; color: rgb(51, 0, 51);" class="MsoNormal"><br /><strong></strong></p> <span style="color: rgb(51, 0, 51);font-size:100%;" >As I've been posting my thoughts on business development, sales and marketing, I've been thinking on how what I'm posting can apply to anyone and everyone. Really, adding sales and marketing to your professional bag of tricks makes you more "marketable" in your career. I think back to every office manager I worked with. Seemingly, if that person didn't have an "above and beyond" work ethic, that position was not hard to replace, but if that person was responsible for referring in $20,000 worth of business every year, then they are truly irreplaceable or at least much more costly to replace. See what I am getting at...</span><br /><br /><span style="color: rgb(51, 0, 51);font-size:100%;" >As I write this post, the unemployment rate in the US is holding steady at 9.3% (Closer to 14% in Nevada where I live; <a href="">click here</a> to see your state). I believe I can help those in the job market looking for a career opportunity, fresh out of college or a seasoned veteran with what I am about to say. In ret</span><span style="color: rgb(51, 0, 51);font-size:100%;" >rospect, I've spoken to many people recently who, years ago, would fight me on joining associations, keeping a growing list of contacts and engaging in social/professional networking (online & offline). When the economy was booming and businesses were in short supply of workers, it was OK to be a paycheck player and fly through your work unnoticed by your peers. Today is the polar opposite with employers looking for team members that can provide value well beyond their j</span><span style="color: rgb(51, 0, 51);font-size:100%;" >ob description....<br /><br /><br /></span><strong style="color: rgb(51, 0, 51);"></strong><strong style="color: rgb(51, 0, 51);"><span style="font-size:130%;">You Don't Need</span></strong><strong style="color: rgb(51, 0, 51);"><span style="font-size:130%;"> It Til You Need It</span></strong><strong style="color: rgb(51, 0, 51);"><br /><br /></strong><span style="color: rgb(51, 0, 51);">Waiting until you are out of work or in a position to look for another opportunity to build up your social media persona, get involved in associations, start volunteering with community organizations and networking in the real world is a hazardous way to manage your career. This philosophy can be compared to waiting til you've acquired diabetes to take control of your diet and exercise. The point is if you are in your comfort zone in your current professional role and don't see the need for any of wha</span><span style="color: rgb(51, 0, 51);">t was just mentioned, well, you are wrong. I'm going to stress how your value to your company goes beyond how well you do the tasks required of you in your position.<br /><br />The first step is understanding your value to your employer. Are you easily replaced? Do you bring more value to your emp</span><span style="color: rgb(51, 0, 51);">loyer than just the responsibilities outlined in your job description? Do you bring unique skills or expertise to the table? Are you considered valuable by your industry peers?<br /><br />The first step is understanding your perceived value right no</span><span style="color: rgb(51, 0, 51);">w.<br /><br /><br /></span><strong style="color: rgb(51, 0, 51);"><span style="font-size:130%;">Professional Branding</span></strong><br /><span style="color: rgb(51, 0, 51);"><br />Knowing the answer to these questions is the key to beginning a process of building a professional pers</span><span style="color: rgb(51, 0, 51);">ona. This is your brand for your career. This is something that needs to be managed and groomed to give you the most benefit... Those benefits can be anything from desired salary, to job title, to just having the creative freedom in your career to really do what you love and have others pay you well for it. The main elements of your professional persona (at least from my point of view) are:<br /></span><ol style="color: rgb(51, 0, 51);"><li>Internal/Employee Reputation</li><li>Industry Professional Reputation</li><li>Industry Social Reputation</li></ol><span style="color: rgb(51, 0, 51);">We all have a reputation.... Ask your boss, your peers and people in your industry what they think of you professionally and socially (or maybe have someone else do this). I am willing to bet, if they are truthful, that you hear some pretty interesting opinions. The worst opinion is for them to not have one. You can control this and here's how.</span><br /><br /><br /><strong style="color: rgb(51, 0, 51);">One Part Social, Two Parts Professional</strong><br /><span style="color: rgb(51, 0, 51);font-size:100%;" ><br /></span><strong style="color: rgb(51, 0, 51);"><span style="font-weight: normal; color: rgb(51, 0, 51);">There are some out there that put a very solid wall between their work life and their social life. There is good reason for some, but this can be a detriment to your career. People help the people they like. They like the people that socialize with them. This can be your boss, your co-worker, an investor, an industry thought leader or whoever. If you are not open to friendships with your professional contacts, then you can't expect friendly help fro</span></strong><strong style="color: rgb(51, 0, 51);"><span style="font-weight: normal; color: rgb(51, 0, 51);">m them. I'm going to explain the path I chose and I what I do that ensures I will never have to be a piece of paper in a stack of resumes.<br /></span></strong><br /><strong style="color: rgb(51, 0, 51);"><span style="font-weight: normal; color: rgb(51, 0, 51);">In 2007, I created my online persona. I wanted to own the search for "Darren Withers" on <a href="">Google</a>. It took time, I won't lie, but the end result is something to be proud of. I spent two weeks on my couch in December 2006. I didn't shave or do much else. I spent hours inputting information into every relevant social media site I could. I drafted a boiler plate for all the "about me" sections, updated my professional skills, researched and began to Search Engine Optimize myself. The sites I started with were:</span></strong><br /><br /><ol style="color: rgb(51, 0, 51);"><li style="text-align: left;"><a href="">Linkedin</a></li><li><a href="">Twitter</a></li><li><a href="">MySpace</a></li><li><a href="">Facebook</a></li><li><a href="">Youtube</a></li><li><a href="">ZoomInfo</a></li><li><a href="">AgencyScoop</a></li><li><a href="">Jigsaw</a></li><li><a href="">123People </a><br /></li><li>Live</li><li>Yahoo!</li><li>AOL</li><li>Google</li><li>Bebo</li><li>Flickr</li><li style="color: rgb(51, 0, 51);"><a href="">Photobucket</a><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href=""><img style="margin: 0pt 0pt 10px 10px; float: right; cursor: pointer; width: 400px; height: 296px;" src="" alt="" id="BLOGGER_PHOTO_ID_5599186251058423698" border="0" /></a></li></ol><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><strong><span style="font-weight: normal; color: rgb(51, 0, 51);"><span style="color: rgb(51, 0, 51);">I began to link the different profiles together to make sure there was only good information that I wanted out there. Once this process was completed, within a few weeks I was very happy with the search term results for "Darren Withers." I had taken control of what others would see if they were to research who I was.</span><br /><br /><span style="color: rgb(51, 0, 51);">As time went on, I added to my online activities. I also launched this blog in 2007. I was aiming to become a thought-leader as I moved toward launching my own consulting business. I won't go through too much about this blog since you must be here reading this post, so you can see how long it's been up. I write about things relevant to the marketing industry but I do add a bit of my own personality by sharing some personal stories as well. I feel like someone reading all of my posts might not just get some value out of it, but might even be able to connect with me as a person.</span><br /><br /><span style="color: rgb(51, 0, 51);">Taking control of your online persona is the first step to building your network database. This is the step that will make you look that much better to employers as they see that you are utilizing social channels that could ultimately help them and their business. Recognizing the tools that you have available to you and how they can be helpful in driving up your value to a company is critical to achieving your career goals. I'll follow up this post with more on social networking and then what to do with your database of contacts. Please feel free to jump back to the first of the </span><span style="font-weight: bold; color: rgb(51, 0, 51);">Business Development Series:</span><span style="color: rgb(51, 0, 51);"> </span><a style="color: rgb(102, 51, 255);" href="">Where the Network Begins</a><span style="color: rgb(51, 0, 51);">. It's a pretty good how-to on networking at events and how to be the most effective. Make sure you online persona is in place before networking out in the real world.</span><br /><br /><span style="color: rgb(51, 0, 51);">The post is dedicated to someone I'm trying to help get their career shoes on. "Let's blow it up!"</span><br /></span></strong><strong><br /></strong><img src="" height="1" width="1" alt=""/>Darren Withers Value of Time<strong><span style="font-size:180%;">Marketing, Money and More (<em>Issue 14)</em></span></strong><br /><em></em><br /><p style="margin: 0in 0in 0pt;" class="MsoNormal"><br /><strong></strong></p><p style="margin: 0in 0in 0pt; color: rgb(51, 0, 51);" class="MsoNormal"><strong><span style="font-size:130%;">Time<br /></span></strong></p><p style="margin: 0in 0in 0pt; color: rgb(51, 0, 51);" class="MsoNormal"><br /><strong></strong></p> <span style="color: rgb(51, 0, 51);font-size:100%;" >I'm kind of a geek at heart. I watch more <a href="">Discovery Channel</a> programming than "normal" shows. One thing that always fascinates me is </span><span style="color: rgb(51, 0, 51);">the concept of "time.". Time is the 4th dimension. If you believe in the concept of <a href="">String Theory</a>, then you know that we operate in an 11 dimension universe in a vast </span><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" style="color: rgb(51, 0, 51);" href=""><img style="margin: 0pt 0pt 10px 10px; float: right; cursor: pointer; width: 225px; height: 225px;" src="" alt="" id="BLOGGER_PHOTO_ID_5591479404339836770" border="0" /></a><span style="color: rgb(51, 0, 51);">multiverse of universes. Before I go into a mind-blowing rant, I'm going to explain (or at least try to explain) my views on time. Time as it stands today is experienced by each person differently. In moments of high-stress where your adrenaline is pumping hard, your perception of time is changed allowing your brain to process more information.</span><br /><br /><span style="color: rgb(51, 0, 51);">Experiments have been done showing this is true. A display on a perceptual chronometer was used to flash numbers on a screen that in normal circumstances could not be read by a person. When time is slowed or our ability to take in more visual information per second is increased, the numbers on the screen are revealed. Check it out the video (</span><a style="color: rgb(51, 51, 255);" href="">Click Here</a><span style="color: rgb(51, 0, 51);">).</span><br /><br /><span style="color: rgb(51, 0, 51);">It is also true that gravity and velocity affect time. Astronauts in outer space are experiencing time differently than those of us on earth. Although only milliseconds of a difference, astronauts on the International Space Station (ISS) actually age slower than we do on earth (.007 seconds slower to be exact).</span><br /><br /><strong style="color: rgb(51, 0, 51);"></strong><br /><br /><p style="margin: 0in 0in 0pt; color: rgb(51, 0, 51);" class="MsoNormal"><strong><span style="font-size:130%;">What Is My Time Worth?<br /></span></strong></p><br /><span style="color: rgb(51, 0, 51);">Now that I've gone over the science of time and how crazy time really is, we begin to think of our own time, who values it, how we value it and what our daily activities say about how we value our time. Having worked int he advertising industry, I used to sell "time." I know. How do you sell "time?" I had rate sheets for processes involved in the creative process. "Concepting" might be billed at a rate of $125 per hour while "copywriting" was billed at $90 per hour. If it takes 50 hours of billable "time" to create a sales kit, then I would factor in all of the different rates and hours and build an estimate. Is someone's time really worth $125, $200, $250 or even $1? Clients never felt like they were buying "time". They felt like they were buying an "end-product" which would ultimately be the sales kit.</span><br /><br /><span style="color: rgb(51, 0, 51);">My time is divided by my personal activities and my work time. Essentially I sold 40 hours of my weekly time to my employer, </span><a style="color: rgb(51, 102, 255);" href="">mobileStorm</a><span style="color: rgb(51, 0, 51);"> (and happily in case my CEO is reading this.) That time is worth more to mobileStorm than what it is worth to me, economically speaking. mobileStorm also invests in my knowledge of digital marketing, increasing the value of my time as it is used to consult for clients. The more my time can be sold for, the value of my time goes up.</span><br /><br /><span style="color: rgb(51, 0, 51);">Opportunity costs play a big role. I just recently moved. I wanted to save time and money. Unfortunately I couldn't save both. I chose to save money and move all of my belongings myself. I took my personal time and my work time to move all of my stuff. I've hired movers in the past to the tune of $100 per hour. If the time I'd save equals 20 hours by hiring movers for 5 hours, then I need to make $25 an hour or more for this to make sense financially. Fortunately for me, it did make financial sense to get movers. This was also great because moving is one of my top 3 most horrible things I can do next to cutting myself and getting cavities filled.</span><br /><span style="font-weight: bold; color: rgb(51, 0, 51);"><span style="font-size:130%;"><br /><br />Older, Wiser and Less Time to Waste</span><br /><br /></span><span style="color: rgb(51, 0, 51);">As I've gotten older and more mature in my career, I've begun to value time much more highly. As I've worked in multiple roles from owning my own consulting business, to working for other people, </span><span style="color: rgb(51, 0, 51);">I</span><span style="color: rgb(51, 0, 51);"> had my time valued anywhere from $10 per hour to $250 per hou</span><span style="color: rgb(51, 0, 51);">r. In my personal life, friends and family don't pay for my time (although sometimes I wish I could charge.) That time is beyond monetary value, but somewhere in my mind when I prioritize family and friends above work I must have made some calculation.<br /><br />I have had people ask for free advice or a favor or to help a nonprofit. I rarely have turned down requests for such things and I have become known for being dependable and someone that can be counted on to help. My views are changing now and I have made a conscious effort to turn down more of these opportunities to give away my time. I believe my past generosity was necessary to prove myself, my willingness, my general work ethic and to just be a good friend and human being. In order for me to raise my value and the value of my time, I have to pull back on my inventory of hours and make sure that opportunities to sell my time are very carefully calculated.<br /></span><br /><span style="font-weight: bold; color: rgb(51, 0, 51);"><span style="font-size:130%;"><br />Time to Change</span><br /><br /></span><span><span style="color: rgb(51, 0, 51);">Thinking like this can make you feel cold, heartless and make everything into a money comparison. I am not saying that you shouldn't visit your mom and dad for Christmas because your time is worth too much. I'm saying that being aware or what your time is currently valued at and what you would like to be paid for your time. Take the time to come up with a dollar value for what you would like to earn and apply that to the total hours you would be willing to commit to your professional activities. If your current earnings per hour worked are not inline with what you value your time at, then it is "time" to look at increasing your professional value. Take comparative salaries of others and see what those people have in terms of experience, schooling or abilities. The goal should be to acquire the skills and experience necessary to achieve your ideal hourly value. Obviously financial situations change and I think we have all taken less than would have liked to do a task or project because we needed the income. If you are in a stable position and you can inch up your professional hourly value year by year, then you can get closer and closer to having your time valued very highly by others.... earning more and having your priceless personal time to do what makes you happy. </span><br /><br /><br /><span style="color: rgb(51, 0, 51);">Alternatively you could build your business on the ISS and charge more per Earth hour than any other business on the Planet! I invested time in sharing my thoughts in this blog and I hope to one day have it pay off in the form of a published book. We'll see as this is my testing ground. I'd love to hear some feedback on how you feel about your time.</span><br /></span><span style="font-weight: bold;font-size:130%;" ></span><img src="" height="1" width="1" alt=""/>Darren Withers Your Relationship<a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href=""><img style="margin: 0pt 0pt 10px 10px; float: right; cursor: pointer; width: 224px; height: 224px;" src="" alt="" border="0" /></a><br /><strong><span style="font-size:180%;"><span style="color: rgb(51, 0, 51);">Marketing, Money and More (</span><em><span style="color: rgb(51, 0, 51);">Issue 13)</span><br /></em></span></strong><p style="margin: 0in 0in 0pt;" class="MsoNormal"><br /></p><p style="margin: 0in 0in 0pt;" class="MsoNormal"><span style="font-size:130%;"><br /><strong></strong></span></p><span style="font-size:130%;"><strong style="color: rgb(51, 0, 51);">Communication Overload</strong></span><br /><br /><p style="margin: 0in 0in 0pt; color: rgb(51, 0, 51);" class="MsoNormal"><br /><strong></strong></p> <span style="color: rgb(51, 0, 51);font-size:100%;" >I was recently inspired by my friends, colleagues and...shoot....even the girls I dated to write this one, so I hope it helps you empathize with others in this new age of communication. I thought about my last month of communicating with people. This morning I checked my <a href="">Facebook</a> and <a href="">Twitter</a>. Yay! I got 2 mentions on twitter, 50 club invites on Facebook and a few comments and posts from friends. Ooh. Three people liked my smart comment! I switched gears and jumped into Outlook. I had 20 messages waiting for me in my inbox. Got a text from my buddy who lives in the same condo development that I do. That exchange went two or three rounds at least. Then..Oops, I work from my home, so I had to jump on to AIM to have some email-related discussion with my friends at <a href="">mobileStorm</a></span><span style="color: rgb(51, 0, 51);font-size:100%;" >.</span><span style="color: rgb(51, 0, 51);font-size:100%;" > I </span><span style="color: rgb(51, 0, 51);">then took a look at </span><a style="color: rgb(51, 0, 51);" href="">Linkedin</a><span style="color: rgb(51, 0, 51);"> and I had a few requests to get connected and someone I was hoping would reach out, reached out. I jumped a little when my phone rang. Of course, it's mom. The only one that still leaves me voicemails. Get to that one later.</span><br /><br /><span style="color: rgb(51, 0, 51);">Point here is that 12 years ago I was lucky to get a page on my pager from friends and then I'd pull out my decoder to see what code meant what and then call someone back once I figured it out. NOW, I have what feels like 100 different ways to get a message to and from someone. This new buffet of communication methods has expanded my network by allowing me to keep tabs on more people from anywhere, but it also has shown me where I stand with those people. The channels I use now communicate something. The time I take to respond communicates something. Not doing anything communicates something. What am I communicating and do I even know am doing it? Calm down. Let's take this slow and work it out.</span><br /><br /><strong style="color: rgb(51, 0, 51);"><br /></strong><strong style="color: rgb(51, 0, 51);"><span style="font-size:130%;">Where Do You Stand?</span><br /><br /></strong><span style="color: rgb(51, 0, 51);">Let's take this personal, very personal. I am a single guy in Vegas. I date... A lot. It's very funny how you can tell where you stand with the people you are dating...or trying to date. I always call first to ask someone out or I do it in person. I don't always get the same in return. I'll get the number one night and call a few nights later and leave a voicemail. A few minutes later I get a text response, "Hey. Glad you called. Heading to a fun event later. Let me know what you are up to." I called and I got a text back. This does not look promising. Essentially, I was downgraded. I value a phone call more highly than a text. This girl likely calls people she feels are important, but I do not meet that criteria. We'll see how this one goes...</span><br /><br /><span style="color: rgb(51, 0, 51);">I have moved up the ladder from a Facebook friend, to a text buddy, to a phone call and ultimately to a dating situation. You can tell by the progression that my personal value rose with this person to a level where she was able to give up a piece of her time to communicate on the phone and ultimately in person. These are usually the best situations and when response times are fast, it's a good sign. It's also really telling when the other person uses multiple communications throughout the day.</span><br /><br /><span style="color: rgb(51, 0, 51);">I've also been downgraded. Recently I watched a dating situation move from in-person to phone calls, to text messages, to email and then ultimately it disappeared. Not only did the communication method dip in "personal value," but I also noticed the response time get longer and longer and longer when I would reach out. The inevitable "beginning of the end."</span><br /><br /><span style="color: rgb(51, 0, 51);">This goes beyond dating. I have had business situations as well where the communications heat up and fizzle out. What's appropriate for personal is not always the same for business. Knowing how and when to use what channel will give you the best outcome in business or your personal life. 90% of communication is non-verbal and words are just words so pay attention. </span><br /><span style="font-size:130%;"><br /><strong style="color: rgb(51, 0, 51);"><br /></strong></span><strong style="color: rgb(51, 0, 51);"><span style="font-size:130%;">Matching the Channel to the Message</span><br /><br /></strong><span style="color: rgb(51, 0, 51);">Here are the channels I feel that I have available to me throughout my day in order of the highest personal value to lowest personal value to me:</span><br /><ol style="color: rgb(51, 0, 51);"><li>In-Person Meeting</li><li>Phone Call</li><li>Text Message</li><li>IM</li><li>Email</li><li>Facebook</li><li>Twitter</li></ol><span style="color: rgb(51, 0, 51);">(I didn't leave out direct mail, but I really don't think it counts for day to day.)</span><br /><br /><span style="font-weight: bold; color: rgb(51, 0, 51);">Meetings </span><span style="color: rgb(51, 0, 51);">are the top dog. It is the highest level of respect and engagement you can have with another human being. Business or personal, nothing says you are important more than someone taking the time to meet up. It is getting more and more rare these days, but if you want to impress someone, get dressed and meet somewhere for more than 30 minutes.</span><br /><br /><span style="font-weight: bold; color: rgb(51, 0, 51);">Phone calls </span><span style="color: rgb(51, 0, 51);">are the next best thing. I do most of my work over the phone. It's a bit harder to gauge reactions because you can't see their facial expressions and body language, but if you are good, you can do anything in the business world. I always tell people I can't give them everything over the phone because then why would you want to hang out with me. I try to move people I want to value me up the ladder by make each communication experience better than the previous and hinting at how much better the next step up will be.</span><br /><span style="font-weight: bold; color: rgb(51, 0, 51);"><br />Text messages</span><span style="color: rgb(51, 0, 51);"> are great for quick informative communications, like leaving a digital post-it note on the fridge. You can get out a quick communication, but choose words carefully and do your best to leave nothing to interpretation...not an easy task for 160 characters. Arguments and bad news are not great in a text message and will likely lead to misunderstandings, plus they are in print. No one can forget a text message with hateful content when they can look at it repeatedly.</span><br /><br /><span style="font-weight: bold; color: rgb(51, 0, 51);">IM </span><span style="color: rgb(51, 0, 51);">is great for having conversations when sitting at your computer and banter, but again it is removed from the personal nature of speech. This can give people a lot of time to think out their comments and it's hard to be "in the moment".</span><br /><br /><span style="font-weight: bold; color: rgb(51, 0, 51);">Email </span><span style="color: rgb(51, 0, 51);">is great for keeping records and sending private messages, but again we have some of the same pitfalls of text messaging. I feel that email is easy to hide behind, but it is wise to keep bad news or highly personal and sensitive messages out of email.</span><br /><br /><span style="font-weight: bold; color: rgb(51, 0, 51);">Facbook </span><span style="color: rgb(51, 0, 51);">can be fun for flirting and keeping up with friends. It can also be a way for people to make judgment on the lifestyle you put up there. Pictures tend to be fun and don't show you at home reading a book. It's a place where jealous boyfriends can make assumptions and arguments can be taken public. Being someone's Facebook friend is equivalent to having class with someone in my book.</span> People celebritize themselves and let everyone know every little thing they are doing (Self-admittedly, I am guilty.)<br /><br /><span style="font-weight: bold; color: rgb(51, 0, 51);">Twitter </span><span style="color: rgb(51, 0, 51);">can be good for promoting your professional knowledge and philosophies, but it is not the best place to try to air your dirty laundry. This is where people go to share information and insight. I don't feel very dynamically connected to my Twitter followers unless I know them in other capacities.</span><br /><strong style="color: rgb(51, 0, 51);"><br /><span style="font-size:130%;"><br />Communications Etiquette</span></strong><br /><span style="color: rgb(51, 0, 51);font-size:100%;" ><br /></span><strong><span style="font-weight: normal; color: rgb(51, 0, 51);">I feel like there is little education out there for people. These channels just sort of snuck up society and I'm not sure if anyone consciously realizes that an etiquette has developed for people that are good communicators. I get extremely offended when etiquette is consistently tossed aside and responses to my communications come through "lower value channels." This practice makes others feel devalued.<br /><br />Try to return the communication using the same channel as your received the original message in. If someone calls you, call them back. If someone tags you on Facebook, tag them back. If someone emails you, reply to them with an email. This is the best way to avoid conflict and maintain the level of your relationship with that person. It's a sign of respect to reciprocate an exchange.<br /><br />Understand what is appropriate. I think society would gasp if police officers started texting loved ones of deceased family members and doctors gave bad news over Facebook. Although extreme examples, understand that the more sensitive the content of your message, the higher up the communication "value chain" you should go. It shows poor character to deliver bad news via email and text. It is a slap in the face to the recipient and it will likely escalate matters.<br /><span style="font-size:130%;"><br /><br /></span></span></strong><span style="font-size:130%;"><strong style="color: rgb(51, 0, 51);">Say What You Mean</strong> </span><span style="font-weight: bold;font-size:130%;" >Because You Already Said It</span><br /><strong><span style="font-weight: normal; color: rgb(51, 0, 51);"><br />Use the appropriate channel for what you want to say. To say to someone, "I really want to see you today, let's get together." via text message, then be unresponsive for the rest of the day is a massive contradiction. The intent may have been positive, but all this did was frustrate the person receiving the message. Not only was the communication impersonal due to the fact that if someone really wants to see you, they would be excited to pick up the phone, but being inaccessible from that point forward is a very clear, "I really didn't want to see you today." Remember, everyone knows you have a Facebook, Twitter, cell phone, email, fax, IM and various other ways of getting in touch. It is nearly impossible for anyone to believe that someone can be "inaccessible" or not get 4 out of 5 communications. Being honest is the key in this new age of communications.<br /><br />How awkward would it be to find out the sex of your unborn child via a Twitter DM. These channels and message values do not match. I feel that often, bad news is give via the easiest channel like text or email. It's easy to hide behind text or email and carefully construct your sentences for the most impact. These are also the easiest to misinterpret. People add their own voice and tone in written word depending on their mood and impression of the sender. It is NEVER a good idea to send sensitive communications that will hurt or upset another person via text message or email. Over the phone or in person is the only way you will be able to react to facial cues, body language and inflections to properly manage emotional interactions.<br /><br />The whole point of this is to be aware of what your channel selections communicate to those around you. Over time, people can get a sense of where they stand with you by the method you choose to communicate to them with. The old adage, "Actions speak louder than words." sums up this post perfectly. Be respectful and show the people you value you really do value them by giving them the best interaction. Reciprocate respectfully using the same channel as they used to reach out. I promise you if you call me, I will call you back. Just understand that you need to be direct and truthful about your relationship these days because its very likely you've already told other people how you feel about them...and you didn't even know it.<br /></span><br /><br /></strong><img src="" height="1" width="1" alt=""/>Darren Withers Development Series: Where the Network Begins<strong><span style="font-size:180%;">Marketing, Money and More (<em>Issue 12)</em></span></strong><br /><em></em><br /><p style="margin: 0in 0in 0pt;" class="MsoNormal"><br /><strong></strong></p><p style="margin: 0in 0in 0pt;" class="MsoNormal"><strong><span style="font-size:130%;">Forrest Gumped My Way to Success<br /></span></strong></p><p style="margin: 0in 0in 0pt;" class="MsoNormal"><br /><strong></strong></p> <span style="color: rgb(51, 0, 51);font-size:100%;" >If you were anything like me, a 22-year old kid fresh from college thinking those you would be working for had their stuff "together", the economy was only going to grow larger and being upwardly mobile was a right guaranteed by every person born in the US, then you also had a lot to learn about the way the world really works.</span><br /><span style="color: rgb(51, 0, 51);font-size:100%;" ><br />I opened up my career like any other middle-class male. I majored in<br />Co</span><span style="color: rgb(51, 0, 51);font-size:100%;" >mmunications </span><span style="color: rgb(51, 0, 51);font-size:100%;" ><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href=""><img style="margin: 0pt 0pt 10px 10px; float: right; cursor: pointer; width: 226px; height: 137px;" src="" alt="" border="0" /></a></span><span style="color: rgb(51, 0, 51);font-size:100%;" >(Advertising) and minored in Marketing at UNLV, pushing my way through the system with the help of financial aid. It was natural that I found my way to an ad agency t</span><span style="color: rgb(51, 0, 51);font-size:100%;" >o</span><span style="color: rgb(51, 0, 51);font-size:100%;" > complete my</span><span style="color: rgb(51, 0, 51);font-size:100%;" > internship before graduation. That experience led me to my first marketing job working for a local Las Vegas Charity, <a href="">Opportunity Village.</a></span><span style="color: rgb(51, 0, 51);font-size:100%;" > </span><span style="color: rgb(51, 0, 51);font-size:100%;" >That was where I shed my ideologies about the way things work (according to the classroom) and began realizing the vast network of relationships that existed in Las Vegas in 2003. As a part of my job role, I was </span><span style="color: rgb(51, 0, 51);font-size:100%;" >responsible for 3rd party fundraising efforts and special events.</span> Fortunately during that time, I was taken under the wing of a very well-respected public relations professional named <a href="">George McCabe </a>(currently the PR Director for B&P Advertising). George opened the door to media professionals in Las Vegas and with a respected charity behind me, I was in the best position to make really valuable connections.<br /><br />I quickly realized that I stumbled onto a really great thing in my career which wouldn't be apparent to me until years later. Working for a non-profit is one the best ways to engage with politicals and decision-makers. To this day, I am recognized for having been a part of such a respected organization. When you are approaching a relationship with someone on behalf of a charity, it is likely that you will get a response and usually at a higher level than your position would justify in the for-profit world. This is great for building your reputation and hopefully you are working for a cause you believe in at the same time. Even after 7 years of not working there, I am still very active with Opportunity Village and it continues to open doors for me. I strongly recommend getting involved in the community.<br /><br />It was during this part of my career that I decided to get out there and attend all the emerging social, professional and political gatherings I could get into. I was peaking at about 5 a week, promoting Opportunity Village and getting my name out there. I was starting to see patterns early on and over the years, I've developed a strong sense about how to gain the most value from networking....<br /><br /><br /><span style="font-size:130%;"> <span style="font-weight: bold;">Sales Locusts and the Events They Feed On</span></span><br /><br />I was a little oblivious as a first-time sales person, constantly looking for opportunities to network and hand out that first business card that said I was a "somebody"...working for "somebody." I must have went to every networking event in Vegas. I'm not sure if I met new people but I sure did help out the bar tabs for the host venues. I'll tell you what...Vegas hosts the best networking events.... but I don't think I've ever done business with someone as s direct result of meeting them at a mixer, in-fact, I think most relationships that came from those experience brought more headache than help. I think this is common for most people. To this day I get chased by financial counselors. Thanks, but I can manage a zero balance on my own.<br /><br />Chamber mixers, networking groups, socials, etc. have a cycle. If they are managed and launched well, you will see an A-List crowd for maybe 12 weeks. After that, the format gets old and the quality people stop coming. The percentages lean more to the side of "clueless" sales people that would shove a business card in your face well before ever thinking to ask where you are from. This common problem accelerates the exodus of all the value that is there for someone looking to truly build their network. I call these problems "sales locusts". They come in and devour all the value and leave nothing but themselves in their wake. Eventually they move on to the next hot spot and repeat the process.<br /><span style="font-weight: bold;"><span style="font-size:130%;"><br /><br />You Never Get a Second Chance to Make a First Impression</span><br /><br /></span>But you do get a second chance to reinforce the business community's bad impression of you. How do you want to be known amongst your professional peers? Are you the sales locust mentioned above? Are you someone that has value in one form or another to people in your industry?<br /><br />If you are reading this, then you are thinking about your place in the business community. People are people. Do you like someone who just talks about what they do and do nothing to find out who you are and what you are about? Most people don't like being sold, but they love being helped. There is a powerful concept - EMPATHY. It's a lot like the Golden Rule. Treat others as you'd like to be treated...<br /><br /><br /><span style="font-weight: bold;font-size:130%;" >MMM Rules of Networking Engagement</span><br /><br />I've been talking a lot here, but I wanted to demonstrate my thoughts on networking and what I found most valuable in my career path. I've developed hundreds of great relationships in business and many of them have turned to friendships. I have some rules to follow that will help even the least social person:<br /><br /><ol><li><span style="font-weight: bold;">Never lead into a conversation with "So what do you do?" </span>This can be compared with asking a girl if she's willing to go home with you on the first date. It won't end well most of the time. You've just given up your true motive and it's a red flag to executives that you are going to harass them.<br /></li><li><span style="font-weight: bold;">Act as if no one in the room has a job, including you. </span>If you can make it through a networking event or social gathering without talking about your job, then you are on a whole other plane of existence and probably a very interesting person. You will likely connect with people better and the relationship will get deeper than just surface-level.</li><li><span style="font-weight: bold;">Keep it in your pants. </span>Don't whip out the business card at all if you can help it. Lead someone into a situation where they feel they should ask for it. If you've ever gone to a networking event and emptied your pockets, it's hard to remember whose business card is whose. I always remember the ones I asked for and really wanted. I even put them in a different spot in my wallet.<br /></li><li><span style="font-weight: bold;">Tactfully prompt someone to ask about your job if necessary. </span>So the whole point of networking is to build up your pipeline and get some business in the future. If you follow the rules above, then you will have better relationships, BUT there's always that, "I just saw the president of X company and I've been chasing them for 2 years and I need an in." If you feel you need to get a business card in someone's hand, there is a way to do this without shoving it in your prospect's face. Lead the conversation in that direction and leave an open opportunity for your prospect to ask about your job. (Example: "Have you ever been to Boston? They have the best thing on the planet. It's a toasted and buttered hot dog bun stuffed with butter-soaked lobster. I was just there on business and got sidetracked...." This leaves the opportunity for them to ask why you were in Boston and what you do which takes us right in to rule 4...</li><li><span style="font-weight: bold;">Lead the conversation. </span>You want each and every person that engages with you in a conversation to walk away with a positive impression and some value they didn't have before meeting you. If the conversation starts out with, "I hate events like this." it's your job to move the conversation quickly to the positive..."Me too, but I'm trying to oust the Mayor of this place on <a href="">Foursquare</a>, I'll find you Joe M!" In one sentence, I probably turned the conversation to one of positivity and it's likely I'll end up educating my prospect on Foursquare and it's awesome capabilities which positions me as an intelligent sound board and creates value for the interaction.</li><li><span style="font-weight: bold;">Follow networking etiquette. </span>Unless you are really deep in conversation, please recognize what you and your conversation partner are there for in the first place...to network. If you are not picking up on the signs to end the conversation, you are going to make it awkward for the other person to leave the conversation. I've heard it come to, "Hey, well it was nice talking to you, but I really want to work the room a little." Try to keep the first conversation to 5 minutes, 10 if it's going really well.<br /></li><li><span style="font-weight: bold;">Know when to leave. </span>If your prospect turns and talks to another group, don't stand behind them and wait. That's kind of strange and that's what they'll remember you for. Say, "Excuse me, I'm going to find the bathroom." and part with a handshake. This is the best position you can gain if the conversation needed to end. If the conversation really isn't going anywhere, but this is a good prospect you don't want to insult and you just need to break free, politely give that person an excuse. Try, "Hey, I'm going to go find my friend, he's the VP of Marketing for this place. Find me later and I'll make an introduction." It's legit and you've offered up a future value if they are interested.<br /><span style="font-weight: bold;"></span></li><li><span style="font-weight: bold;">Leave an invitation to reconnect. </span>As you wrap your conversation up, please give them a way to reach you or find you. Do this without shoving them your card unless they ask for it. Let them know if you plan on attending the next event or ask them what their next social night will be. I'll cover social media follow-up in the next post, so stay tuned.</li></ol><br />The next time you are at an event, you hopefully are not littering with your business cards and are engaging in a lot of valuable 5 minute conversations. Don't judge success by how many business cards you collected. Judge by how many people asked you for yours. If you can change your thinking, you may have less prospects, but you'll have better ones and fewer to manage.<br /><br /><script type="text/javascript"><br /><br /> var _gaq = _gaq || [];<br /> _gaq.push(['_setAccount', 'UA-3456971-1']);><img src="" height="1" width="1" alt=""/>Darren Withers Development Series: Foundation for Successful Business Development<div class="post-header"> </div> <strong><span style="font-size:180%;">Marketing, Money and More (<em>Issue 11)</em></span></strong><br /><em></em><br /><p style="margin: 0in 0in 0pt;" class="MsoNormal"><br /><strong></strong></p><p style="margin: 0in 0in 0pt;" class="MsoNormal"><strong><span style="font-size:130%;">The Beginning of a New Series</span></strong></p><p style="margin: 0in 0in 0pt;" class="MsoNormal"><br /><strong></strong></p> <span style="color: rgb(51, 0, 51);font-size:100%;" >My goal is to eventually become a voice amongst business development professio</span><span style="color: rgb(51, 0, 51);font-size:100%;" >nals. I think </span><span style="color: rgb(51, 0, 51);font-size:100%;" >about who I would take advice from and I know that I have to do a few things to earn that right:</span><br /><br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href=""><img style="margin: 0pt 0pt 10px 10px; float: right; cursor: pointer; width: 226px; height: 273px;" src="" alt="" border="0" /></a><br /><ol style="color: rgb(51, 0, 51);"><li><span style="font-size:100%;">Provide a unique insight into practices that will without a</span><span style="font-size:100%;"> doubt</span><span style="font-size:100%;"> produce real results for</span><span style="font-size:100%;"> sales, marketing and business development professionals</span></li><li><span style="font-size:100%;">Have a track record for success in my own right that is both aspirational and reproduce-able across any b2b industry</span></li><li><span style="font-size:100%;">Show my work and provide "real world" cases of success and implementation of key strategies</span></li></ol><span style="color: rgb(51, 0, 51);font-size:100%;" >In this series I will go into detail in identifying the key elements of a great business development program and give instruction on how to launch and maintain specific tactics. Communication channels, resources, trends, activities and the underlying process that leads to success will be comprehensively demonstrated with a realistic approach to developing clients. All of what I am teaching is fully possible for a one-man-show, but as with anything, a team effort will produce exponential returns.<br /><br />Consider this the overview and all of the following blog posts in this series will dive into great detail on foundational business development practices and explain each channel in this imaginary tool belt.</span><p style="margin: 0in 0in 0pt;" class="MsoNormal"><br /><strong><span style="font-size:130%;"></span></strong></p><p style="margin: 0in 0in 0pt;" class="MsoNormal"><br /><strong><span style="font-size:130%;"></span></strong></p><p style="margin: 0in 0in 0pt;" class="MsoNormal"><strong><span style="font-size:130%;">The Power Position<br /></span></strong></p><p style="margin: 0in 0in 0pt;" class="MsoNormal"><br /><strong><span style="font-size:130%;"></span></strong></p><p style="margin: 0in 0in 0pt;" class="MsoNormal"><span style="font-size:100%;">Who are you? I like to pull in a great analogy here. I come from a family of car sales people as far back as my grandfather. In a great economy on a car lot that has a great marketing program and consistent customer traffic, even the worst sales person can make a decent living. They become more of a cog in the machine and roll through the motions set by management. As the economy took a dive and the opportunity for selling a car decreased, these sales people were the first to go. They couldn't develop their own clients and get repeat customers. They were short-sighted in their role and believed it was their employer's job to get people to the car lot and maintain the relationship with their customers. The sales people that maintained personal relationships with their clients and generated their own leads could still maintain enough sales monthly to make or exceed quotas and they thrive even in today's economy.<br /></span></p><p style="margin: 0in 0in 0pt;" class="MsoNormal"><span style="font-size:100%;"><br /></span></p><p style="margin: 0in 0in 0pt;" class="MsoNormal"><span style="font-size:100%;">There is power in becoming self-reliant. Once you become a self-sufficient sales person, you begin to become a powerful business developer. These people have the most value to companies and can write their own ticket. More often than not, a business developer is constantly in demand and rarely has to look for employment. They are usually changing companies because a better offer was made to acquire them. These people are self-promoters and highly social. Typically they put their career ahead of almost everything and don't need to look outwardly for motivation to become better at their job. </span></p><p style="margin: 0in 0in 0pt;" class="MsoNormal"><span style="font-size:100%;"><br /></span></p><p style="margin: 0in 0in 0pt;" class="MsoNormal"><span style="font-size:100%;">Again I pose the question, "Who are you?" I see myself as a business developer who has little reliance on employers to drive opportunities for success. If you are or aspire to be in a similar position, then I hope you continue to read these posts and hone your skills as a powerful force in your company.</span><br /><strong><span style="font-size:130%;"></span></strong></p><p style="margin: 0in 0in 0pt;" class="MsoNormal"><br /><strong></strong></p><p style="margin: 0in 0in 0pt;" class="MsoNormal"><strong><span style="font-size:130%;"><br /></span></strong></p><p style="margin: 0in 0in 0pt;" class="MsoNormal"><strong><span style="font-size:130%;">What is Your Value?</span></strong></p><p style="margin: 0in 0in 0pt; color: rgb(51, 0, 51);" class="MsoNormal"><span style="font-size:100%;"><strong><span style="font-size:130%;"><br /></span></strong></span></p><span style="font-size:100%;"><span style="color: rgb(51, 0, 51);">In all of my years in business development, I've learned that one thing remains overwhelmingly consistent...VALUE in the relationship. You must constantly prove your value to the company you work for. Value is the basis for all relationships. If there is no value in a relationship for you, then it is likely that you will leave that relationship. This is true of personal relationships, business relationships and relationships with companies. Providing value in some form is the most important element in developing a client relationship.<br /></span><br /><span style="color: rgb(51, 0, 51);">Both sales and marketing must reinforce and communicate to customers and prospects the value of a relationship with your company. Consistency in communication is a vital ingredient in successfully engaging new customers. Every communication must provide additional value at each stage in the relationship. That value must be delivered even after the close and continually reinforced by front line staff, sales, billing, support and any other department that touches a customer. This value will then be communicated in the form of referrals to potential new customers for your business. The relationships between sales, marketing and operations are all essential to acquiring and keeping customers. Depending on the size of your business, these functions could be consolidated or be very separate departments with a hierarchy of staff for each.</span><br /><br /><p style="margin: 0in 0in 0pt;" class="MsoNormal"><br /><strong></strong></p><p style="margin: 0in 0in 0pt;" class="MsoNormal"><strong><span style="font-size:130%;">Tools of the Trade</span></strong></p><p style="margin: 0in 0in 0pt; color: rgb(51, 0, 51);" class="MsoNormal"><br /><strong></strong></p> <span style="color: rgb(51, 0, 51);font-size:100%;" >Whatever tools you use, make sure that each is consistent with all of your communications with customers and prospects. Social media is considered new and is a great tool for reaching top business professionals in key industries that could be prospects for your business. I believe it is being used incorrectly by even the most recognized and progressive brands. Social media is a great opportunity to stay in front of influencers and decision-makers consistently, but it is also a tool that can be used incorrectly to destroy opportunities to develop future business. More familiar channels such as telemarketing, direct sales, direct mail, trade shows, networking events, email and online are all great, but used without clear direction and inconsistently can do more harm than good and actually damage your program and tarnish your reputation.<br /></span><br /><span style="color: rgb(51, 0, 51);">As my career has progressed, my focus today is with mobile and email. These are great channels for maintaining relationships with customers, especially if your business requires ongoing knowledge of your service or product by your customer base. Maintaining long-term interest by subscribers can be difficult if you struggle to find content. As deliverability becomes more and more difficult to maintain, we are forced into sending to our email database on a regular and consistent basis. Getting ahead of your deployment schedule can be time consuming, but the long-term payoff is well worth the effort. </span><a style="color: rgb(51, 0, 51);" href="">mobileStorm's</a></span><span style="text-decoration: underline; color: rgb(51, 0, 51);"></span><span style="color: rgb(51, 0, 51);font-size:100%;" ><span style="text-decoration: underline;"></span><span style="color: rgb(51, 0, 51);"> <a href="">Digital Marketing Blog</a> is a great resource for developing your email marketing expertise.</span></span><br /><br /><span style="color: rgb(51, 0, 51);">Trade shows can be costly, but they can be effective in driving valuable leads and ultimately business. Standing out at these shows requires creativity, energetic sales reps, gimmicks, materials, expensive booths, planning, travel and other things that cost time and money. Effectively driving leads through trade shows requires planning, budgets and time. </span><br /><br /><span style="color: rgb(51, 0, 51);">For many companies, the tactics above may be luxuries that cannot be afforded. Partnerships with vendors, bypassing the need for booth space and making the most of resources are ways to decrease the expense and increase sales efficiencies. Finding a program that works financially and within the bandwidth of current staff and resources is a focus that I have incredible expertise. Leveraging relationships and planning can give prospects the impression that your company spends large amounts of money on sales and marketing when in fact your company is very cost-effective in its efforts.</span><br /><br /><br /><span style="font-size:130%;"><span style="font-weight: bold;"><span style="color: rgb(51, 0, 51);">Moving Ahead </span><p></p></span></span><span style="color: rgb(51, 0, 51);">As we move ahead, I want you to make your own decisions. Take a look at my background on</span> <a href="">LinkedIn</a>. <span style="color: rgb(51, 0, 51);">Follow me on</span> <a href="">Twitter</a>. <span style="color: rgb(51, 0, 51);">Even this blog is meant to drive lead generation. If you feel that I am practicing what I preach, then participate with me. Leave comments, ask questions and reach out. I am happy to take criticism, listen and share ideas. Stay tuned for the next post.</span><br /><span style="font-weight: bold;"><br /></span><img src="" height="1" width="1" alt=""/>Darren Withers Casinos by Storm in 2010<strong><span style="font-size:180%;">Marketing, Money and More (<em>Issue 10)</em></span></strong><br /><em></em><br /><p style="margin: 0in 0in 0pt;" class="MsoNormal"></p><p style="margin: 0in 0in 0pt;" class="MsoNormal"><strong><span style="font-size:130%;">Revelation</span></strong></p><p style="margin: 0in 0in 0pt;" class="MsoNormal"><strong><span style="font-size:130%;"><br /></span></strong></p><p style="margin: 0in 0in 0pt;" class="MsoNormal">I had a revelation that I thought my readers would want to hear. As the newest part of the <a href="">mobileStorm</a> team, I need to know what it is that I am selling. Up until recently, company efforts centered a ton of focus around the SMS platform. I think that is due to the overwhelming response by marketers to step into text messaging in 2010. In 3, 5 or even 10 years, SMS could die and another channel will take its place as the primary channel for mobile devices. I think we are just misnaming what it is that marketers are trying to grasp. It is something with longevity and based on a relationship between man and his ability to interface with the rest of the world from anywhere. The “cell phone” represents a gateway to what all of us crave…interaction with other people, access to knowledge, entertainment, help, etc.<br /></p><p style="margin: 0in 0in 0pt;" class="MsoNormal"><br /><"><span style="font-size:130%;"><strong>A Pair of Golden Handcuffs</strong></span></p><p style="margin: 0in 0in 0pt;" class="MsoNormal"><span style="font-size:130%;"><strong><br /></strong></span></p><p style="margin: 0in 0in 0pt;" class="MsoNormal">There is a relationship between this device and the person using it. The vast majority of us cannot live without our cell phones and that addiction is very deep with those of us that have smart phones. Focusing on this relationship between a device that provides this gateway and the individual is what was just recently discussed at a panel discussion on social media at the <a href="">Global Gaming Expo (G2E.)</a> Troy Simpson, Director of Innovation for <a href="">Barona Casino </a>spoke on this very subject and called this relationship “a pair of golden handcuffs”. He said more money will be spent on harnessing the power of"><br /></p><p style="margin: 0in 0in 0pt;" class="MsoNormal">With all this said, I will be out there positioning <a href="">mobileStorm</a> as the partner that can help casinos and other relevant companies master all of the facets of the this relationship and provide a way for them to intervene and participate in a meaningful way. This presentation of mobileStorm’s role with respect to clients reaching their customers provides a “timeless” ability in specializing in connectivity with each client's respective target audience in a truly one-to-one way. For now we are focusing on SMS as the application by which mobileStorm can be a valued partner. With this thought process, voicemail and email become very relevant channels in this mastery. As more services and platforms are created and others go away, we will always be the experts in managing"></p><p><strong><span style="font-size:130%;">Palms Players Club SMS Campaign</span></strong> </p><p><span style="font-family:georgia;"><span style="font-size:100%;">Over 7 days mobileStorm teamed up with the Palms Casino Resort to demonstrate a wholeistic understanding of a relationship between a casino gamer and their mobile device. We demonstrated a campaign that uses the mobileStorm's SMS platform to manage this relationship in a beneficial way to a casino. This “test” was intended to drive players club sign-ups. The campaign ran live at G2E from November 13 thru November 20. Casino professionals from all over the US got to watch it unfold. The campaign featured the following elements at the Palms:</span></span> </p><ul><li><span style="font-family:georgia;">Free Standing Posters</span></li><li><span style="font-family:georgia;">Slot Bank End Caps</span></li><li><span style="font-family:georgia;">Elevator Posters</span></li><li><span style="font-family:georgia;">Television Screens near Club Palms and the Front Desk</span></li></ul><p style="margin: 0in 0in 12pt;" class="MsoNormal"><span style="font-family:'Calibri','sans-serif';"><span style="font-family:georgia;">The campaign was also implemented on 7 bus stop shelters at key locations on the Strip provided by <a href="">Outdoor Promotions</a> with two (2) :15 video animations running on 70” plasmas within 10 minutes of video content for maximum frequency. The centerpiece of the campaign was a 3D Screen provided by <a href="">Magnetic 3D</a> which had a special lens on a 42” plasma that merges 10 moving images simultaneously to create and unbelievable 3D effect without the need for special glasses. The 3D screens were placed in front of the valet entrance at the Palms to engage people walking into the property. Inserts (4” X 5”) were placed in cars at valet as well to catch those leaving the property. </span></span></p><p style="margin: 0in 0in 12pt;" class="MsoNormal"><span style="font-family:'Calibri','sans-serif';"><span style="font-family:georgia;">The offer was high-value; a New Year's Eve weekend with Maroon 5. Once people have opted in to win the New Year's Eve package, they received a series of offers until they headed to Club Palms to sign up and redeem. The text offers deployed were progressively better and better over 72 hours. The strategy mimicked the excitement and anticipation of "Deal or No Deal". The offers were very aggressive in terms of attracting players and were tracked using unique keywords for each medium utilized in the campaign. The campaign ran from the Thursday prior to G2E (11/12) until the folloiwng Thursday (11/19) to give the test weekend traffic numbers. </span></span></p><p style="margin: 0in 0in 12pt;" class="MsoNormal"><span style="font-family:'Calibri','sans-serif';"><span style="font-family:georgia;">mobileStorm managed the entire campaign including the production of animation through strategic partners (mobileStorm, Outdoor Promotions/Posterscope USA, <a href="">Environmental Ink</a>, etc.). All of this was FREE for this test except for the printing which Environmental Ink helped to control costs for those relevant items listed above. A cost per acquisition model will be derived from this campaign. <o:p></o:p></span></span></p><p style="margin: 0in 0in 12pt;" class="MsoNormal"><span style="font-family:georgia;">We are experts at delivering messaging to mobile devices and providers of the tools and knowledge to do so. This ideology gives mobileStorm “lasting power” and will position us to lead the industry well past the existence of SMS. If you would like to hear about the results or learn about an upcoming test campaign with an "unannounced" casino partner on the Las Vegas Strip, please feel free to shoot me an <a href="mailto:email....darren@mobilestorm.com">email....darren@mobilestorm.com</a> or check out mobileStorm's <a href="">Digital Marketing Blog</a>. </span></p><p style="margin: 0in 0in 0pt;" class="MsoNormal"><o:p><span style="font-family:georgia;"></span></o:p></p><p style="margin: 0in 0in 0pt;" class="MsoNormal"><span style="font-family:georgia;"></span></p><img src="" height="1" width="1" alt=""/>Darren Withers Death of the Mid-Size Agency and The Birth of Giants<strong><span style="font-size:130%;">Marketing, Money and More (<em>Issue 9</em>) 11/30/08</span> </strong><br /><br /><br /><strong>The New Economy</strong><br />Value is the name of the game in a recession. If a company cannot provide high value, then it will not survive through 2009. Our economy has been crippled to the point where even OPEC is vulnerable.<br /><br /><strong>Jumping the Curve<br /></strong>Guy Kawasaki (managing director of Garage Technology Ventures, an early-stage venture capital firm and a columnist for Entrepreneur Magazine. Previously, he was an Apple Fellow at Apple Computer, Inc.) speaks of a concept of "jumping the curve." long and short of it is that companies often fall victim to success and don't invest in the next evolution of their industry. One example Guy uses is the business of keeping food cold. Originally people had to go up to high altitudes to get ice for storing food. Then factories began to produce ice and delivered it to customers. Finally we had the home refridgerator which could freeze ice, eliminating the need for delivery. No one company survived all three stages of this evolution. Prior businesses died out and a host of new businesses emerged at each stage of the evolution. The moral is that your business is relevant one day and can lose relevance if you don't pay attention.<br /><br /><strong>The Death of the Mid-Size</strong> <strong>Agency</strong><br />Evolution just got a helping hand from a poor economy. Mid-size branding firms/ad agencies (30 -100 employees) thrived in the booming economy. Now faced with reduced budgets and an economy in recession coupled with a boom in online and mobile communications and you get a recipe for big change in the industry.<br /><br />Not only is there an increased focus on online, but there is a resurgence in popularity of grass-roots strategies. Traditional agencies are falling victim to a lack of preparation and vision. Big broadcast buys (an area where traditional firms earn big commissions) will be scarce for the mid-size agency in 2009. Any medium that cannot be held accountable for every dollar in terms of ROI will be highly scrutinized by clients and perhaps eliminated from the budget completely.<br /><br /><strong>Agency "Best" Practices</strong><br />In case you were not "in the know" on common agency billing practices, then let me shed some light on what additional fees can be in your billing without your knowledge:<br /><ul><li>Production Management Fee - Usually 10% - 25% mark-up on all items not handled in-house (i.e. printing, subcontractors, production, etc.)</li><li>Media Commission - As a standard, media outlets have offered agencies a 15% commission for purchasing media. As time goes on , these agency discounts or commissions have been given directly to businesses and are much more well-known than years past.</li></ul><p>These practices are more about "hoping the client doesn't notice" than a justifiable accounting. I have witnessed a client pay an additional $12,000 because they allowed their agency to print a direct mail piece that cost $2,500 in creative fees to create. This was a $90,000 mailing with 45,000 pieces. Had the client known, they never would have agreed to the mark-up. </p>Those firms that highly specialized, adapted to new technology and stayed flexible with their fee structure will have the best chance for survival.<img src="" height="1" width="1" alt=""/>Darren Withers Down the Barriers to Online<strong><span style="font-size:130%;">Marketing, Money and More (<em>Issue 8</em>) 8/24/08</span> </strong><br /><br /><br /><strong>Websites</strong><br />There is a lot of "old school" mentality in terms of online. I have met very few small to medium-size business owners that are very active in generating leads online. Many business owners know they need a website, but they don't know what type of website, how much they should spend on their website, what type of coding will be used and is most beneficial, etc. There are a million questions when it comes to web and it is hard to write a check for something that you don't fully understand.<br /><br />The first place to look is at your competition. What does there website do? How does it look? Is it easy to find on <a href="">Google</a>, <a href="">Yahoo!</a> and <a href="">MSN</a> with relevant searches? If your competition is doing well in capturing leads online, that may just mean that no one is challenging them. They may be doing their online marketing very poorly, but everone in their space is doing it worse.<br /><br />This lack of competive force in many categories in terms of online marketing and <a href="">Search Engine Marketing</a> (SEM) is a great opportunity for many businesses.<br /><br /><strong>Search Engines & SEO</strong><br />Google is changing the way we find information. Google is built on one basic premise... getting us to build better, more relevant websites. Google's job is to match up information-seekers to information, not to control the flow of customers to marketing websites. With this in mind, the medium is defined. "Value" is what it is all about. Build an information-rich, website that provides loads of perceived value for your customers and Google will reward you greatly, organically.<br /><br />Read a few articles on <a href="">Search Engine Optimization</a> (SEO) and search engines. There are more than you can ever possibly read, but they will open the online world up to you. Of those that search online, about 65% use <a href="">Google</a>, 22% use <a href="">Yahoo</a>! and 13% use <a href="">MSN</a>. Knowing this, you can see why so much emphasis is put on Google when we talk about Search Engine Marketing (SEM), <a href="">Search Engine Optimization</a> (SEO) and <a href="">Pay-Per-Click</a> (PPC). We play up to the 800 pound Gorilla, not the 100 pound Orangutan.<br /><br /><strong>The Myth</strong><br />SEO is a function of building a website correctly from the beginning. If a website is carefully planned and well executed, it can be the life blood of a business. Anyone that says, "I can guarantee you a top spot on Google." or, "We have great relationships with <a href="">Google</a> and <a href="">Yahoo</a>! which will help with your SEO." is full of it! These tactics are used on those that don't understand web and are misinformed on how <a href="">search engines</a> work.<br /><br />If you ever see these claims, beware! These companies will sometimes mask <a href="">Pay-Per-Click </a>campaigns as <a href="">Search Engine Optimization</a>. The two are completely different. <a href="">Orgnanic</a> (being indexed highly by <a href="">Google</a> in relevant searches without paid placement) is much more valuable than paid placement which is based on a bid system. Only between .04% of people searching click thru paid search on <a href="">Google Adwords</a>. This may improve from the 0% you had before you started, but it is not true SEO and don't be fooled.<br /><br />These are companies that likely employ dishonest practices such as <a href="">link farming</a> and masking keywords behind images. Here are some good questions to ask these companies:<br /><ul><li>How do you "guarantee" top placement and in what searches are we talking about (only so many searches are relevant to your business and there are services that can show search traffic for every key phrase typed into Google)?</li><li>What type of practices do you employee for SEO? Do you employ pay-per-click campaigns or do you concentrate on organic placement?</li><li>What are you quality control measures to ensure ethical practices to avoid "blacklisting" by Google and other search engines?</li><li>Can I get a list of references and see a few case studies?</li></ul><p>These questions should communicate that you know your stuff, at least enough not to be taken in by the first shark you talk to. Look at all the things we asked for above. Write out your objectives for your website and ask the prospective company to address each of them. Give people a fair shake at convincing you, but at the end of the day, it is your decision. </p>Without going into a full dissertation on web design, there are standards that have been developed. Addressing meta tags, title tags, keyword density and more will give any website a good shot at being indexed highly with google. The big win is working with other sites that are relevant to the key terms you are optimizing for and getting them to link to your site without giving them anything in return (money or a reciprocal link). Google sees your site as relevant to a topic when other relevant sites link to yours. Working with seasoned web designers and marketing strategists will give you an edge over a competitor. If this edge means that hundreds more people searching for your product or service find you before your competition, then it will be worth it.<br /><br /><strong>Standards & Practices<br /></strong>Just like reading from left to write is a standard for writing literature, having topside navigation is a standard for web. Adhereing to standards creates less confusion, frustration and clearly maps out the user experience leading them to what you ultimately want them to do. What is it you want them to do? Book a room, buy a toy, call, email, give you their information. Many sites have every option imagineable so that there is no clear direction when getting to the site. This is not done on purpose, but done out of fear. Decision-makers get so entrenched in not wanting to lose any client, that they dilute their ability to capture anyone in a decisive manner. The more vague and homogeneous the site, the less effective it will be in converting customers.<br /><br />Do the homework, adhere to standards and create a clear path for a group of people you have the best shot at capturing and success will follow. Try to be everything to everyone that may happen upon your site and be burried with the rest.<br /><strong></strong><br /><strong>CMS vs. Outsourcing</strong><br />I've had some confusion with clients saying that they want to be able to make edits to their website once it is designed. This is called "Content Management." A site can be built with a Content Managment System (CMS) which gives the customer the ability to make edits to text and pictures in pre-determined areas of the site that need to be changed often. The problem lies in aesthetics. The CMS creates a challenge in terms of design. The CMS will lock the site into a framework that cannot be changed. The amount of text and size of images needs to be standardized and we lose the ability to be creative in these areas of the site.<br /><br />The alternative is to have the web designer make all changes. This can be expensive if there are changes consistently. An emphasis on quality would dictate that changes are outsourced and an emphasis on budget would dictate the latter. It is really a compromise between the two. Content manage those areas that make sense and re-employ a web designer to make bigger changes.<br /><strong></strong><br /><strong>Viral</strong><br />I have heard more directors and vice presidents of marketeing say, "We need to do some viral marketing." The fun part is that they say this as if it is something that happens when you spend money on it. Viral is just as it sounds. Viral marketing is based on the premise that you will "pass around" something of your own free will without being paid and that a majority of a segment will do the same. The thing about viral is that it must be one of the following:<br /><ul><li>Funny</li><li>Weird</li><li>Gross</li><li>Shocking</li><li>Helpful</li><li>Sexy</li><li>Inspiring</li><li>Novelty</li></ul><p>If your idea for a viral online campaign is anything short of the descriptors mentioned, scrap it. If your company is so tight that it could never let communications that may be taboo or slighly edgy slip through, then viral is probably not a viable tactic. Viral speaks on behalf of the person sending it. It speaks to their personality, kind of like a greeting card. If I send something to a friend, you can bet it is borderline offensive, sexual or at least give them a chuckle. Why would I pass around an ad for $.50 off of detergent. I wouldn't and neither would you. Packaged differently, a homeless man bathing naked in a park fountain with a funny tie in at the end saying, "He could have used $.50 off detergent!" might be viral enough to pass around if it is presented correctly. Viral is about pop culture not contrived and choreographed ad messages. </p><p>Going viral is a marketers dream. You may have noticed some of these off-the-wall commercials for candy lately. These attempts at being "weird" are attempts at going viral. The Starburst commercial on my <a href="">YouTube</a> page has gotten over 6 million views...for free. Starburst didn't have to pay for the extra 6MM impressions. Good for them.<br /><br /><strong>Email<br /></strong>For any company that has cut a check for $10,000 or more pretty regularly in direct mail campaigns is very interested in moving their customers over to email. This effects the bottom line immediately. Just like with search engines, Email Service Providers play a big role in gatekeeping. </p><p>AOL is the big player here. Treat them like gold. A long time ago, email marketing was like the wild wild west. AOL had a lot of users. As more marketers began to take hold of email marketing, AOL noticed users drop off because they were being inundated with email from marketers. AOL fought back and began gatekeeping, penalizing spammers for abuse. Whitelisting was born. Whitelisting means that you promise Email Service Provider's (ESP) like AOL that you will adhere to their rules and standards when marketing to AOL users, even with their permission.</p><p>AOL is the toughest, but when email marketing is done right, this can be your most responsive group. Whitelisting is important. If you are sending your bulk emails through a third party, you will want to know their whitelisting status with the major ESP's like AOL, Gmail, MSN Hotmail and Yahoo!. Each has their own standards and as you build an email marketing history, you will build report with each. </p><p>"Opt-In" is the word of the day. If you send emails, all of your recipients must be opted in. This means that they explicitly gave you permission to send them offers. The <a href="">CAN-Spam Act</a> clearly outlines the legalities asssociated with email marketing, but the premise is that if someone does not give you their permission to market to them through email then you cannot send them commercial email.</p><p>Messaging and offers also play a big role in email marketing. The message must get attention and have a clear call to action. The balance between deliverability and aesthetics will always be an issue. Everything that makes an email visually appealing usually inhibits its ability to successfully make it to the target's email box. <a href="">mobileStorm</a> is a veteran in the email marketing space. More than just a provider, mobileStorm employs a Vice President of Deliverability whose job it is to maintain a relationship with each ESP. This relationship results in something called "whitelisting" which gives a stamp of approval for email marketers to email subscribers of some of the most popular ESP's. With so many changing considerations, it is smart to work with a responsible email platform. </p><p>An email database is worthless if the people in it don't want to receive your messages. I've seen clients start with 60,000 plus records and after an opt-in campaign was conducted, the list was reduced to 2,500 opted-in participants. The client in this case adamantly emailed all 60,000 records without their permission as we marketed to only the 2,500 opted-in recipients on their behalf. Needless to say, our efforts out-performed the client's SPAM effort. This is the difference between a "Database" and a "Working Database." Is your database "Working?"</p><p><strong>India or Bust</strong><br />I received a call from India the other day asking about my website. The gentleman proceeded to tell me that his company could guarantee top ranking in search engines and was prepared to take on our website at a nominal fee. All the red flags were raised and I hit them with the hard questions. At the end I said I was not interested, but I could see how the pitch would be enticing to a business owner.</p>Many things these days can be done for cheap. I have heard, "Why would I pay $5,000 or $10,000 to get a website designed when I could pay $300 like I've seen advertised online." Odds are pretty good at a $300 price tag you are getting a basic site that is a "template" and will have little to no customization based on your business objectives and the needs of your customers which may not allow you to reach your full sales conversion potential. It is also safe to assume that these companies will not address SEO concerns on the front end. What you may end up with is a pretty basic website that does about 5% of what it could potentially do for your business. If you are serious about using online to improve your business, I would suggest talking to a professional. Email me if you need one.<br /><br /><strong>Getting Offline</strong><br />This is just the beginning. I could have done a separate blog on each section written here, but I just wanted to touch on the hot buttons and push for participation. Email is intriguing and online marketing changes daily. It is a full time job to keep up and not something a business owner and operator usually does well. If you need advice, email me or for info on email marketing visit <a href="">mobileStorm's website</a>.<br /><br />Thanks for taking the time to read my blog! Comments?<img src="" height="1" width="1" alt=""/>Darren Withers Power of Appreciation<strong><span style="font-size:130%;">Marketing, Money and More (Issue 7) 6/28/08</span> </strong><br /><br /><strong>Never Expect</strong><br />There is one great thing about the terrible disease of alzheimer's, the ability to feel apprectiation for something as if it is the first time something has been done for you. Although the analogy is a bit gruesome, the message is that gifts and favors should never be expected. The favor easily turns into "work" for the person that is giving when appreciation is taken out of the equation.<br /><br />By the same token it is not healthy to do favors or give gifts for the feeling of "self worth" or "esteem". This is where your internal power comes into play. When your self-esteem is derived from being a source of dependency for others, you become what is traditionally known as a "care-taker." This is a co-dependency issue that requires couseling. (I may have had a bit myself.)<br /><br /><strong>Lash Out</strong><br />It is your responsibility to communicate and set boundaries. When you feel taken advantage of, let people know, but don't wait until you are drunk or angry... This is an obvious recipe for a worse scenario. It may make more sense to wait until you have a bit more of your senses about you. (Again, this is something I may have experience with.)<br /><br />Boundaries are communicated not imposed. Make sure you tell people when they have crossed your philanthropic line. If you don't they will think that you enjoy making them happy and will no longer be apprehensive about asking for things. Say "No" every once in a while, even when you really do want to do the favor. Break the cycle.<br /><br /><strong>Set the Stage</strong><br />I've been out on dates where I've broken the bank at a nice restaurant and paid for a big Strip show...It sets you up to be a wallet for the other person. You have started the relationship out on an expensive note. You cannot build up to anything. Have you ever had a girl have the audacity to ask you if she could borrow money after 3 dates? Not good. Of course I said, "No." It is very interesting to me what girls will ask for. Apparently it worked on someone else.<br /><strong></strong><br /><strong>Value</strong><br />Much like in business, it's all about value. Do people value you and what you do? Do you value yourself. Who's job is it to communicate that value? Everyone has a responsibility to tell the people that they help and give to what went into that favor. If the relationship is mutually beneficial, the other will go out of their way to a similar extent in the future. Relationships must be fair and balanced to make sense. Will your friends go to the ends of the Earth for you? Will you do the same? Will you be the one to carry them to the ends of the Earth? For some people it is only important that their friends made the trip with them, not that they shared the workload.<br /><br />The more you give without compensations, the less others will value it over time. It is human nature. Keep people on their toes. Command respect and recognition. Express when you feel taken advantage of and, most importantly, show the same respect for others...<br /><br /><strong>Thanks A Lot!</strong><br />I worked for a <a href="">charity</a> and the one lesson I took away was to always say "Thank you." People like to do things for others that APPRECIATE them. "Thank you" is a very powerful set of words. If you remember to say it after every selfless act, favor, gift and even when nothting happens you communicate that you recognize the efforts of others and are appreciative of what has been done for you. There is nothing worse that you can do in the non-profit world than to forget to thank a donor. They will never, ever forget and it can be enough to send them to another charity that does appreciate them.<br /><br />This little bit of advice will help you in all aspects of your life. Business relationships are centered around mutual benefit and appreciation.<br /><br />If you take one thing away from this post, please say, "Thank you!" to everyone that you appreciate. It is not always implied or assumed and it is nice to hear.<br /><br />Thank you for reading this post!<img src="" height="1" width="1" alt=""/>Darren Withers Forward<span style="font-size:130%;"><strong>Marketing, Money and More (<em>Issue 6</em>) 2/10/08</strong></span><br /><br /><br /><strong>Skip It</strong><br />All this talk of <a href="">recession</a> is making people think more about "<a href="">recession</a>." As we further and further promote the idea of <a href="">recession</a>, the general public will act in a manner that they think will get them through the <a href="">recession</a>. Save money, spend less, pull out of the stock market, sell your home. This is perpetuating the problem. The power of perception is strong.<br /><br />Consumer spending is down and foreclosures are on the rise (especially in Nevada - #1 in the country.) This economic downturn is expected to worsen into the summer of 2008. The government is trying to stimulate the economy going into a very important political year with a tax rebate of $300 - $1,200 for Americans. This will help, but to what extent. We need a mind change.<br /><br /><strong>Think Growth</strong><br />It is worse to think gloom and doom. Think of your every day life. When you think negatively about your situation it tends to get worse. It's the <a href="">Law of Attraction</a>. That is what <a href=""><em>The Secret</em> </a>is based on. The power of your thoughts to influence your environment. If we could unify the thoughts of the many to stimulate positive activity, then the economy would follow.<br /><br />Think of value. People provide value to society in many forms. I provide value to society when I took the time to sit on the board of my local <a href="">American Advertising Federation</a>, buy a friend a coffe or get up 10 minutes earlier in my day to sort the recyclables. My contributions have an economic impact. If a million people get out and buy a coffee for someone, that is an increase of $1.5 million in consumer spending over the course of a day.<br /><br /><strong>The Experiment</strong><br />You've seen tons of these types of emails. "Don't buy gas today! It will spur a price war between the gas stations and that will help to bring gas prices to a manageable level." I think that requires too much participation from too many people. It sounds logical, but humans are emotional and these attempts to influence the public don't take into account the impracticality of not buying gas for a day.<br /><br />I would like to start by being realistic. I would like to challenge a few people I know each month to do something that they wouldn't normally do as we head into tough economic times. If we can produce high levels of value in 2008, the economy will follow. Here are a few suggestions:<br /><br /><ol><li>Buy someone a <a href="">coffee</a></li><br /><li>Volunteer time at a <a href="">charity</a></li><br /><li>Join a trade <a href="">association</a></li><br /><li>Buy a <a href="">toy</a> for a friend's/family member's child</li><br /><li>Give someone a ride</li><br /><li>Stay an extra 10 minutes at work each day (productive minutes)</li><br /><li>Sell/buy something on <a href="">ebay</a></li><br /><li>Write a <a href="">blog</a></li><br /><li>Share success</li><br /><li>Register to vote</li></ol><p>I know this sounds like a movie...<em><a href="">Pay It Forward</a></em>. Well, I'm not <a href="">Haley Joel Osment</a>. The principle is sound. Do something for someone else that provides a value. If you own your own restaurant business, buy someone's meal tonight. If you have a tool that a neighbor needs, offer it. Find a <a href="">charity</a> that you have an interest in and ask them how you can help. </p><p>I am starting with myself. I am going to make an effort and lead by example. I have already begun. I will do more with my time in 2008 to provide value to myself and society and push through this period of recession. I hope this blog is one step toward eradicating what could potentially be an economic downturn. It is about reconfiguring resources. If you have a resource and have the ability to share with those that do not, you will be helping yourself in the long run. This will stimulate spending, goodwill and social activity. </p><p>Today and each month after, I will be sending out an email to close friends and business people to persuade them to do anything that is beneficial to someone else and society. Mobilization of those that have the energy and resources to make an impact, even just a small one. If you read this, please send out an email to your close friends asking them to do the same. </p><strong>The Email</strong><br />"Hey. I'm urging everyone to get involved. In 2008, times will be tough... or will they? If you can do something extra such as help a charity, spend a few extra dollars for someone else, help a friend or do something that creates some sort of value, we can help curb some of the impact of the recent economic trends that lead to a recession. Please forward this message on to a friend and keep the string going. This is not chainmail, but if we can "make change" now we won't have to wait for <a href="">Obama</a> or <a href="">Hilary</a> to get into office. Write down what small thing you can do extra this month on a post-it and put it somewhere on your desk. Don't take it down until you've done it. Once it's done, write on another <a href="">Post-It</a>. Do this all throughout 2008 and you can look at all the <a href="">Post-Its</a> that you've been able to accomplish. I want to get "<a href="">Post-It</a>" to construct a page where people can post "<a href="">Post-It's</a>."<br /><br /><p>Feel free to use this and pass it on.</p><img src="" height="1" width="1" alt=""/>Darren Withers'll Have What Their Having<span style="font-size:130%;">Marketing, Money and More <em>Issue 5 </em>(1/21/07)</span><br /><br /><br /><strong>What Worked Yesterday...</strong><br />I don't believe it when anyone says, "It's been done before." If it's been done before and it works for your brand, go with it. A smart person takes the best practices of their industry and reskins it for their business. What worked yesterday, might not work today, but it could work tomorrow. Never forget to test.<br /><br />Have you ever gotten an annoying <a href="">telemarketer</a> and wondered who would ever buy something from a person you talked to on the phone? Me too. But...If it did not work, companies would not spend money on this relatively expensive tactic. It works.<br /><br />I've worked with several casino properties here in <a href="">Las Vegas</a> and around the country. There are only so many ways you can do a slot tournament, poker tournament or other gaming event. It is the same promotion at every casino. They do them because they work.<br /><br /><strong>Testing, testing...</strong><br />I have spoken with many businesses. They come to firms or agencies looking for the guarantee. That does not exist and if your firm ever guarantees you anything, call them liars and find a new agency. A guarantee would assume that they have some sort of mind control or psychic ability. All a firm can provide is knowledge of what has worked for a similar customer and the ability to analyze information to make the best decision on the client's behalf. It is a game of knowing what the market is doing, what the competition is doing and breaking throug the clutter.<br /><br />Test everything and give it a chance to work. If you decide that <a href="">direct mail</a> is right for your business, test it. Put together a campaign with a small list based on the attributes of your current customer or at least who you think might be your customer. Do an A/B Split. This test will tell you what sort of offer is most likely to get your target group through your doors. Once the offer is perfected, work on the creative. Does a postcard outperform a letter? Does increasing the size of the call to action make a difference in response?<br /><br />Testing can and should be done for as many tactics as you can test in your marketing mix. Branding is the exception. You can test how well you are branding your company, but it is very expensive and may not be justified in your industry. Not every business is <a href="">Nabisco</a> with multi-million dollar budgets. It makes sense to spend $70,000 on market research when you are making a decision that could cost you $5 million.<br /><br /><strong>They Did It, So I Gotta Do It</strong><br />The car dealer industry is notorious for this mentality. They are all on <a href="">TV</a>, <a href="">Radio</a> and <a href="">Newspaper</a> trying to scream louder. Each is so affraid to step away from traditional media that they never try anything new for any decent amount of time. I have had a car dealer tell us so desperately how much they wanted to explore "outside the box" thinking (a term which has come to mean nothing due to overuse.) If everyone is outside the box, you might want to be in it.<br /><br />Many businesses tend to look at what their competitor is doing and use that as the sole basis for their decisions. Competitive knowledge is good, but sound research and strategy is better. You may find out that your competitor is not being as effective as they could be and you'll just be adding to that waste.<br /><br /><strong>Media Reps Are Good People, But...</strong><br />A rep for a media outlet is not a bad person and most are very knowledgable. They have only one fault. They are looking out for the interests of their outlet and obtaining as much of your budget as possible. It is not always in the best interest of your business. The rep is doing their job and hopefully going above and beyond to show the value of what their outlet may provide. This is where the consultant or firm comes in. We study them with all of our tools and metrics and make them work to prove value beyond what our resources tell us. It is a win for the client because they are not talked into spending an inappropriate amount of their budget with a single outlet. Rarely is one medium appropriate for a client. It may be a start, but not the most effective mix.<br /><br /><strong>Competition is Good</strong><br />All in all, competition is good. It is what makes for great branding, keeps companies honest and makes us all a bit smarter. In the end, the customer wins because we tend to create more value when we are engaged in competive marketing. I would love to hear if anyone has a case where following the competition proved to be the right strategy.<img src="" height="1" width="1" alt=""/>Darren Withers Begins<span style="font-family:trebuchet ms;font-size:130%;">Marketing, Money and More <em>Issue 4</em> (1/7/07)</span><br /><span style="font-family:trebuchet ms;"></span><br /><span style="font-family:trebuchet ms;"></span><br /><strong><span style="font-family:trebuchet ms;">A Little Personality Goes a Long Way</span></strong><br /><span style="font-family:Trebuchet MS;">I've had lots of first contacts with business owners. Their problems always seem so obvious to me. In this day and age, it takes more than the ability to cook to run a restaurant, more than slot machines to run a casino and more than good taste to sell soda. We've gone well above "basic needs" and we are feeding our emotional needs. We are all consumer addicts looking for that next emotional fix. </span><br /><span style="font-family:Trebuchet MS;"></span><br /><span style="font-family:Trebuchet MS;">We get validation from jeans, attitude from the beer we drink and our sense of humor from insurance companies. None of it makes sense. Take the logic of this scenario:</span><br /><br /><ol><li><span style="font-family:Trebuchet MS;">I need clothes</span></li><li><span style="font-family:Trebuchet MS;">I search for clothes</span></li><li><span style="font-family:Trebuchet MS;">I compare price and quality of clothes</span></li><li><span style="font-family:Trebuchet MS;">I buy clothes</span></li><li><span style="font-family:Trebuchet MS;">I wear clothes</span></li></ol><p><span style="font-family:Trebuchet MS;">Each step is logical. We fulfil our need for clothes with a quality product at a good price. Now suddenly we throw emotions into the whole thing and it all gets complicated. Now we have a new scenario:</span></p><ol><li><span style="font-family:Trebuchet MS;">I need clothes</span></li><li><span style="font-family:Trebuchet MS;">I search for clothes</span></li><li><span style="font-family:Trebuchet MS;">I see a person I want to be like wearing ripped, faded jeans with paint splatters</span></li><li><span style="font-family:Trebuchet MS;">I see the girl I like with the person that I want to be like</span></li><li><span style="font-family:Trebuchet MS;">I find the overpriced, ripped, faded jeans</span></li><li><span style="font-family:Trebuchet MS;">I pay too much </span></li><li><span style="font-family:Trebuchet MS;">I wear clothes</span></li><li><span style="font-family:Trebuchet MS;">I feel like the person I want to be like for a short while</span></li><li><span style="font-family:Trebuchet MS;">The girl I like is still with the person I want to be like</span></li><li><span style="font-family:Trebuchet MS;">I need more clothes</span></li></ol><p><strong><span style="font-family:Trebuchet MS;"></span></strong></p><span style="font-family:Trebuchet MS;">It's called <a href="">emotional branding</a>. </span><br /><br /><strong><span style="font-family:Trebuchet MS;">To Brand or Not to Brand</span></strong><br /><span style="font-family:Trebuchet MS;">I've found that a good product will only go so far</span> <span style="font-family:trebuchet ms;">if there are comparable substitutes. Once the competition enters the market and the differences in your product or services become indistinguishable, customers rely on their emotions to make a choice. "Which do I like better?"</span><br /><span style="font-family:Trebuchet MS;"></span><br /><span style="font-family:Trebuchet MS;">This is where branding comes in. Rely on society's need to fit in, need to stand out, need for status... We are emotional beings and to the detriment of our bank accounts. We move from one branded experience to the next and marketers have caught on to our weakness.</span><span style="font-family:trebuchet ms;"> The book <a href=""><em>Brand Hijack</em></a> covers what happens when society shapes the brand such as in the case of <a href="">Dickies</a> or <a href="">RedBull</a>.</span><br /><span style="font-family:Trebuchet MS;"></span><br /><strong><span style="font-family:Trebuchet MS;">Branding Begins at Home</span></strong><br /><span style="font-family:Trebuchet MS;">Most small and medium businesses look to ad agencies to solve their problems. <a href="">Ad agencies </a>tend to look at a brand as the perception of the business that they can create in the public eye. I believe branding begins a bit deeper. Healing begins inside. Here's an example:</span><br /><br /><ul><li><span style="font-family:Trebuchet MS;">I met with a restaurant owner a few years ago. He had a Mediterranean Restaurant attached to a small market. He explained the cuisine and that the restaurant was very slow. I spoke with him about what PR could accomplish, what print ads could accomplish, direct mail and so on. He told me to come in and try it out. I took a lady friend of mine and we met there. We came in and sat...and sat...and sat and after five long minutes, a very quiet server came to the table. She gave us menus, took our orders and didn't really say much and walked away. We waited for a while. The food shows up after about 25 minutes. Mind you we were the only other table in the restaurant besides an older couple already eating their food. We finished and were not asked about dessert and were presented with the check. I will say that the food was good.</span></li></ul><p><span style="font-family:Trebuchet MS;">The moral of the story is that I told the owner that there was nothing that marketing could do for him. All marketing would do is encourage people to come in for bad service so that they can tell 10 other people how bad it was. <a href="">Dick's Last Resort</a> can get away with that because they've built a brand around bad attitudes in their service.</span></p><p><span style="font-family:Trebuchet MS;"></span></p><p><strong><span style="font-family:Trebuchet MS;">The Customer Experience is King</span></strong><br /><span style="font-family:Trebuchet MS;">Your brand begins with the owner or president. Once decisions are made about the customer experience, and preferably one that will lead to a profitable business, then the brand can be communicated. Branding has foundations in <strong>consistency</strong> in customer experience and <strong>management</strong> of customer expectations. Your service can be bad if it is part of the experience that you are selling. Your product can be average if that's what you are selling. If you claim to cater to a particular segment such as gay couples, your staff better buy into that. It's called a <em><a href="">Brand Promise</a></em>. </span></p><p><span style="font-family:Trebuchet MS;">The best brand experiences can be found right here in Las Vegas. Each experience is coreographed down to the way staff members point to the bathroom. Themes are eveywhere. <a href="">The Hard Rock Hotel & Casino Las Vegas</a> hires young men and women that fit the profile. Tatoos, hair and attitude. Yes, it's even down to the hiring. </span></p><p><span style="font-family:Trebuchet MS;"><strong>Just Start at the Beginning</strong></span><br /><span style="font-family:Trebuchet MS;">Before you run out to find an ad agency you may want to evaluate your customer experience. Do my customers enjoy the experience we provide? Are the sales staff of the same attitude and corporate culture? Are employees empowered to do their job?</span></p><span style="font-family:Trebuchet MS;"></span><br /><span style="font-family:Trebuchet MS;">Speak to your customers on a regular basis and ask them what they like and don't like. This can provide great insight into what you are doing right and what you are likely doing wrong. Take notes and try to put some words to what you think your brand is. Even if all you get down is some rules about engaging the customer and visualize a few scenarios, you are that much closer. Once you've done as much as you can to improve the internal branding, communicate that to ALL of the employees. Tell them what the customer experience is supposed to be and accept nothing but perfection from them. </span><br /><span style="font-family:Trebuchet MS;"></span><br /><span style="font-family:Trebuchet MS;">After that, you may want to talk with a marketing consultant and work out a formal plan. Once you have everything in a document, staff are living the brand and customers are happy and coming back, then you are ready to talk to a firm.</span><br /><span style="font-family:Trebuchet MS;"></span><br /><span style="font-family:Trebuchet MS;">Let me know if you agree with what I have said or have examples that can help.<span style="font-family:Trebuchet MS;"><br /><br /></span></span><span style="font-family:Trebuchet MS;"><span style="font-family:Trebuchet MS;"></span></span><span style="font-family:Trebuchet MS;"><span style="font-family:Trebuchet MS;"><p><br /><br /></span></span></p><span style="font-family:Trebuchet MS;"></span><br /><span style="font-family:Trebuchet MS;"></span><br /><br /><span style="font-family:Trebuchet MS;"></span><img src="" height="1" width="1" alt=""/>Darren Withers Involved<span style="font-size:130%;">Marketing, Money and More <em>Issue 3 </em>(12/2/07)</span><br /><br /><strong></strong><br /><strong>Let's Get Political...Political...I Wanna Get Po-lit-ical</strong><br />The one class that was never offered in college that university curriculums never teach you is social business. There is no teacher telling you how important it is to go to <a href="">lunch with clients</a>, show appreciation for all of the offerings your boss gives you, showing up to company functions and creating a rapport with your peers. It seems like common sense, but it definitely is not. There are people that make their living purely on their ability to be social and connect people together. Here in Las Vegas, we have <a href="">The Link </a>which is run by Joel Jarvis - a producer for Kaercher Insurance and friend of mine that has truly shown that networking is more than being social.<br /><br />It's called office politics. A mentor of mine once said, "You can be the best PR guy in the world, but it's the guy that golfs with his clients that will make the most money." That statement was a very real and very impactful one to me. Ever since I have made an effort to connect with everyone on some level. You can find something in common with everyone in the world because we are all human. We eat, we drink, we bleed, we breathe and we die. If you cannot find one thing to talk to someone about for 5 minutes, then you are making an effort to not be social.<br /><br /><strong>Promises, Promises</strong><br />Are you detecting an 80's song title theme in my headings today? Me too. Anyway, I have found that if there is a process to getting to where you want to go that is logical and intuitive but involves follow-through that 75% of people won't do it to completion. What am I trying to say??? I'll give you an example. If you knew that all you had to do to get a promotion was to show an interest in your industry and a desire to learn new things and you were told you had the recources at your disposal, what would you do? I would continue reading books that address "best practices," look into seminars and classrooms, join trade associations and potentially look at getting a Master's Degree. Not everyone thinks that way. Most people will think about it and put it off until their review comes. They will be told that they haven't progressed as quickly as their boss would expect and then they will get discouraged quit and start the process all over again somewhere else. It is a spiral that is hard to get out of but not impossible.<br /><br /><strong>It's Human Nature</strong><br />I attribute most of it to human nature. Look at the gym. I have continually been on an exercise program for over 10 years without missing a week. Year after year I watch a flood of people take over the gym in January and then about 3/4 drop off by March. It works out great for the gym owner because 100% of them keep their membership and only 25% use it. It is like free money. My dues would be much higher and the gym would be more crowded, so I thank the 75% that don't go.<br /><br />The mentality of a person that is goal-oriented is logical, for example...I want a body that is in good shape. I have to exercise 3-5 times a week to get the body I want. I go to the <a href="">gym</a> 3-5 days a week and I see results and I continue to go.<br /><br />It seems easy. When it comes to putting in the time and energy and people see how much dedication it takes, it becomes easier to give in to excuses and do other things with that time. They know what it takes to achieve the goal but something in them creates a barrier to achieve that goal. What is it? The same thing happens in othere areas of their life. Don't let you get in the way of what you want. Find balance and prioritize based on long term goals. It is all in your mind. A short work out is still a workout and gets you closer to the body you want. Learn something new even if it is just a new word in your industry glossary...it's a step and you moved foward toward your career goals.<br /><br /><strong>Knowledge is Power, Relationships are Money</strong><br />Whoever said knowledge is power was only half right. Knowledge can get you far, but having relationships with other decision-makers that have rapport with you and respect your knowledge will get you money. Now we are seeing the difference between a job and a career. You put much more of yourself into your <a href="">career</a> than a "job." I believe that is why it becomes so hard for career professionals to separate themselves from their work. They've become a hybrid of career and life because the two bleed into each other.<br /><br />Keep the people you've impressed in your career very close. Remember their birthday, anniversary and just remember to pick up the phone and call them. It will go a long way and opportunities that find them will also find you. A phone call means more when there is nothing behind it. Just catch up and don't ask for a favor. Use the 3 to 1 rule. This means have 3 calls about them or just talking and then throw 1 in that asks for a favor. It builds loyalty (read <a href=""><em>The</em> <em>Loyalty Effect</em></a>, one of the best books about a secret of economics.)<br /><br /><strong>I Want to Thank You...</strong><br />The first thing I learned from working for a non-profit was to ALWAYS SAY THANK YOU! It doesn't matter if someone opened the door or gave you a million dollars, say, "Thank you!" Even use a smiley face. People like to feel that their kindness was appreciated. A thank you can go a long way, forgetting to say thank you can kill a relationship.<br /><br /><strong>Be on Time</strong><br />If it is possible, be on time to appointments. It shows respect for the time that others have. I live by my calendar and successful people may have only minutes to talk to you. If you are late, you wasted their time and trust. It is a small step, but it makes you stand out.<br /><strong></strong><br /><strong>Social Networking</strong><br />I believe social marketing has become a discipline because as society gets smarter, there are more and more rules and contexts involved with social behavior and it will only get harder. I've managed to watch how behaviors communicate to others and I am very sensitive to how people act versus what they say. An action does speak louder and harder. If I say I really wanted to come to your birthday, but I went to a concert instead...it means I prioritized the concert over celebrating your birthday and no words can change that. Being late says I have no respect for your time. Not going to a work function means that you are not engaged with your company and don't care about the effort put on by your peers.<br /><p>There is no way around communicating. It happens whether you do something, don't do something, speak, nod, move, don't move. Action means just as much as inaction. Think about how you want to be perceived. Forgiveness is a virtue of humanity so play the percentages and try to be "on" the majority of the time. <p></p><p><strong>Here are a few tips:</strong></p><ol><li>Always say thank you</li><li>Take time to meet people and nurture relationships</li><li>Know more than you did yesterday</li><li>Work toward the goal and do all the steps in between</li><li>Be on time ALWAYS</li><li>Keep your promises no matter what; it builds trust </li><li>Listen, don't just wait for your turn to speak</li><li>Give credit where credit is due</li><li>Take every opportunity you are given to shine</li><li>Compete with yourself and no one else</li></ol><p>I'd love to hear if there is anyone that has seen their career turn around due to changing to new philosophies...Please post and I will say, "Thank you!"<br /></p><p></p><img src="" height="1" width="1" alt=""/>Darren Withers Selection Process<span style="font-size:130%;">Marketing, Money and More <em>Issue 2 </em>(11/24/07)</span><br /><span style="font-size:130%;"></span><br /><strong>Agency Arithmetic </strong><br />Let's do some math. Say an agency has 30 staff members that work 40 hours per week each. That's 1,200 hours per week and there are 52 weeks per year for a total of 62,400 total hours each year. Agencies don't sell products, just hours. That is their inventory. Those hours are spread out amongst different departments and disciplines. There are also lights, a building, power, computers, research tools and <a href="">subscriptions</a>, <a href="">seminars</a>, <a href="">classrooms</a>, chairs, toilets, water, <a href="">books</a> and other related expenses that lead to a bottom line number that has to be spread and charged to the 62,400 hours available to sell to clients. It is a basic matter of running a business, it must be profitable but there are industry practices that drive up the expense for everyone.<br /><br /><strong>Rolling the Dice</strong><br /><p>The average agency will do many "pitches" for work. Hours will be spent putting together these pitches. If the average agency wins 1 in 7 pitches, that is 6 pitches where the hours are written off. An agency could easily spend 100-200 hours on a major pitch. That reduces the available inventory of hours. Some agencies can be very selective about how much work that they will put toward winning a client's business and some have to just to compete. This is an industry standard that stems from the ambiguous nature of marketing. Since we aren't selling widgets, clients want to see what they are buying. There is no other way to show them the product than to do the work. Every pitch is a gamble and there may not be any return on that investment other than a letter thanking you for your effort. At the end of the day you gave away your best ideas, learned about a company that you will not be partnering with and have lower morale than when you started...But when you win, it's that much more rewarding.<br /><br /><strong>Agency Selection Process</strong><br />I have been through pitches for clients that have $5,000 per month to spend and pitches for clients that have millions. It then makes sense to give it your all for the ones that have millions and do a minimum amount of work to win the small clients, right? If it were that easy, I wouldn't take the time to write this. People watch too many <a href="">movies</a>. Not every client needs to go through the same process. Here are a few tips:<br /><span style="font-size:85%;"></span></p><ol><li><span style="font-size:85%;">Assess what your account is worth to an agency in a dollar amount per year or month.</span></li><li><span style="font-size:85%;">Have an expectation of what marketing can do for your business, even if it is wrong.</span></li><li><span style="font-size:85%;">Do your homework. Read a few case studies within your industry.</span></li><li><span style="font-size:85%;">Ask yourself what sort of agency culture will work best with your company.</span></li><li><span style="font-size:85%;">Start out online and ask a few people in your industry for recommendations.</span></li></ol><p>Now, what was your answer to #1? That will help you know what size firm to be talking to. Chiat Day will not speak to you if you have $5,000 per month, but a small consulting firm or PR firm will.<br /><br /><strong>Size Does Matter</strong><br />Now that you know you are talking to the right size agencies, do some homework. Ask for some references and their materials with a few case studies that match your business' situation. Once you have narrowed your seach to just a few candidates, call for a casual meeting with a represenative from each candidate firm at their office. Be upfront about your budget and your situation and let them come back to you with a proposal. Tell them your expectations in terms of what you want to see such as costs, spec creative, recommendations, etc. It is also important to let each firm know that you are talking to more than one firm, they will need to decide if they can accommodate your expectations. Firms do get short staffed, although most would pitch for the new business regardless.</p><p>How do you know if you should be seeing creative done "on spec?" Here are some ranges based on my experience:</p><ul><li><span style="font-size:85%;">$25,000 Annual Budget = Proposal with broad recommendations, case studies, etc</span></li><li><span style="font-size:85%;">$100,000 - $300,000 Annual Budget = Proposal with specific recommendations, case studies, etc.</span></li><li><span style="font-size:85%;">$500,000 + Annual Budget = Full agency pitch with recommendations and spec creative</span></li></ul><p>These ranges are based on total annual budgets. It is difficult to quote because of the amount of money that may be spent on media or production. A $5,000,000 budget can translate into less than $1 million in agency revenue if there is a heavy media spend. The best course is to ask each agency how they will be demonstrating what they will do for you. If 2 out of the 3 agree to go to the next level by writing up some recommendations and showing creative, then you are most likely a valid client that deserves that respect. If all agencies pass, it is because the potential return on your business does not qualify for a pitch process. In this case, you may go back and rethink your position on what you would like to see. </p><strong>Agencies Investment</strong><br />An agency will invest time into learning the client's business. Marketing directors tend to want to reduce their rate over time. Agencies tend to want to reap the benefits of having learned the clients business and therefore reducing the amount of time spent on the account.<br /><br />If you have found a firm that produces results, you must look at every dollar spent as an investment. Look at your P & L and share pertinent information with your agency. If the agency is performing, then a reward is in order, not a lower rate. Agencies are in business also. If they are receiving a fair rate with bonuses for performance, you probably have a very involved and motivated agency.<br /><br /><strong>Outlining the Relationship</strong><br />Retainers are great...for one of you. If your agency receives a monthly retainer for services and your workload is up and down, then you are paying for a block of time that does not get used. If the retainer dates back to 1997 and has not increased over the last 10 years but the workload has, then the agency loses. Here are a few fair potential scenarios<br /><br /><br /><ol><li><span style="font-size:85%;">Min/Max Retainer - This scenario is based on a range. There would be a minimum and a maximum. The minimum might be $10,000 and the maximum might be $30,000. The agency could charge anywhere within this range based on usage but it gives an expecation on both ends for cashflow. </span></li><li><span style="font-size:85%;">Performance - This scenario would allow the agency to truly be a partner in success. Goals are set for each campaign and performance bonuses are dispersed to the agency when they help achieve specific goals. A basic retainer would be attached to this for maintaining the account.</span></li><li><span style="font-size:85%;">Account Planning Retainer - This scenario pays for account planning and account service on a monthly retainer. Strategies are developed ongoing and execution is done a "per project" basis.</span> </li></ol><p>These are just a few scenarios that give a bit more controll over spending than a traditional retainer. Some clients don't want account planning, but I feel that it is the strategic thinking of an agency that differentiates it. Otherwise you are looking for a specialty firm like a <a href="">creative shop</a> or an interactive boutique. </p><p>The point is that it is very costly in terms of time and expense to choose a firm that doesn't fit your business. Choose carefully and make sure you conduct an appropriate process in your selection. If you feel like you need someone to guide you, there are plenty of <a href="">consultants</a> out there and when you are talking about managing millions of marketing dollars per year, it's worth it to choose wisely. </p><p>If you want to add a few scenarios or throw out a situation, please do. </p><img src="" height="1" width="1" alt=""/>Darren Withers & Marketing: How to Select a Marketing Firm that's a Good Fit for Your Company's NeedsI read over this blog and it is valid and supports what I believe is a good start when searching for a firm.<br /><br /><a href="">Branding & Marketing: How to Select a Marketing Firm that's a Good Fit for Your Company's Needs</a><img src="" height="1" width="1" alt=""/>Darren Withers for an Ad Campaign?<strong><span style="font-family:times new roman;font-size:130%;">Marketing, Money and More - <em>Issue 1</em> (11-22-07)</span></strong><br /><strong></strong><br /><span style="font-family:times new roman;">I have been with <a href="">Virgen Advertising </a>for 4 years, 3 of which I have been the lead business developer. We are a mid-sized <a href="">Vegas</a> agency with small accounts that spend a few thousand dollars here and there and very large accounts that spend millions of dollars annually. I have had clients from <a href="">Strip casinos </a>to the mom-and-pop's running a corner restaurant. The question keeps coming into play over and over and over from all size clients and there is never really an answer that seems to pacify everyone. </span><br /><span style="font-family:times new roman;"></span><br /><span style="font-family:times new roman;"><strong>Why does and ad campaign cost $10,000 to create? Did it really take your artists that long? The creative concepting time seems a bit excessive, can't you just spend less time on it? </strong></span><br /><strong><span style="font-family:Times New Roman;"></span></strong><strong><span style="font-family:Times New Roman;"></span></strong><br /><span style="font-family:Times New Roman;">I do my best to combat these questions and the answer can involve one or all three of the following:</span><br /><ol><li><span style="font-family:Times New Roman;">Value</span></li><li><span style="font-family:Times New Roman;">Time</span></li><li><span style="font-family:Times New Roman;">ROI</span></li></ol><span style="font-family:Times New Roman;">Ad agencies employ various techniques when pricing their services. <strong>Hourly rate, total estimated project cost </strong>and<strong> value.</strong></span><br /><strong><span style="font-family:Times New Roman;"></span></strong><br /><strong><span style="font-family:times new roman;">Hourly Rate</span></strong><br /><span style="font-family:Times New Roman;">When a service is ongoing such as public relations or strategic planning, an hourly rate is applied. Marketing is endless. There is always more you can do, but there is usually a budgetary restriction that tells us what an agency can accomplish for a client. If the client asks, "How much should I spend on my marketing monthly?" My answer is, "Well... you need to spend what makes sense to remain profitable and reach your growth goals." Agencies will maximize every dollar you give them. It is up to the client to say, "I have $50,000 dollars and I want to increase covers in my restaurant by 30 covers (restaurant lingo meaning table customers) a week."</span><br /><span style="font-family:Times New Roman;"></span><br /><span style="font-family:Times New Roman;">Wow! A dollar amount and a goal. That's all we need. I would then tell the client that with such a limited budget, we should try public relations and lifestyle marketing to increase word of mouth and get some good press on the food, chef, ambience, etc. We would need a minimum of 30 hours per month to work on this, so a retainer of roughly $3,000 - $4,000 would be sufficient to cover the amount of <strong>time</strong> our professionals would spend selling the local media on the client's restaurant. At that hourly rate, we would eat up the budget in a year. We may even recommend scaling back PR and employing some offer-based direct marketing to promote sampling. You begin to see how there are varoius ways we can apply a budget. This leads us to the next topic...</span><br /><strong><span style="font-family:Times New Roman;"></span></strong><br /><span style="font-family:Times New Roman;"><strong>Value of Service</strong></span><br /><span style="font-family:Times New Roman;">When we talk about creative, we are talking about art. What makes a Picasso worth millions and my water color paintings worth less than the blank piece of paper I started with? The answer is the amount of people that find the Picasso appealing and the laws of supply and demand. Now I'm not saying that <a href="">ad agencies </a>are pumping out masterpieces, BUT they are bringing appeal to your message through the use of images and text that connect with your target emotionally. What's that worth? My watercolor painting is awesome to me, but the world wouldn't pay a dime to have it. It's worthless and will not capture the attention of anyone. It can't be used to deliver a message.</span><br /><span style="font-family:Times New Roman;"></span><br /><span style="font-family:Times New Roman;">In our example, we talked about a restaurant. Let's say the agency quotes the restaurant $10,000 to do a print campaign. Did it take 100 hours? The final ad probably didn't. The 30 versions prior to getting to the final probably took a chunk of time. Are we using pictures of food from the restaurant? Do we have any? Will there be a photo shoot or will we look for stock images? STOP. This is where it starts to spin out of control for the small restaurant owner. If you are a restaurant that is losing money (as is industry standard in the first year of operation) then this may not sound like such a good idea, but if you are a restaurant chain and you have 5 locations, this may be a great idea and worth every expense. </span><br /><span style="font-family:Times New Roman;"></span><br /><span style="font-family:Times New Roman;">The point is what? Although each client will have varying hours to develop an ad, we charge $10,000 to put together a branding campaign. The market across the country says that $10,000 is what a branding campaign is worth. Somewhere in there the agency costs are covered and somewhere in every agency <a href="">business plan</a> is something about <strong>profit</strong> so there is some of that accounted for. Negotiate. Tell the agency what you are willing to pay. If you don't like their work that much you should probably be talking to another firm anyway; however, if you love their work and they have case studies and references proving that their creative expertise sells then you as the client need to decide if your brand is worth the expense and if it has <strong>value</strong>. </span><br /><strong><span style="font-family:Times New Roman;"></span></strong><br /><span style="font-family:Times New Roman;"><strong>ROI Is the Answer</strong></span><br /><span style="font-family:Times New Roman;">Return on Investment (ROI) or Return on Opportunity (ROO) are what should guide client decisions about marketing. If a campaign will yeild no returns, do you execute it? Probably not unless the wife of the owner likes the color blue and puppies and wants to see her last name on a billboard. Look at your annual revenues and ask yourself, "What is the maximum amount I can spend if I want to grow by 20% this year?" That is a key question. It has a goal attached that can be used to calculate a dollar amount. If you are a start-up, then this is probably mapped out in your <a href="">business plan</a>. Now you can go to an advertising agency with a marketing budget and a sense of what ROI needs to be obtained from the spend. The agency will tell you if they think your budget can achieve your ROI goals. You may need to adjust based on recommendations.</span><br /><span style="font-family:Times New Roman;"></span><br /><strong><span style="font-family:Times New Roman;">All Firms are Unique</span></strong><br /><span style="font-family:Times New Roman;">There is very little that is uniform in the marketing world. Standarization occurs where it can, but "best practices" are not always established for the ever-changing world of advertising. <a href="">Match your business with a firm that complements it.</a> If you have $50,000 a year to spend, then you probably aren't talking to <a href="">Young & Rubicam</a>. You are probably speaking to a small-to-mid-sized firm with less than 50 people. The larger the agency, the bigger the building, the more equipment, the more toilette paper, the more books, the more media research subscriptions, the more payroll, the more, the more, the more. Costs of providing the tools and space to manage all the various disciplines of marketing go up with agency size and that affects rates and prices. A good agency cost more just like a good interior designer costs more.</span><br /><span style="font-family:Times New Roman;"></span><br /><span style="font-family:Times New Roman;"><strong>You Get Out What You Put In it</strong></span><br /><span style="font-family:Times New Roman;">Each agency will have its own process. A good agency will spend many hours and involve multiple people in the creative process to deliver the very best ideas to the client. Another agency might allow one guy to spend 2 hours and you get the best idea that came from that one person in that short time. I don't care how creative that one guy is, he needs time to think of ideas. You get what you pay for. More time usually means more creativity. The one who spends less time will be able to charge a lower price in less time at the cost of mediocre creative at the end of today. If mediocre is appealing to your audience, then go with it. I've seen it work. If your brand demands the very best and your audience will judge you by the level of your branding, then you will end up paying for the extra time. Now you begin to understand what price speaks to. </span><br /><span style="font-family:Times New Roman;"></span><br /><span style="font-family:Times New Roman;">A firm of 5 people that can charge $200 for a print ad can't be compared to a firm that has 50 employees and charges $10,000 for a print campaign. Price cannot be the sole factor in this decision. There has to be a fit in so many other places as well as countless other considerations. Do your homework. </span><br /><span style="font-family:Times New Roman;"></span><br /><span style="font-family:Times New Roman;">I will be posting more and more about these issues in order to educate business people that haven't had enough experience with agencies to know what they need to know. I've seen a lot of people get burned and then they don't trust agencies and every nickel on an invoice becomes and epic battle. The next post will be on <strong><a href="">agency selection processes.</a> </strong></span><br /><span style="font-family:Times New Roman;"></span><br /><span style="font-family:Times New Roman;"></span><img src="" height="1" width="1" alt=""/>Darren Withers | http://feeds.feedburner.com/MarketingMoneyAndMore | CC-MAIN-2016-50 | refinedweb | 23,824 | 61.77 |
We all know Elmah right? It’s one of the top packages in NuGet. For those who don’t really know or use Elmah, I’ll give a brief explanation of the functionality it provides and how you can use it in your application.
Elmah stands for Error Logging Modules and Handlers. It’s an application-wide error logging library which logs nearly all unhandled exceptions. It provides you with a web page which enables you to (remotely) view the log of recorded exceptions. This log doesn’t only contain the error message; it also includes the entire stack trace and the values of all server variables at the time of the error.
Since we have NuGet, setting up Elmah with an ASP.NET MVC application has become really easy. Right click your web application and select ‘Add Library Package Reference…’ to pop up the NuGet Package Manager. Search for Elmah and install it. After installing, Elmah will have been added as a project reference.
The next step is to configure Elmah. I won’t go into too much detail here. We’ll just set up Elmah to log all errors to an in-memory repository and to expose those errors through a web page. First let’s add the following code to the <configSections> node to make Elmah read it’s configuration from your web.config.
<configSections>
<sectiongroup name="elmah">
<section name="errorLog" type="Elmah.ErrorLogSectionHandler, Elmah"
requirepermission="false">
</sectiongroup>
Elmah allows you to log errors to several storages. They currently support Microsoft SQL Server, Oracle, SQLite, Access, XML files, in-memory, SQL CE, MySQL and PostgreSQL. Insert the code below in your web.config to log error to an in-memory storage. When using an in-memory repository, all errors that got recorded will vanish when the application restarts.
<elmah>
<errorlog type="Elmah.MemoryErrorLog, Elmah">
</elmah>
We still have to do two things to get everything up and running:
To achieve this, we have to add an HTTP module and an HTTP handler. The module is responsible for logging the exceptions while the HTTP handler will render a page with a list of errors. You’ll have to add these sections to both the <system.web> node and the <system.webServer> node in order to support IIS running in Classic mode as well as Integrated mode. More information in this can be found on MSDN – How to: Register HTPP Handlers.
<system.web>
<system.webServer>
<system.web>
<httphandlers>
<add type="Elmah.ErrorLogPageFactory, Elmah"
verb="POST,GET,HEAD" path="elmah.axd">
</httphandlers>
<httpmodules>
<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah">
</httpmodules>
</system.web>
<system.webserver>
<modules runallmanagedmodulesforallrequests="true">
<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah">
</modules>
<handlers>
<add name="Elmah" type="Elmah.ErrorLogPageFactory, Elmah"
verb="POST,GET,HEAD" path="elmah.axd"
precondition="integratedMode">
</handlers>
</system.webserver>
Let’s take a closer look at the registration of the HTTP handler. We specified a path ‘elmah.axd’, this means that the handler will only kick in when we browse to that specific path. So, let’s launch our application and take a look. If I browse to I get this:
And oh, it even gets better. Let's click on the ‘details’ link next to the error message. This is where the magic happens:
This is really neat; we get a ton of information on what was going on when the error was thrown. If an application error occurred, we can almost immediately pin-point the problem.
Obviously, you don’t want to give access to this log to everyone that visits your website, as user might be able to spot vital problems in your code and exploit them. You can prevent access to this log in various ways (no remote access, through ASP.NET authorization …). More information on this topic can be found here: Elmah: Securing Error Log Pages.
Most of you probably know Firebug. And actually, Glimpse is a lot like Firebug, except it’s implemented in JavaScript on the client side with hooks in to ASP.NET on the server side. What Firebug is for the client, Glimpse does for the server... in other words, a client side Glimpse into what’s going on in your server.
Currently Glimpse can only be used within web applications that target .NET 4.0; however the Glimpse team is currently working on a build that supports.NET 3.5 as well. As a matter of fact, Glimpse is not just a .NET only tool; currently it only works with ASP.NET MVC and Web Forms but eventually it will support Ruby on Rails, PHP and others.
For ASP.NET MVC 3, it currently already has a bunch of nice features, like:
Integrating Glimpse with ASP.NET MVC is very easy. It’s available as a NuGet package so installing it literally takes about 30 seconds. Let’s have a look … Right click your web application and select ‘Add Library Package Reference…’ to pop up the NuGet Package Manager. Search for Glimpse and install it:
The Glimpse NuGet package will automatically reference the right assembly and it will add a configuration section to your web.config. The only thing you have to do to get it up and running is the following:
What these Glimpse guys developed is really mind blowing. Currently Glimpse is still beta, but in my opinion it’s stable enough to integrate with all of your current ASP.NET projects.
Scott Hanselman, unofficially titled the funniest guy at Microsoft, recently featured Glimpse as ‘NuGet Package of the Week’. At the end of the article, he says:
‘Glimpse, along with ELMAH, is officially my favorite add-on to ASP.NET MVC. I'll be using it every day and I recommend you do as well.’
So … wouldn’t it be cool to integrate Elmah with Glimpse?
Glimpse has a really clean plugin system. Internally, they use MEF to discover extensions. The best of all is that writing a Glimpse plugin is really easy. All you have to do is:
IGlimpsePlugin
GlimpsePlugin
Let’s take a look at my Elmah plugin for Glimpse:
[GlimpsePlugin]
public class ElmahPlugin : IGlimpsePlugin
{
public string Name
{
get { return "Elmah"; }
}
public object GetData(HttpApplication application)
{
if (application == null || application.Context == null)
return null;
var errorList = new List<errorlogentry>();
var errorCount = ErrorLog
.GetDefault(application.Context)
.GetErrors(0, 15, errorList);
if (errorCount == 0)
return null;
var data = new List<object[]>
{
new object[]
{
"Host", "Code", "Type",
"Error", "User", "Date", "Time"
}
};
data.AddRange(
errorList.Select(
errorEntry => new object[]
{
errorEntry.Error.HostName,
errorEntry.Error.StatusCode,
errorEntry.Error.Type,
errorEntry.Error.Message,
errorEntry.Error.User,
errorEntry.Error.Time.Date.ToShortDateString(),
errorEntry.Error.Time.ToShortTimeString()
}));
return data;
}
public void SetupInit(HttpApplication application)
{
throw new NotImplementedException();
}
}
In the code sample above, you see I implement the IGlimpsePlugin interface. The interface has the following methods:
GetData
HttpApplication
SetupInit
ShouldSetupInInit
true
[GlimpsePlugin(ShouldSetupInInit=true)]
The GetData method is the place where you should make any decisions about what should be rendered and how you want to render it. If this method returns null, then your tab will be disabled in the Glimpse UI.
null
In the above implementation, I return null if no HTTP context is available or when no errors have been logged yet. In case errors have been logged, I return them as a list of objects. The first entry in the list will be used as the title row; all subsequent rows are data rows. Currently only the last 15 errors are returned to the user.
null
Update 05/31/2011: The above code sample and the explanation that comes with it are not entirely valid anymore, but for the purpose of the document I'll leave it as it initially was.
The Elmah plugin for Glimpse is available as a NuGet package. To install the package, right click your web application and select ‘Add Library Package Reference …’ search for either ‘Glimpse’, ‘Elmah’ or ‘Glimpse.Elmah’ and the Package Manager will come up with the ‘Elmah plugin for Glimpse’.
The package has dependencies to Glimpse and Elmah, so if you haven’t got these package installed yet, then NuGet will get them automatically as well. If you didn’t have Elmah before, you might still have to configure it.
After installing the package, you still have to include the Elmah for Glimpse client side script on your pages, preferable in your main master page.
<script src="<%: Url.Content("~/Glimpse/Resource/?resource=Pager") %>"
type="text/javascript"></script>
Let’s run our application again and see what happens. Our Elmah plugin has been added as a reference to the project so it will be discovered by the Glimpse plugin system. Glimpse will load it into its UI and voila, there we have it:
The easiest to get started is by getting the ‘Elmah plugin for Glimpse Sample’ package, which is also available through NuGet.
Just create a new empty ASP.NET MVC 3 application and add a library package reference to the Elmah plugin for Glimpse Sample package. The package will automatically:
After installing the package, you’ve got yourself an application to throw exceptions! Cool huh!? OK, so let’s run the application, throw some exceptions and see what happens:
If you try the sample yourself, but you don’t see the Glimpse plugin you might still have to enable it. Please take a look at the ‘Using Glimpse with ASP.NET MVC’ section on how to do this.
If there's any feature you would like to see implemented, you can always submit a feature request on the project home page at CodePlex. If you want to implement a feature yourself, you can fork the project and submit a pull request.
Things I’m considering for the next version are:
IProvideGlimpseHelp. | http://www.codeproject.com/Articles/198251/Elmah-for-Glimpse-Best-of-Both-Worlds | CC-MAIN-2016-18 | refinedweb | 1,617 | 56.96 |
Check if the frequency of all the digits in a number is same
Given a positive number ‘N’, the task is to find whether ‘N’ is balanced or not. Output ‘YES’ if ‘N’ is a balanced number else ‘NO’.
A number is balanced if the frequency of all the digits in it is same i.e. all the digits appear the same number of times.
Examples:
Input: N = 1234567890 Output: YES The frequencies of all the digits are same. i.e. every digit appears same number of times. Input: N = 1337 Output: NO
Approach:
- Create an array
freq[]of size 10 which will store the frequency of each digit in ‘N’.
- Then, check if all the digits of ‘N’ have the same frequency or not.
- If yes then print ‘
YES‘ or ‘
NO‘ otherwise.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include
using namespace std;
// returns true if the number
// passed as the argument
// is a balanced number.
bool isNumBalanced(int N)
{
string st = to_string(N);
bool isBalanced = true;
// frequency array to store
// the frequencies of all
// the digits of the number
int freq[10] = {0};
int i = 0;
int n = st.size();
for (i = 0; i < n; i++) // store the frequency of // the current digit freq[st[i] - '0']++; for (i = 0; i < 9; i++) { // if freq[i] is not // equal to freq[i + 1] at // any index 'i' then set // isBalanced to false if (freq[i] != freq[i + 1]) isBalanced = false; } // return true if // the string is balanced if (isBalanced) return true; else return false; } // Driver code int main() { int N = 1234567890; bool flag = isNumBalanced(N); if (flag) cout << "YES"; else cout << "NO"; } // This code is contributed by ihritik [tabby title = "Java"]
Python3
C#
PHP
YES
Recommended Posts:
- Check if the Xor of the frequency of all digits of a number N is zero or not
- Check whether product of digits at even places is divisible by sum of digits at odd place of a number
- Check if the sum of digits of number is divisible by all of its digits
- Check if two numbers have same number of digits
- Check if a number has digits in the given Order
- Check if all digits of a number divide it
- Check if the sum of digits of a number N divides it
- Check if a number with even number of digits is palindrome or not
- Program to check if a number is divisible by sum of its digits
- Program to check if a number is divisible by any of its digits
- Check whether sum of digits at odd places of a number is divisible by K
- Check if the number is even or odd whose digits and base (radix) is given
- Check if N is divisible by a number which is composed of the digits from the set {A, B}
- Check if a number is magic (Recursive sum of digits is 1)
- Check if a given number divides the sum of the factorials of its, rituraj_jain, ihritik | https://www.geeksforgeeks.org/check-if-the-frequency-of-all-the-digits-in-a-number-is-same/ | CC-MAIN-2019-39 | refinedweb | 504 | 50.13 |
Created on 2013-03-19 17:35 by ncoghlan, last changed 2014-02-19 12:40 by ncoghlan. This issue is now closed.
functools.update_wrapper inadvertently overwrites the just set __wrapped__ attribute when it updates the contents of __dict__.
This means the intended __wrapped__ chain is never created - instead, for every function in a wrapper stack, __wrapped__ will always refer to the innermost function.
This means that using __wrapped__ to bypass functools.lru_cache doesn't work correctly if the decorated function already has __wrapped__ set.
Explicitly setting __signature__ fortunately still works correctly, since that is checked before recursing down through __wrapped__ in inspect.signature.
There's an interesting backwards compatibility challenge here. We definitely need to fix the misbehaviour, since it can lead to some pretty serious bugs in user code when attempting to bypass the LRU cache decorator if the wrapped function itself had a __wrapped__ attribute.
However, Michael tells me that at least some third party clients of the introspection tools assumed the "__wrapped__ points to the bottom of the wrapper stack" behaviour was intentional rather than just me screwing up the implementation.
The existing docs for update_wrapper are unfortunately ambiguous because they use the term "original function" instead of "wrapped function".
And as further evidence that I always intended this to be a wrapper chain: issue 13266 :)
OK, thinking about this a little further, I think it's not as bad as I feared. The number of people likely to be introspecting __wrapped__ is quite small, and updating to the correct recursive code will still do the right thing in existing versions.
So long as we tell people this is coming, and get Georg to highlight it in the release notes for the corresponding 3.3.x point release, we should be able to fix the lru_cache bug without too much collateral damage.
Georg, just a heads up that I was informed of a fairly significant bug in the __wrapped__ handling which some folks doing function introspection had been assuming was a feature.
I'd like to fix it for 3.3.3, but need your +1 as RM since it *will* break introspection code which assumes the current behaviour was intentional.
New changeset 13b8fd71db46 by Nick Coghlan in branch 'default':
Close issue 17482: don't overwrite __wrapped__
I decided I can live with the risk of this biting someone in 3.3 - the combination of using multiple levels of wrapping *and* using __wrapped__ for more than merely introspection seems remote enough to make being conservative with the behavioural change the better course.
this is actually biting me, I think, though I'm having a very hard time getting a small Python script to duplicate it :/. refers to the current problems I'm having. I am not really familiar with the ramifications of __wrapped__ so I need to learn some more about that but also I'm concerned that a standalone test which attempts to simulate everything as much as possible is not doing the same thing.
i think I found the problem. sorry for the noise.
OK well, let me just note what the issue is, and I think this is pretty backwards-incompatible, and additionally I really can't find any reasonable way of working around it except for just deleting __wrapped__. It would be nice if there were some recipe or documentation that could point people to how do do the following pattern:
import functools
import inspect
def my_wrapper(fn):
def wrapped(x, y, z):
return my_func(x, y)
wrapped = functools.update_wrapper(wrapped, fn)
return wrapped
def my_func(x, y):
pass
wrapper = my_wrapper(my_func)
# passes for 2.6 - 3.3, fails on 3.4
assert inspect.getargspec(wrapper) == (['x', 'y', 'z'], None, None, None), inspect.getargspec(wrapper)
basically in Alembic we copy out a bunch of decorated functions out somewhere else using inspect(), and that code relies upon seeing the wrappers list of arguments, not the wrapped. Not that Python 3.4's behavior isn't correct now, but this seems like something that might be somewhat common.
Mike, could you file a new issue for that? It's a genuine regression in the
inspect module.
New release blocker created as issue 20684 | https://bugs.python.org/issue17482 | CC-MAIN-2020-40 | refinedweb | 699 | 61.87 |
The Best of Both Worlds: Combining XPath with the XmlReader
Dare Obasanjo and Howard Hao
Microsoft Corporation
May 5, 2004
Download the XPathReader.exe sample file.
Summary:.
(11 printed pages)(11 printed pages)
Introduction
About a year ago, I read an article by Tim Bray entitled XML Is Too Hard For Programmers, in which he complained about the cumbersome nature of push model APIs, like SAX, for dealing with large streams of XML. Tim Bray describes an ideal programming model for XML as one that is similar to working with text in Perl, where one can process streams of text by matching items of interest using regular expressions. Below is an excerpt from Tim Bray's article showing his idealized programming model for XML streams.
Tim Bray isn't the only one who yearned for this XML processing model. For the past few years, various people I work with have been working towards creating a programming model for processing streams of XML documents in a manner analogous to processing text streams with regular expressions. This article describes the culmination of this work—the XPathReader.
Finding Loaned Books: XmlTextReader Solution
To give a clear indication of the productivity gains from the XPathReader compared to existing XML-processing techniques with the XmlReader, I have created an example program that performs basic XML processing tasks. The following sample document describes a number of books I own and whether they are currently loaned out to friends.
>
The following code sample displays the names of the persons that I've loaned books to, as well as which books I have loaned to them. The code samples should produce the following output.
Sanjay was loaned XML Bible by Elliotte Rusty Harold Sander was loaned Definitive XML Schema by Priscilla Walmsley XmlTextReader Sample: using System; using System.IO; using System.Xml; public class Test{ static void Main(string[] args) { try{ XmlTextReader reader = new XmlTextReader("books.xml"); ProcessBooks(reader); }catch(XmlException xe){ Console.WriteLine("XML Parsing Error: " + xe); }catch(IOException ioe){ Console.WriteLine("File I/O Error: " + ioe); } } static void ProcessBooks(XmlTextReader reader) { while(reader.Read()){ //keep reading until we see a book element if(reader.Name.Equals("book") && (reader.NodeType == XmlNodeType.Element)){ if(reader.GetAttribute("on-loan") != null){ ProcessBorrowedBook(reader); }else { reader.Skip(); } } } } static void ProcessBorrowedBook(XmlTextReader reader){ Console.Write("{0} was loaned ", reader.GetAttribute("on-loan")); while(reader.NodeType != XmlNodeType.EndElement && reader.Read()){ if (reader.NodeType == XmlNodeType.Element) { switch (reader.Name) { case "title": Console.Write(reader.ReadString()); reader.Read(); // consume end tag break; case "author": Console.Write(" by "); Console.Write(reader.ReadString()); reader.Read(); // consume end tag break; } } } Console.WriteLine(); } }
Using XPath as Regular Expressions for XML
The first thing we need is a way to perform pattern matching for nodes of interest in an XML stream in the same way we can with regular expressions for strings in a text stream. XML already has a language for matching nodes called XPath, which can serve as a good starting point. There is an issue with XPath that prevents it from being used without modification as the mechanism for matching nodes in large XML documents in a streaming manner. XPath assumes the entire XML document is stored in memory and allows operations that would require multiple passes over the document, or at least would require large portions of the XML document be stored in memory. The following XPath expression is an example of such a query:
The query returns the publisher attribute of a book element if it has a child author element whose value is 'Frederick Brooks'. This query cannot be executed without caching more data than is typical for a streaming parser because the publisher attribute has to be cached when seen on the book element until the child author element has been seen and its value examined. Depending on the size of the document and the query, the amount of data that has to be cached in memory could be quite large and figuring out what to cache could be quite complex. To avoid having to deal with these problems a co-worker, Arpan Desai, came up with a proposal for a subset of XPath that is suitable for forward-only processing of XML. This subset of XPath is described in his paper An Introduction to Sequential XPath.
There are several changes to the standard XPath grammar in Sequential XPath, but the biggest change is the restriction in the usage of axes. Now, certain axes are valid in the predicate, while other axes are valid only in the non-predicate portion of the Sequential XPath expression. We have classified the axes into three different groups:
- Common Axes: provide information about the context of the current node. They can be applied anywhere in the Sequential XPath expression.
- Forward Axes: provide information about nodes ahead of the context node in the stream. They can only be applied in the location path context because they are looking for 'future' nodes. An example is "child.'' We can successfully select the child nodes of a given path if "child" is in the path. However, if "child" were in the predicate, we would not be able to select the current node because we cannot look ahead to its children to test the predicate expression and then rewind the reader to select the node.
- Reverse Axis: are essentially the opposite of Forward Axes. An example would be "parent." If parent were in the location path, we would want to return the parent of a specific node. Once again, because we cannot go backward, we cannot support these axes in the location path or in predicates.
Here is a table showing the XPath axes supported by the XPathReader:
There are some XPath functions not supported by the XPathReader due to the fact that they also require caching large parts of the XML document in memory or the ability to backtrack the XML parser. Functions such as count() and sum() are not supported at all, while functions such as local-name() and namespace-uri() only work when no arguments are specified (that is, only when asking for these properties on the context node). The following table lists the XPath functions that are either unsupported or have had some of their functionality limited in the XPathReader.
The final major restriction made to XPath in the XPathReader is to disallow testing for the values of elements or text nodes. The XPathReader does not support the following XPath expression:
The above query selects the book element if its string contains the text 'Frederick Brooks'. To be able to support such queries, large parts of the document may have to be cached and the XPathReader would need to be able to rewind its state. However, testing values of attributes, comments, or processing instructions is supported. The following XPath expression is supported by the XPathReader:
The subset of XPath described above is sufficiently reduced as to enable one to provide a memory-efficient, streaming XPath-based XML parser that is analogous to regular expressions matching for streams of text.
A First Look at the XPathReader
The XPathReader is a subclass of the XmlReader that supports the subset of XPath described in the previous section. The XPathReader can be used to process files loaded from a URL or can be layered on other instances of XmlReader. The following table shows the methods added to the XmlReader by the XPathReader.
The following example uses the XPathReader to print the title of every book in my library:
using System; using System.Xml; using System.Xml.XPath; using GotDotNet.XPath; public class Test{ static void Main(string[] args) { try{ XPathReader xpr = new XPathReader("books.xml", "//book/title"); while (xpr.ReadUntilMatch()) { Console.WriteLine); } } }
An obvious advantage of the XPathReader over conventional XML processing with the XmlTextReader is that the application does not have to keep track of the current node context while processing the XML stream. In the example above, the application code doesn't have to worry about whether the title element whose contents it is displaying and printing is a child of a book element or not by explicitly tracking state because this is already done by the XPath.
The other piece of the puzzle is the XPathCollection class. The XPathCollection is the collection of XPath expressions that the XPathReader is supposed to match against. An XPathReader only matches nodes contained in its XPathCollection object. This matching is dynamic, meaning that XPath expressions can be added and removed from the XPathCollection during the parsing process as needed. This allows for performance optimizations where tests aren't made against XPath expressions until they are needed. The XPathCollection is also used for specifying prefix<->namespace bindings used by the XPathReader when matching nodes against XPath expressions. The following code fragment shows how this is accomplished:
Finding Loaned Books: XPathReader Solution
Now that we've taken a look at the XPathReader, it's time to see how much improved processing XML files can be compared to using the XmlTextReader. The following code sample uses the XML file in the section entitled Finding Loaned Books: XmlTextReader Solution and should produce the following output:
Sanjay was loaned XML Bible by Elliotte Rusty Harold Sander was loaned Definitive XML Schema by Priscilla Walmsley XPathReader Sample: using System; using System.IO; using System.Xml; using System.Xml.XPath; using GotDotNet.XPath; public class Test{ static void Main(string[] args) { try{ XmlTextReader xtr = new XmlTextReader("books.xml"); XPathCollection xc = new XPathCollection(); int onloanQuery = xc.Add("/books/book[@on-loan]"); int titleQuery = xc.Add("/books/book[@on-loan]/title"); int authorQuery = xc.Add("/books/book[@on-loan]/author"); XPathReader xpr = new XPathReader(xtr, xc); while (xpr.ReadUntilMatch()) { if(xpr.Match(onloanQuery)){ Console.Write("{0} was loaned ", xpr.GetAttribute("on-loan")); }else if(xpr.Match(titleQuery)){ Console.Write(xpr.ReadString()); }else if(xpr.Match(authorQuery)){ Console.WriteLine(" by {0}",); } } }
This output is greatly simplified from the original code block, is almost as efficient memory-wise, and very analogous to processing text streams with regular expressions. It looks like we have reached Tim Bray's ideal for an XML programming model for processing large XML streams.
How the XPathReader Works
The XPathReader matches XML nodes by creating a collection of XPath expressions compiled into an abstract syntax tree (AST) and then walking this syntax tree while receiving incoming nodes from the underlying XmlReader. By walking through the AST tree, a query tree is generated and pushed onto a stack. The depth of the nodes to be matched by the query is calculated and compared against the Depth property of the XmlReader as nodes are encountered in the XML stream. The code for generating the AST for an XPath expression is obtained from the underlying code for the classes in the System.Xml.Xpath, which is available as part of the source code in the Shared Source Common Language Infrastructure 1.0 Release.
Each node in the AST implements the IQuery interface that defines the following three methods:
The GetValue method returns the value of the input node relative to the current aspect of the query expression. The MatchNode method tests whether the input node matches the parsed query context, while the ReturnType property specifies which XPath type the query expression evaluates.
Future Plans for XPathReader
Based on how useful various people at Microsoft have found the XPathReader, including the BizTalk Server that ships with a variation of this implementation, I've decided to create a GotDotNet workspace for the project. There are a few features I'd like to see added, such as integration of some of the functions from the EXSLT.NET project into the XPathReader and support for a wider range of XPath. Developers that would like to work on further development of XPathReader can join the GotDotNet workspace.
Conclusion
The XPathReader provides a potent way for processing XML streams by harnessing the power of XPath and combining it with the flexibility of the pull-based XML parser model of the XmlReader. The compositional design of System.Xml allows one to layer the XPathReader over other implementations of the XmlReader and vice versa. Using the XPathReader for processing XML streams is almost as fast as using the XmlTextReader, but at the same time is as usable as XPath with the XmlDocument. Truly it is the best of both worlds.
Dare Obasanjo is a member of Microsoft's WebData team, which among other things develops the components within the System.Xml and System.Data namespace of the .NET Framework, Microsoft XML Core Services (MSXML), and Microsoft Data Access Components (MDAC).
Howard Hao is a Software Design Engineer in Test on the WebData XML team and is the main developer of the XPathReader.
Feel free to post any questions or comments about this article on the Extreme XML message board on GotDotNet. | https://msdn.microsoft.com/en-us/library/ms950778 | CC-MAIN-2017-43 | refinedweb | 2,130 | 53.31 |
On 11/04/2013 02:13 PM, Philip Nienhuis wrote: > Rik wrote: >> On 11/04/2013 09:54 AM, John W. Eaton wrote: >>> On 11/04/2013 12:05 PM, Rik wrote: >>> >>>> Aside from performance, does using gnulib::frexp solve the original >>>> problem? The gnulib documentation is somewhat minimal and they suggest >>>> that they only replace an existing library function if the function is >>>> buggy. Otherwise, they fall back on the library version that is >>>> available. This may be, however, only when you use the bare function >>>> such as 'frexp' rather than the namespace-qualified version >>>> 'gnulib::frexp'. >>> >>> The namespace thing allows gnulib to replace the function in C++ code >>> without introducing macros that screw things up in other places. But the >>> replacement code is still only used if needed. It works by using a >>> function pointer in the namespace that either refers to the replacement >>> function (usually called rpl_FOO) or the system function FOO. So there >>> shouldn't be much of a penalty if the system function is used. >> Philip, >> >> Can you test the solution which is in Mercurial with MinGW? It is possible >> that gnulib doesn't identify the frexp on Windows as being buggy (since it >> works for ordinary values) in which case it won't replace it with the >> correct version. > > Yes I'll try but only tomorrow night at the earliest, sorry. > I've just finished io-1.2.4 which required more attention than I hoped for. Independent testing is always great, but jwe has already gone ahead and tested it. If you're super busy then I don't think it's necessary to replicate the test. --Rik | http://lists.gnu.org/archive/html/octave-maintainers/2013-11/msg00090.html | CC-MAIN-2017-43 | refinedweb | 275 | 72.36 |
Hello, so there’s my problem, I have a body out of vertex points and a skin modifier, now I need the skin radius (which is the same for x and y) with the location
I can loop through the skin points and add them to a list aswell as the vertex points, but how do I know that the first vertex is also the first in the skin modiefier?
import bpy import mathutils from mathutils import Vector import random splineList = [] #list of vertex points I created #list of skin points (where I set the radius) for v in ob.data.skin_vertices[0].data: print(v.radius[:]) randVar = random.uniform(0.05,0.3) v.radius = randVar , randVar | https://blenderartists.org/t/how-to-get-skin-vertex-position/670487 | CC-MAIN-2020-40 | refinedweb | 118 | 61.7 |
0
I need help with this program
I need to be able to type all the names and the grades then the graph of all the student will be shown but i am only able to type one student name and grade and the graph shows but i can still type student....
am i doing the for looping wrong?
import java.util.Scanner; public class Students { public static void main (final String[] args) { final Scanner scanner = new Scanner (System.in); final String name = "Name"; final String result = "Grade"; final String letter = "Letter"; // String s1 = scanner.next (); // if (scanner.hasNextDouble ()) { for (int i = 0; i < 4; i++) { final String s3 = scanner.next (); final String s2 = scanner.next (); final int score = scanner.nextInt (); char grade = 0; // "blank final" if (score >= 90) { grade = 'A'; } else if (score >= 80) { grade = 'B'; } else if (score >= 70) { grade = 'C'; } else if (score >= 60) { grade = 'D'; } else { grade = 'F'; } System.out.printf (" %-10s %5s %10s%n ", name, result, letter); System.out.printf ("%-10s %-9d %-10s", s3 + s2, score, grade); System.out.println (); } } }
Edited 5 Years Ago by Ezzaral: Added code tags. Please use them to format any code that you post. | https://www.daniweb.com/programming/software-development/threads/343924/need-help | CC-MAIN-2017-04 | refinedweb | 194 | 82.85 |
DIRECTORY(3B) DIRECTORY(3B)
opendir, readdir, telldir, seekdir, rewinddir, closedir, dirfd -
directory operations (4.3BSD)
#include <sys/types.h>
#include <sys/dir.h>
DIR *opendir(char *filename);
struct direct *readdir(DIR *dirp);
long telldir(DIR *dirp);
void seekdir(DIR *dirp, long loc);
void rewinddir(DIR *dirp);
void closedir(DIR *dirp);
int dirfd(DIR *dirp)
The inclusion of <sys/dir.h> selects the 4.3BSD versions of these
routines. For the System V versions, include <dirent.h>.
opendir opens the directory named by filename and associates a directory
stream with it. opendir returns a pointer to be used to identify the
directory stream in subsequent operations. The pointer NULL is returned
if filename cannot be accessed, or if it cannot malloc(3) enough memory
to hold the whole thing.
readdir returns a pointer to the next directory entry. It returns NULL
upon reaching the end of the directory or detecting an invalid seekdir
operation.
telldir returns the current location associated with the named directory
stream.
seekdir sets the position of the next readdir operation on the directory
stream. The new position reverts to the one associated with the directory
stream when the telldir operation was performed. Values returned by
telldir are good only for the lifetime of the DIR pointerdir.
rewinddir resets the position of the named directory stream to the
beginning of the directory.
Page 1
DIRECTORY(3B) DIRECTORY(3B)
closedir closes the named directory stream and frees the structure
associated with the DIR pointer.
dirfd returns the integer file descriptor associated with the named
directory stream, see open(2).
Sample code that searches a directory for entry ``name'':
len = strlen(name);
dirp = opendir(".");
if (dirp == NULL) {
return NOT_FOUND;
}
while ((dp = readdir(dirp)) != NULL) {
if (dp->d_namlen == len && !strcmp(dp->d_name, name)) {
closedir(dirp);
return FOUND;
}
}
closedir(dirp);
return NOT_FOUND;
open(2), close(2), read(2), lseek(2), directory(3C)
PPPPaaaaggggeeee 2222 | https://nixdoc.net/man-pages/IRIX/man3b/directory.3b.html | CC-MAIN-2022-21 | refinedweb | 312 | 50.73 |
Sending push notifications with Azure Notification Hubs on Windows Phone
Overview
Note
To complete this tutorial, you must have an active Azure account. If you don't have an account, you can create a free trial account in just a couple of minutes. For details, see Azure Free Trial..
Create your notification hub
Select New > Web + Mobile > Notification Hub.
In the Notification Hub box, type a unique name. Select your Region, Subscription, and Resource Group (if you have one already).
If you already have a service bus namespace that you want to create the hub in, do the following:
a. In the Namespace area, select the Select Existing link.
b. Select Create.
If you don't already have a service bus namespace, you can use the default name, which is created based on the hub name (if the namespace name is available).
After you've created the namespace and notification hub, the Azure portal opens.
Select Settings > Access Policies. Note the two connection strings that are available to you. You will need them to handle push notifications later.
Click the Notification Services section (within Settings), click on Windows Phone (MPNS) and then click the Enable unauthenticated push check box.
>.
![Visual Studio - New Project - Windows Phone App][13]); }); });
Note
The value MyPushChannel is an index that is used to lookup an existing channel in the HttpNotificationChannel collection. If there isn't one there, create a new entry with that name..
Note.xmlfile, click the Capabilities tab, and make sure that the ID_CAP_PUSH_NOTIFICATION capability is checked.
![Visual Studio - Windows Phone App Capabilities][14] This ensures that your app can receive push notifications. Without it, any attempt to send a push notification to the app will fail.
Press the
F5key to run the app.
A registration message is displayed in the app.
Close the app.
Note
To receive a toast push notification, the application must not be running in the foreground.
Send push notifications from your backend
You can send push notifications by using Notification Hubs from any backend via the public REST interface. In this tutorial, you send push notifications using a .NET console application.
For an example of how to send push notifications from an ASP.NET WebAPI backend that's integrated with Notification Hubs, see Azure Notification Hubs Notify Users with .NET backend.
For an example of how to send push notifications by using the REST APIs, check out How to use Notification Hubs from Java and How to use Notification Hubs from PHP.
Right-click the solution, select Add and New Project..., and then under Visual C#, click Windows and Console Application, and click OK.
![Visual Studio - New Project - Console Application][6]file and add the following
usingstatement:
using Microsoft.Azure.NotificationHubs;
In the
Programclass,. Also, replace the connection string placeholder with the connection string called DefaultFullSharedAccessSignature that you obtained in the section "Configure your notification hub."
Note
Make sure that you use the connection string with Full access, not Listen access. The listen-access string does not have permissions to send push notifications.
Add the following line in your
Mainmethod:
SendNotificationAsync(); Console.ReadLine();
With your Windows Phone emulator running and your app closed, set the console application project as the default startup project, and then press the
F5key to run the app.
You will receive a toast push notification. Tapping the toast banner loads the app.
You can find all the possible payloads in the toast catalog and tile catalog topics on MSDN.
Next steps
In this simple example, you broadcasted push notifications to all your Windows Phone 8 devices.
In order to target specific users, refer to the Use Notification Hubs to push notifications to users tutorial.
If you want to segment your users by interest groups, you can read Use Notification Hubs to send breaking news.
Learn more about how to use Notification Hubs in Notification Hubs Guidance. | https://docs.microsoft.com/en-us/azure/notification-hubs/notification-hubs-windows-mobile-push-notifications-mpns | CC-MAIN-2017-47 | refinedweb | 642 | 57.37 |
Answer by Timo Lindenschmid 30 January 2018
Hi Mack,
there are a couple of ways to move the installation across.
One very simple way is by ,as already has been mentioned, shutting down cache and then copy the cache.dat files across for example using ftp.
Another way is using the build-in backup utility to take a backup and restore the backup on your new system,. this does not require a shutdown of cache on either side.
Also make sure you grep a copy of the original cache.cpf file as this contains all the database,namespace and mapping information. | https://community.intersystems.com/user/97681/answers | CC-MAIN-2019-43 | refinedweb | 101 | 74.29 |
Games::Object - Provide a base class for game objects
package MyGameObject; use Games::Object; use vars qw(@ISA); @ISA = qw(Games::Object); sub new { # Create object my $proto = shift; my $class = ref($proto) || $proto; my $self = $class->SUPER::new(@_); bless $self, $class; # Add attributes $self->new_attr(-name => "hit_points", -type => 'int', -value => 20, -tend_to_rate => 1); $self->new_attr(-name => "strength", -type => 'int', -value => 12, -minimum => 3, -maximum => 18); ... return $self; } package MyObjectManager; use Games::Object::Manager; use vars qw(@ISA); @ISA = qw(Games::Object::Manager); sub new { my $proto = shift; my $class = ref($proto) || $proto; my $self = $class->SUPER::new(<my args>, @_); bless $self, $class; ... return $self; } my $world = new MyObjectManager; my $object = new MyGameObject; $world->add($object);
The purpose of this module is to allow a programmer to write a game in Perl easily by providing a basic framework in the form of a module that can be either subclassed to a module of your own or used directly as its own object class. The most important items in this framework are:
You can define arbitrary attributes on objects with rules on how they may be updated, as well as set up automatic update of attributes whenever the object's
process() method is invoked. For example, you could set an attribute on an object such that:
process()is called on the object.
This is just one example of what you can do with attributes.
You can define any number of arbitrarily-named flags on an object. A flag is a little like a boolean attribute, in that it can have a value of either true or false. Like attributes, flags can be created independently on different objects. No "global" flag list is imposed.
Basic functionality is provided for saving data from an object to a file, and for loading data back into an object. This handles the bulk of load game / save game processing, freeing the programmer to worry about the mechanics of the game itself.
The load functionality can also be used to create objects from object templates. An object template would be a save file that contains a single object.
New to version 0.10 of this module is object managers. An object manager is a Perl object that allows you to manage groups of related game objects. The object manager allows you to relate objects together (for example, you could define a relationship that allows certain objects to act as containers for other objects). In effect, the object manager acts as your world or universe.
Like the game object class, the manager class can be subclassed, allowing you augment its functionality. An object manager can be loaded and saved, which in turn performs a load or save of the objects being managed by it.
This documentation is a bit long. I sometimes find it easier to view this in HTML format. To do this, in the directory from which you installed the module, enter:
pod2html Object.pod > filename
Replace filename with a filename of your choice in some directory that is writable. You should then be able to view it in most browsers by typing in the URL "".
Games::Object requires perl 5.6.0 or better. While nothing in the modules restrict what Perl is required anymore, I have not tested this under older versions and do not support them.
You also will need IO::String, at least version 1.02 or better. You MUST have at least this version, as I used features specific to this version.
Version 0.11 is a patch release only to fix major bugs, no new functionality implemented. The following bugs were fixed:
Version 0.11 is compatible with version 0.10. Any workarounds you might have done to get around the aforementioned bugs should still continue to work.
Version 0.10 was a major restructuring that broke compatibility with earlier versions.
This is the optimal way to use Games::Object. You define a game object class of your own as a subclass of Games::Object. In your constructor, you create a Games::Object classed object first, then re-bless it into your class. You can then add your object class' customizations. To insure that all your customizations can be potentially
save()ed at a later time, you should add all your data to the object as attributes.
The main reason this is the ideal way to use this class will become clear when you reach the section that talks about events. Briefly, an event is defined as some change to the object, such as an attribute being modified or a boundary condition being reached. If you wish to provide code to be executed when the event is triggered, you must define it in the form of a method call. This is due to the fact that you would want your event mappings to be
save()ed as well as your attributes, and CODE references cannot be written out and read back in.
Nothing explicitly prohibits the use of this module in this fashion. Indeed, the very idea behind OOP is that a class does not need to know if it is being subclassed or not. It is permissable to use "raw" Games::Object objects in this manner.
The only limitation is that you may not be able to define event mappings, due to the limitation stated above.
This is a new feature in 0.10. It allows you to manage your objects in a larger object that acts as the "world". Objects you create are added to this world, and relationships can be maintained between objects.
One of the main advantages of using an object manager is that it greatly reduces the need for circular references. Using the manager, only one circular reference exists for each object (the manager contains a reference to the game object, the game object back to the manager). This reference is carefully broken when removing objects from the manager.
Creating an empty object can be done simply as follows:
$obj = new Games::Object;
When an object is created in this fashion, it generally has nothing in it. No attributes, no flags, nothing. There are no options at this time in the constructor to automatically add such things at object creation.
You can optionally add an ID to the object. The ID matters only when you add your object to an object manager. You can either define the ID now when you create the object, or wait until you are ready to add the object to a manager. If you wish to specify the ID now, you do so like this:
$obj = new Games::Object(-id => "id-string");
You can instantiate a new object from a point in an open file that contains Games::Object data that was previous saved with
save() by using the
load() constructor instead of
new():
$obj = load Games::Object(-file => \*INFILE);
The argument to -file can be a simple GLOB reference or an IO::File object or FileHandle object, so long as it has been opened for reading already. You can even use an IO::String object, and thus load from a string containing an object definition.
The constructor will by default use as the ID of the object the ID that was stored in the file when it was saved (if one was defined on the original object when it was first saved to the file).
A simple way to implement a load-game functionality that takes place at game initialization would thus be to open the save file, and make repeated calls to load() until the end of file was reached. Note however that this functionality is provided in the object manager module, which is covered later in this document.
You can choose to override the ID stored in the file by passing an -id option to the constructor along with the -file option. This would in essence allow you to create duplicate objects if you were so minded. Example:
my $fpos = tell INFILE; my $obj1 = load Games::Object(-file => \*INFILE); seek(INFILE, $fpos, SEEK_SET); my $obj2 = load Games::Object(-file => \*INFILE, -id => $obj1->id() . "COPY");
In this case "template" is simply a fancy term for "a file that contains a single object definition". It is simply a convenience; rather than opening a file yourself and closing it afterward just to read one object, this does those operations for you:
$obj = new Games::Object(-filename => "creatures/orc.object");
All it really is a wrapper around a call to open(), a call to the constructor with a -file argument whose value is the newly opened file, and a call to close(). As with -file, it obtains the ID of the object from the file, but you can specify an -id option to override this. Example:
$obj = load Games::Object(-filename => "creatures/orc.object", -id => "Bob");
The ID of a valid object is obtained with the
id() method. Example:
if ($obj->id() eq 'HugeRedDragon') { print "Oh-oh, NOW you've done it ...\n"; ... }
(Note that as of 0.10, you can take advantage of overloaded operators and not have to invoke the
id() method at all. See next section for details.)
If you are not using a manager, you will generally have no need to explicitly destroy a game object, as it will be cleaned up when it goes out of scope. If you are using a manager, however, which makes the object persistent, you can call
destroy() as an alternative to calling the manager's
remove() method. In fact,
destroy() will in turn call
remove() for you if the object is managed.
The
destroy() method will also invoke any
on_destroy action defined on the object before calling the manager
remove() method.
As of version 0.10, basic string and numeric comparison operators (
cmp and
<=>) are overloaded. String comparisons are performed against the
id() of the object, and numeric comparisons against the priority value. For example, this lets you do things like this:
if ($object1 eq $object2) { ... } if ($object1 eq 'RedDragon') { ... } if ($object1 > $object2) { ... }
Which are the equivalents of:
if ($object1->id() eq $object2->id()) { ... } if ($object1->id() eq 'RedDragon') { ... } if ($object1->priority() > $object2->priority()) { ... }
Where
$object1 and
$object2 are references to Games::Object objects, or objects of subclasses of Games::Object.
This overloading is accomplished via the
use overload directive. This means your subclass is free to override these and provide your own overload definitions. This will not alter the operation of Games::Object, as these overloaded operators are provided for your convenience and are not used internally.
Prior to version 0.10 of this module, all objects that you created were inherently managed by the Games::Object module. The main problem with this is that it limits your ability to augment or modify the way the module manages the objects. It also prevents you from having multiple groups of related objects independent of each other. Finally, the way it was implemented violated the spirit if not the letter of object-oriented programming rules.
Thus in version 0.10, all management functionality has been moved to a separate module called Games::Object::Manager. This module does what the various capitalized function calls did in the older versions of the module. Not only does this better adhere to OO programming rules, it allows you to much more easily augment manager functionality by simply subclassing from it.
Using an object manager will also allow you to establish relationships between objects and let the manager do the dirty work of maintaining these relationships and triggering the right actions when relationships are forged or broken.
To create an object manager is rather like creating a game object:
my $manager = new Games::Object::Manager;
Likewise, you can subclass from Games::Object::Manager, and instead call the constructor of your subclass:
my $world = new MyGames::Dungeons::World;
Creating an object manager in this manner creates it empty, meaning it has no objects in it. It does have one object relationship defined by default, which will be described in a later section.
Once you have a manager created, you can add objects to it. You first create an object using the Games::Object constructor (or the appropriate subclass constructor), then add it with the
add() method:
$manager->add($object);
In this form of the call, the manager will look on
$object for an ID to use in its internal index. If you did not define an ID when you created the object, the manager will assign a guaranteed unique ID for you.
You can specify the exact ID you want when you call
add():
$manager->add($object, "brass lantern");
If
$object already had an ID defined on it, this will both override it and cause the ID to be modified on the object to the new value.
Once you add an object to a manager, that object is now persistent. This means that, using the example above, if
$object goes out of scope, the object will continue to exist, as the manager maintains a reference to the object. Thus the manager frees you from having to maintain your own object lists.
As mentioned in the previous section, when using a manager, objects are persistent, even after the initial variable containing the reference to it goes out of scope. If you have the ID of the object, you can later retrieve a reference to the object via
find():
my $object = $manager->find('Sam the ogre');
If the ID specified is not a valid object,
find() will return undef.
The
find() method takes an additional optional argument that is the assertion flag. Setting this to a true value will cause
find() to croak with an error of the format:
Assertion failed: '$id' is not a valid/managed object ID
This is done via a call to
confess() rather than
croak() so that you can see a stack trace of the calls from your program that led to the invalid object.
Example:
$manager->find('The Player', 1);
Note that the
find() method can also be passed a game object reference instead of an ID. In this case, the method will verify that the passed object is indeed one being managed by that manager. If the object is indeed valid, it will return the object reference, otherwise it returns undef.
You can choose to remove an object from the manager by calling the
remove() method on the manager, and pass it either the ID or the object reference of the object to remove. This method call will return the reference to the object it removed, or
undef if the object was not found in the manager. Examples:
$manager->remove($creature); $manager->remove("Sam the Ogre");
Naturally, you don't have to store the reference that is returned. You can simply call it in a void context (like above) and let the object go out of scope and into oblivion.
Likewise, there is an
id() method on the manager that also validates an object in a manner similar to
find(), except that it returns the ID on success rather than the object reference.
Using
id() and
find() allows you to build code that does not have to know whether it is receiving an object reference or an ID string as an argument. If variable
$foo contains either an object or an ID, but you don't know which, then this:
$manager->find($foo);
is guaranteed to return the object reference no matter what
$foo is, and this:
$manager->id($foo);
is guaranteed to return the ID no matter what, and both will return undef if
$foo is neither.
Like
find(),
id() can take an assertion flag that will bomb the program with a stack trace if it is not valid.
A user-defined flag is any arbitrary string that you wish to use to represent some sort of condition on your objects. For example, you might want a flag that indicates if an object can be used as a melee weapon. Flags are defined on a per-object basis as you need them with the method
new_flag():
$object->new_flag(-name => "melee_weapon", -value => 1);
The only restriction on flag names is that they cannot contain characters that could be interpretted as file-control characters (thus you can't have imbedded newlines), or the "!" character (which is reserved for future planned functionality). If you stick to printable characters, you should be fine.
Note in this example that the initial value of the flag is set. If omitted, the default is for the flag to be off (or 0).
Because flags are not defined globally, you will have to define the flag on all the objects that require them, whether the initial value is on or off. Later, an easy way of doing this for large groups of objects will be presented.
You may set a user-defined flag on an object with the
set() method:
$obj->set('melee_weapon');
You can choose to set multiple flags at one time as well by specifying an array instead of a scalar:
$obj->set( [ 'melee_weapon', 'magical', 'bladed' ] );
Setting a flag that is already set has no effect and is not an error. The method returns the reference to the object.
Clearing one or more flags is accomplished in similar fashion with the
clear() method. Like
set(), it can clear multiple flags at once:
$obj->clear('cursed', 'wielded');
Two methods are provided for fetching flag status,
is() and
maybe().
The
is() method returns true if the flag is set on the object. If more than one flag is specified, then ALL flags must be set. If even one is not set, false is returned. For example:
if ($weapon->is('cursed', 'wielded')) { print "It is welded to your hand!\n"; ... }
The
maybe() method works the same as
is() for a single flag. If multiple flags are present, however, it requires only that at least one of the specified flags be set to be true. Only if none of the flags are present will it return false. Example:
if ($weapon->maybe('rusted', 'corroded', 'broken')) { print "It's not looking in good shape. Sure you want to use it?\n"; ... }
This is the heart of the module. Attributes allow you to assign arbitrary data to an object in a controlled fashion, as well as dictate the rules by which attributes are modified and updated.
A simple attribute has a name that uniquely identifies it, a datatype, and the starting value. The name needs to be unique only in the confines of the object on which the attribute is defined. Two different objects with an attribute of the same name retain separate copies of the attribute. They do not even need to be the same datatype.
An attribute of type number can take on any valid decimal numeric value that Perl recognizes. Such an attribute can be created as follows:
$obj->new_attr(-name => "price", -type => "number", -value => 1.99);
Any attempt to set this to a non-numeric value later would be treated as an error.
The datatype of int is similar to number except that it restricts the value to integers. Attempting to set the attribute to a numeric that is not an integer, either when created or later modified, is not an error, but the result will be silently truncated as if using the Perl
int() function. An int attribute can be created as follows:
$obj->new_attr(-name => "experience", -type => "int", -value => 0);
An attribute of type string is intended to contain any arbitrary, printable text. This text can contain newlines and other text formatting characters such as tabs. These will be treated correctly if the object is later saved to a file. No special interpretation is performed on the data. Such an attribute can be created as follows:
$obj->new_attr(-name => "description", -type => "string", -value => "A long blade set in an ornamental scabbard of gold.");
The any datatype is used for data that does not fall into any of the above categories. No particular interpretation is performed on the data, and no special abilities are associated with it. Use this datatype when you wish to store references to arrays or hashes. The only caveat is that these complex data structures must eventually work down to simple scalar types for the data in the attribute to be
save()d correctly later. Do not use this for object references, except for objects subclassed to Games::Object (this is covered in more detail in an upcoming section). Here is an example of using the any datatype:
$obj->new_attr(-name => "combat_skill_levels", -type => "any", -value => { melee => 4, ranged => 2, hand_to_hand => 3, magical => 5, });
There is one more datatype called object, which is intended to provided a way for storing an object reference in an attribute. However, as there are some special caveats and setup required, this is covered as a separate topic.
A "split" attribute is available only to datatypes number and int. An attribute that is split maintains two separate values for the attribute, a "real value" and a "current value" (or simply the "value"). An attribute that is split in this way has the following properties:
process()method is called (covered in a later section).
A split attribute is defined by specifying the additional parameter -tend_to_rate, as in this example:
$obj->new_attr(-name => "health", -type => "int", -tend_to_rate => 1, -value => 100);
This indicates that each time the object is processed, the current value will tend towards the real by 1. The tend-to rate is always treated as a positive number. Its sign is adjusted internally to reflect what direction the current needs to go to reach the real (thus in this case if the real were less than the current, 1 would be subtracted from the current when the object was processed).
Note in the above example that in the absense of specifying what the starting real value is, the real value will start off set to the current (in this case, the value of 100). If you wish to start off the real at a different value than the current, you add the -real_value option, as in this example:
$obj->new_attr(-name => "power", -type => "number", -tend_to_rate => 0.2, -value => 0, -real_value => 250);
An attribute's value can be "limited", in that it is not allowed to go beyond a certain range or a certain set of values.
Attributes of type number and int can be limited in range by adding the -minimum and -maximum options when the attribute is created. Note that you can choose to use one or the other or both. Example:
$obj->new_attr(-name => "hit_points", -type => "int", -tend_to_rate => 1, -value => 20, -minimum => 0, -maximum => 50);
By default, attempts to modify the attribute outside the range will cause the modifying value to be "used up" as much as possible until the value is pegged at the limit, and the remainder ignored. In the above example, if the current value were 5, and an attempt to modify it by -7 were attempted, it would be modified only by -5 as that would put it at the minimum of 0. This default behavior can be modified with the -out_of_bounds option, which is a string that has one of the following values:
Use up as much of the modifying value as possible (the default).
Ignore the modification entirely. The value of the attribute will not be changed.
Operates like use_up, except that the excess is tracked internally. Subsequent attempts to modify the attribute the other way will have to use up this amount first.
Using the track option when creating the attribute is exactly like specifying the -force option to every call to
mod_attr().
Attributes of type string can be limited by specifying a set of allowed values for the attribute. This is done when the attribute is created by adding the -values option. This is a reference to an array of strings that constitute the only allowable values for this attribute. For example:
$obj->new_attr(-name => "status", -type => 'string', -values => [ 'quiet', 'moving', 'attacking', 'dead' ], -value => 'quiet');
This feature is available only to string attributes. This allows you to map the actual value of the attribute such that when it is retrieved normally, some other text is returned instead. This is done by adding a -map option when the attribute is created. The argument to -map is a reference to a hash containing the allowed values of the attribute as keys, and the corresponding values to be returned when the attribute is fetched as values. For example:
$obj->new_attr(-name => "status", -values => [ 'quiet', 'moving', 'attacking', 'dead' ], -value => 'quiet', -map => { quiet => "It appears quiescent.", moving => "It is moving stealthily.", attacking => "It is attacking you!", dead => "It's dead, Jim.", } );
Note that the above example used -map with -values, but you're not required to do this. With this setup, retrieving the value of this attribute when it is set internally to "dead" will cause "It's dead, Jim." to be returned instead.
Object references have been vastly simplified in version 0.10 of this module. Storing a reference is as easy as specifying the
object data type:
$other_obj = new Some::Other::Class; $obj->new_attr(-name => "some_other_object", -type => "object", -value => $other_obj);
And you can modify an existing value with
mod_attr():
$obj->mod_attr(-name => "some_other_object", -value => $another_obj);
HOWEVER ...
There is one caveat with this. The class for that object MUST define the following methods:
This is responsible for creating a new object of the appropriate class and loading its data from the file at the present file position. This is passed a single argument, the file object, which you can assume is compatible with a file glob, IO::File or related object, or FileHandle object.
This is called as a class method, so the code should expect the first argument to be the class name.
This is responsible for writing the data of the object to the save file in a format that is readable by the corresponding
load() method. As with
load, it is passed a file object.
Do not store other Games::Object or Games::Object subclassed objects in the attribute. This will result in a possible infinite loop on a save of the file. If you MUST know something about another object, store the ID of the object, or set the
DONTSAVE flag on the attribute (this flag is covered in the next item).
There are a few more things you can do with attributes at creation time.
Recall above that I stated that by default, if you assign a fractional value to an attribute that is of type int that it stores it as if calling the Perl
int() function. Well, this behavior can be modified. You can specify the -on_fractional option when creating the attribute. This can be set to one of "ceil", "floor", or "round". When a fractional value results from an assignment or modification, the corresponding function in the Perl POSIX module is called on the result (in the case of "round", which is not a POSIX function, a function that performs rouding is provided internally in the module). Example:
$obj->new_attr(-name => "time", -type => "int", -on_fractional => "round", -value => 0);
There's even more you can do with fractional amounts on integer attributes. You can instruct the object to track the fractional component rather than just throw it away. Retrieving the value will still result in an integer, which by default is derived by
int()ing the factional value. For example, say that an attribute is defined like this initially:
$obj->new_attr(-name => "level", -type => "int", -track_fractional => 1, -value => 1, -maximum => 10);
Initially, retrieving the value will result in 1. Say you later add 0.5 to it. Internally, 1.5 is stored, but 1 still results when retreiving the value. If later the value becomes 1.99999, 1 is still returned. Only when it reaches 2.0 or better will 2 be returned.
You can combine -track_fractional and -on_fractional. In this case, -on_fractional refers to how the value is retrieved rather than how it is stored. Say we change the above definition to:
$obj->new_attr(-name => "level", -type => "int", -track_fractional => 1, -on_fractional => "round", -value => 1, -maximum => 10);
Now if the internal value is 1.4, retrieving it will result in 1. But if the internal value reaches 1.5, now retrieving the value will return 2.
Finally, there is a special option to
new_attr() called -flags. This allows you to specify one or more flags that affect attribute behavior. These flags are defined as single-bit flags, thus multiple flags are bitwise or'ed together (using the
| operator). Constants for these values are defined in
Games::Object but are not exported by default. You may import them into your namespace by specifying the
:attrflags tag in the
use statement. Example:
use Games::Object qw(:attrflags);
This will define the following flags:
This indicates that the value of this attribute is static, meaning it will not change. Any attempt to modify it using
mod_attr() will fail. You can circumvent this using
attr_ref().
This tells the object not to save this attribute to the save game file when the
save() method is invoked. Likewise, if you perform a
load() in place of an existing object, the current values of these attributes will be preserved.
This flag has an effect only when used with
ATTR_DONTSAVE. Normally, if you create an object with a
ATTR_DONTSAVE flag, then destroy and reload the object from a file fresh via
new() with the -file option, this attribute will disappear. If the attribute were created with the
ATTR_AUTOCREATE flag before it was saved to the file, then loading this object will cause the attribute to be auto-created for you.
The initial value of such an auto-created attribute depends on the datatype of the attribute:
intor
number
The starting value is 0, unless the attribute specified a -minimum attribute, in which case this value is used.
string
The starting value is an empty string.
any
Dependent on the type of data first assigned to it when it was created. If this was a simple scalar, this will be set to an empty string. If an array or hash reference, it will be set to an empty array or hash reference.
object
Always initialized to undef. This behavior may change in the future.
Think of this feature as similar to autovivication, but extended to the attributes.
Do not allow objects inherting from this one to inherit this attribute. It will act as if the attribute does not exist. See the section "Attribute inheritance" for details on how this works.
Do not create an accessor method for this attribute if the accessor method global option is turned on. See "Attribute accessors" for more details.
Here is an example of creating an attribute that will not be saved to a file but will be rereated when the object is created fresh from a previous save file:
$obj->new_attr( -name => "widget_table", -type => "any", -value => { canvas => $mainw->Canvas(...), title => $mainw->Label(...), }, -flags => ATTR_DONTSAVE | ATTR_AUTOCREATE, );
If this object is later saved to a file, then destroyed, then recreated from that file, this attribute will be auto-created and the value set to a hash reference pointing to an empty hash.
You can check to see if an attribute exists with
attr_exists():
if ($obj->attr_exists('encounters')) { $obj->mod_attr(-name => 'encounters', -modify => 1); } else { $obj->new_attr(-name => 'encounters', -type => 'int', -value => 1); }
An attribute's value is fetched with the
attr() method:
$str = $obj->attr('strength');
This is subject to all the interpretations mentioned above, which is summarized below:
To retrieve the real value as opposed to the current value in a split attribute, specify the string "real_value" as the second argument:
$realhp = $obj->attr('hit_points', 'real_value');
This is still subject to rules of factionals and mapping. To completely bypass all of this, retrieve the value with
raw_attr() instead:
$rawlev = $obj->raw_attr('level'); $rawlev_real = $obj->raw_attr('level', 'real_value');
An important note when dealing with attributes of datatype any that are array or hash references: When you use either
attr() or
raw_attr() (which are effectively the same thing in this case), you get back the reference. This means you could use the reference to modify the elements of the array or keys of the hash. This is okay, but modifications will not generate events. Here is an example (building on the example above for creating an attribute of this type):
$cskill = $obj->attr('combat_skill_levels'); $cskill->{melee} ++;
In all cases, if the attribute specified does not exist, undef is returned.
You may also retrieve a reference to the stored attribute value with the
attr_ref() method. Example:
$aref = $obj->attr_ref('hit_points');
This method can be used like
attr(), in that you can select either current value or the real value in the case of a split attribute. If you attempt to retrieve a
real_value when none exists, undef is returned instead. If you attempt to retrieve a reference to an attribute that does not exist, you also get back undef, but a warning is printed to STDERR, so that a subsequent "Can't use undef as a <X> reference" Perl error is not so mysterious.
This should be used with care. If you modify the value that the reference points to, you circumvent the event code (i.e. the change will not spawn attribute modified events). The purpose of this method is to allow hooks into other Perl modules that act on changes to a variable's value. A perfect example of this would be Tk. Say you design an interface to a game in Perl Tk and want to use a Tk::ProgressBar widget to show the player's current health. The constructor for this widget takes a -variable parameter, which is a reference to a variable whose value affects the position of the ProgressBar automatically. By specifying this parameter in the following way:
-variable => $player->attr_ref('hit_points'),
You now allow the ProgressBar to update automatically when the current value for the player's hit points change. Otherwise, you would have to create a package global variable to store the hit points, specify it in the the Tk::ProgressBar constructor, write a method to copy the hit points attribute value into the variable, and perform a
bind_event() to call the method when the attribute changes. This is far too much work for something that should be simple.
Modifying attributes is where a lot of the strengths of attributes lie, as the module tries to take into account typical modifier situations that are found in various games. For example, sometimes an attribute needs to be modified only temporarily. Or a modification could be thwarted by some other outside force and thus negated. And so on.
A simple modifier is defined as a modification that occurs immediately and is not "remembered" in any way. No provisions are made for preventing multiple modifications within a given cycle, either through time or code. The value of the attribute is changed and the deed is done.
There are two ways to perform a simple modification. One is to set the value directly, which would be done as in the following examples:
$obj->mod_attr(-name => "color", -value => "red"); $obj->mod_attr(-name => "price", -value => 2.58); $obj->mod_attr(-name => "description", -value => "A piece of junk.");
If an attribute is split, this would set the current value only. The real value could be set by using -real_value instead of -value:
$obj->mod_attr(-name => "health", -real_value => 0);
The other way is to modify it relative to the current value. This is available only to numeric types (int and number) as in these examples:
$obj->mod_attr(-name => "hit_points", -modify => -4); $obj->mod_attr(-name => "strength", -modify => -1);
In these cases, -modify modifies the current value if the attribute is split. To change the real value, you would use -modify_real instead.
A persistent modifier is one that the object in question "remembers". This means that this modifier can later be cancelled, thus rescinding the blessing (or curse) that it bestowed on this attribute.
Currently, this type of modifier is limited to numeric types, and must be of the relative modifier type (via -modify or -modify_real). In addition, it should be noted that the results of a persistent modifier are NOT applied immediately. They are instead applied the next time the object is
process()ed. That said, all that is needed to turn a modifier into a persistent one is adding a -persist_as option:
$obj->mod_attr(-name => "strength", -modify => 1, -persist_as => "spell:increase_strength");
The value of -persist_as becomes the ID for that modifier, which needs to be unique for that object. The ID should be chosen such that it describes what the modification is, if for no other reason than your programming sanity.
What happens now is that the next time
process() is called on the object, the "strength" attribute goes up by 1. This modification is done once. In other words, the next time after that that
process() is called, it does NOT go up by another 1.
However, this does not mean you can't have it keep going up by 1 each time if that's what you really wanted. In order to accomplish this effect, add the -incremental option:
$obj->mod_attr(-name => "health", -modify => 3 -persist_as => "spell:super_healing", -incremental => 1);
In this example, the "health" attribute will indeed increment by 3 EVERY time
process() is called.
There is another important difference between incremental and non-incremental persistent modifiers. A non-incremental modifier's effect is removed when the modifer is later cancelled. Thus in the above example, if the "strength" modifier caused it to go from 15 to 16, when the modifier is removed, it will drop back from 16 to 15. However, in the case of the incremental modifier, the effects are permanent. When the "health" modifier goes away, it does not "take away" the accumulated additions to the attribute.
Note that the effects of modifiers and tend-to rates are cumulative. This needs to be taken into account to make sure modifiers are doing what you think they're doing. For instance, if the idea is to add a modifier that saps away health by -1 each time
process() is called, but the health attribute has a -tend_to_rate of 1, the net effect will simply be to cancel out the tend-to, which may or may not be what you wanted. Future directions for this module may include ways to automatically nullify tend-to rates.
Also note that modifiers are still subject to limitations via -minimum and -maximum options on the attribute.
It was noted above that persistent modifiers stay in effect until they are purposely cancelled. However, you can set up a modifier to cancel itself after a given amount of time by adding the -time option:
$obj->mod_attr(-name => "wisdom", -modify => 2, -persist_as => "spell:increase_wisdom", -time => 10);
In this case, -time refers to the number of times
process() is called (rather than real time). The above indicates that the modification will last through the next 10 full calls to
process(). These means that after the 10th call to
process(), the modification is still in effect. Only when the 11th call is made is the modifier removed.
A self-limiting modifier can still be manually cancelled like any other persistent modifier.
As stated above, the usual behavior of persistent modifiers is that they do not take effect immediately, but rather when the next process() call is made on the object.
With version 0.05 of Games::Object, you can force a persistent modifier to take effect immediately. This is done by using the -apply_now option to the mod_attr() call. Setting this to a true value will cause mod_attr() to apply the effects of the modifier right now. This also means that any events associated with modifying the attribute will be triggered at this time.
Be careful when using this feature with incremental modifiers. This means that the target attribute will be modified now, and then again when the process() is next called on the object.
A persistent modifier, either one that is timed or not, can be set up such that it does not take effect for a given number of iterations through the
process() method. This is done via the -delay option, as in this example:
$obj->mod_attr(-name => "health", -modify => -5, -incremental => 1, -persist_as => "food_poisoning", -time => 5, -delay => 3);
This means: For the next 3 calls to
process(), do nothing. On the 4th, begin subtracting 5 from health for 5 more times through
process(). The last decrement to health will take place on the 8th call to
process(). On the 9th call, the modifier is removed.
Note that while this example combined -delay with -time and -incremental to show how they can work together, you do not have to combine all these options.
A delayed-action modifier can be cancelled even before it has taken effect.
Any persistent modifier can be cancelled at will. There are two ways to cancel modifiers. One is to cancel one specific modifier:
$obj->mod_attr(-cancel_modify => 'spell:increase_wisdom');
Note that the -name parameter is not needed. This is because this information is stored in the internal persistent modifier. You only need the ID that you specified when you created the modifier in the first place.
Or, you can choose to cancel a bunch of modifiers at once:
$obj->mod_attr(-cancel_modify_re => '^spell:.*');
The value of the -cancel_modify_re option is treated as a Perl regular expression that is applied to every modifier ID in the object. Each that matches will be cancelled. Any matching modifiers on that object will be cancelled, no matter what attribute they are modifying. This makes it easy to cancel similar modifiers across multiple attributes.
For each non-incremental modifier that is cancelled,
mod_attr() will reverse the modification that was made to the attribute, but not right away. It will instead take place the next time
process() is called. To override this and force the change at the very moment the cancellation is done, include the -immediate option set to true, as in this example:
$obj->mod_attr(-cancel_modify_re => '^spell:.*', -immediate => 1);
Any modification of an attribute via
mod_attr() may take the -force option. Setting this to true will cause the modifier to ignore any bounds checking on the attribute value. In this manner you can force an attribute to take on a value that would normally be outside the range of the attribute.
For example, the following modification would force the value of the attribute to 110, even though the current maximum is 100:
$obj->new_attr(-name => "endurance", -value => 90, -minimum => 0, -maximum => 100); ... $obj->mod_attr(-name => "endurance", -modify => 20, -persist_as => "spell:super_endurance", -force => 1);
At the same time, however, a call to
attr() to return the value of the attribute will still only return values in the range of 0 to 100. This can be very useful in that you can allow modifications to go above or below the bounds internally, but still allow only the proper ranges from the point of view of the program.
Various properties of an attribute normally set at the time the attribute is created can be modified later. These changes always take effect immediately and cannot be "remembered". The general format is:
$obj->mod_attr(-name => ATTRNAME, -PROPERTY => VALUE);
where PROPERTY is one of "minimum", "maximum", "tend_to_rate", "on_fractional", "track_fractional", "out_of_bounds".
To delete an attribute, use the
del_attr() method:
$obj->del_attr('xzyzzy');
This removes the attribute immediately. Any persistent modifiers on this attribute are removed at the same time.
New in version 0.10 is an optional feature called attribute accessors. This is a way of automatically defining new object methods when methods are first created or loaded into an object from a save file.
To turn on this feature, you will need to see a global variable to a true value before creating or loading objects:
$Games::Object::AccessorMethod = 1;
When you turn this option on, generating a new attribute with
new_attr() or by loading an object from a file will create two accessor methods to allow you to retrieve the value of the attribute and modify it in simple ways. For example, if you create an attribute called
foo after turning on this option, you will be able to make the following calls:
Returns the current value of attribute
foo. This is the equivalent of:
$object->attr('foo');
Sets the attribute to the new value, which is the equivalent of this:
$object->mod_attr(-name => "foo", -value => $value);
Modifies the value relative to the current value, as if this call were made:
$object->mod_attr(-name => "foo", -modify => $value);
In the last form described above, if you wish to do things like set up a persistent modifier, you can do so by specifying the additional parameters that you would normally pass to
mod_attr() at the end of the parameter list. For example, this:
$object->mod_foo(2, -persist_as => "foo_boost", -incremental => 1, -time => 5);
is the same as:
$object->mod_attr( -name => 'foo', -modify => 2, -persist_as => "foo_boost", -incremental => 1, -time => 5);
When accessors are turned on, you can selectively choose not to create accessors for certain attributes by using the
ATTR_NO_ACCESSOR flag.
If you choose to use persistent modifiers combined with self-limiting attributes, there are a few pitfalls that you need to watch out for.
By default, modifications made to an attribute are done in the use_up mode. This means that any modifications beyond what is needed to bring the value to minimum or maximum is discarded. When combined with persistent modifiers, this may not result in what you want.
For example, say you have an attribute that ranges from 0 to 100 and is currently at 95. It was created with the default use_up option for its -out_of_bounds parameter. Say you apply a persistent modifier of 10 with no special options. Because of the use_up option, only 5 is added to the value, resulting in 100. If later you cancel the modifier, or it was timed and expires, it will apply -10 to the value, bringing it down to 90. This is probably not what you intended.
This problem can be solved one of two ways:
mod_attr()call. This will force the attribute to 105 internally, but a normal call to
attr()will return 100.
In retrospect, it appears that perhaps track is better as the default rather than use_up.
Actions are user-defined bits of code that are designed to execute when certain things happen to your objects or attributes and flags on objects. This allows you to program into your objects a set of bahavior rules that automatically trigger when things happen, saving you the trouble of having to check for these events yourself.
In order to understand how actions work, you must first understand the callback programming model.
Callback programming is a technique where you define a chunk of code not to be run directly by you, but indirectly when some external event occurs. If you've ever done any graphics or signal programming, you've done this before. For instance, in Tk you might define a button to call some arbitrary code when it is pressed:
$mainw->Button( -text => "Press me!", -command => sub { print "Hey, the button was pressed!\n"; ... }, )->pack();
Or you may have set up a signal handler to do something interesting:
sub stop_poking_me { my $sig = shift; print "Someone poked me with signal $sig!\n"; } $SIG{TERM} = \&stop_poking_me; $SIG{INT} = \&stop_poking_me;
These are examples of callback programming. Each example above defines a set of code to be run when a particular condition (or "event") occurs. This is very similar to the way it works in Games::Object, except you're dealing with events that have to do with Game::Object entities. There is only one crucial difference, which has to do with the way the module is structured, as you'll see in the next section.
A single callback is represented as a reference to an array that consists of the following elements, in this order:
The first parameter, the object, is specified symbolically. To understand this, you must first understand that each action is considered to have from one to three objects involved, which go by the following symbolic names:
This refers to the object on which the action callback has been defined. This object will always be defined.
This is the object that caused the action to happen. This may or may not be defined depending on the nature of your action and the way it was invoked.
If an action involves the interaction of two objects, the other object can be referenced in this manner. Again, whether this is defined will depend on the action and how it was invoked.
Knowing this, consider this example of a callback:
[ 'O:self', 'mod_hit_points', 5 ]
Assuming that you define an attribute name
hit_points with attribute accessors turned on, this would invoke the following when called:
$self->mod_hit_points(5);
where
$self is the object on which the action was defined. You're not limited to calling methods defined only in Games::Object; you can call whatever methods you may have creating in your subclass.
As well as calling methods on them, you can also pass the other objects as parameters to your method call. For example:
[ 'O:self', 'strike', 'O:object', 'O:other' ]
If we assume that
strike() is a method that registers a blow with a weapon on a character,
O:object could represent the weapon being used and
O:other the creature striking the blow.
As a convienience, you can also reference
O:manager as an object argument. This represents
O:self's object manager, thus allowing you to invoke methods on the manager as well, if you wish your callback to manipulate the objects in the manager in some way.
You can specify arguments as the results of method calls or other calculations on object symbols. For example, you could do something like this:
[ 'O:self', 'mod_hit_points', 'O:object->hit_power(O:other)' ]
This passes to
mod_hit_points the result of the following when executed:
$object->hit_power($other);
In this example,
hit_power() could be a method you devised that computes the amount of striking power of weapon
$object when wielded by
$other.
Anywhere that a callback is called for, you can specify multiple callbacks, defined as multiple callback array refs in a larger array. Example:
[ [ 'O:self', 'mod_hit_points', 'O:object->hit_power(O:other)' ], [ 'O:other', 'mod_melee_skill', 1 ], ]
When invoked, the above example will call two callbacks in the order they are defined. What's more, you can use the return code of a callback to affect whether remaining callbacks in the list will be executed. If a callback in a list returns true, the next callback will be invoked. If it returns false, no further callbacks on this list will be invoked. Thus, extending the example above, you could do something like this:
[ [ 'O:self', 'can_be_hit', 'O:object', 'O:other' ], [ 'O:self', 'mod_hit_points', 'O:object->hit_power(O:other)' ], [ 'O:other', 'mod_melee_skill', 1 ], ]
In this example, it is assumed that you have created a method called
can_be_hit() in your subclass, which takes the two other object parameters and sees if this action can really be done. If
can_be_hit() returns false, then the remaining two callbacks will not be invoked.
There is another option available to you when defining multiple callbacks: failure callbacks.
A failure callback is a callback invoked if and only if the previous callback fails (i.e. returns false). This is defined by prefacing the failure callback with the string
FAIL. We can thus extend the previous example in the following manner:
[ [ 'O:self', 'can_be_hit', 'O:object', 'O:other' ], FAIL => [ 'O:manager', 'output', 'Your blow appears to have no effect!' ], [ 'O:self', 'mod_hit_points', 'O:object->hit_power(O:other)' ], [ 'O:other', 'mod_melee_skill', 1 ], ]
(Note that you do not have to use
=>; I use it because it makes it so I don't have to put quotes around
FAIL and makes the code easier to read).
In this example, we assume that you have created a class that you have subclassed to Games::Object::Manager, and it contains a method called
output that sends text output to the player. With this setup, if the call to
can_be_hit() returns false, then the following is invoked:
$manager->output("Your blow appears to have no effect!");
The remaining callbacks after the failure callback are not invoked.
Remember when I stated that wherever you have a callback you can specify a group of callbacks? The failure callback is no exception:
[ [ 'O:self', 'can_be_hit', 'O:object', 'O:other' ], FAIL => [ [ 'O:manager', 'output', 'Your blow appears to have no effect!' ], [ 'O:object', 'does_it_break' ], [ 'O:manager', 'Oh, no, your weapon breaks!' ], [ 'O:object', 'destroy' ], ], [ 'O:self', 'mod_hit_points', 'O:object->hit_power(O:other)' ], [ 'O:other', 'mod_melee_skill', 1 ], ]
In this example, if the failure callback is invoked, it will attempt to execute the four callbacks defined in the list in turn. The first one outputs the message, then the second one calls a method on the
O:object parameter. If this returns true, the remaining callbacks are executed (note that this assumes that
output() will return true all the time). There is no limit to how far you can "nest" callbacks in this manner. You could easily put yet another
FAIL after the
does_it_break test and do something else:
[ [ 'O:self', 'can_be_hit', 'O:object', 'O:other' ], FAIL => [ [ 'O:manager', 'output', 'Your blow appears to have no effect!' ], [ 'O:object', 'does_it_break' ], FAIL => [ 'O:manager', 'output', 'Lucky for you, your weapon is still intact.' ], [ 'O:manager', 'Oh, no, your weapon breaks!' ], [ 'O:object', 'destroy' ], ], [ 'O:self', 'mod_hit_points', 'O:object->hit_power(O:other)' ], [ 'O:other', 'mod_melee_skill', 1 ], ]
Thus the callback structure can be extremely versatile, allowing you to set up complex behavior with a minimum of programming.
Sometimes you may have a situation where you are not interested in having the return code checked for callbacks. Perhaps you know you always want to execute every callback in the list, or from a particular point on, but some methods inherently return 0 or false. Or you simply don't care if some actions fail or not.
To accomplish this, specify the string
NOCHECK in the callback list. All callbacks after this point will be unconditionally executed, until the end of the callback list, or until it hits the string
CHECK.
You can define arbitrary actions on an object by specifying them as parameters to the
new() constructor. An action callback is recognized as any parameter that starts with the characters
on_ or
try_. For example:
my $object = Games::Object->new( -id => "expensive camera", -on_use => [ [ 'O:self', 'pictures_left' ], FAIL => [ 'O:manager', 'output', 'Nothing happens when you press the button' ], [ 'O:self', 'take_picture', 'O:object' ], [ 'O:manager', 'output', 'Click! The camera takes a picture.' ], [ 'O:self', 'mod_pictures_left', -1 ], ], );
This now defines an arbitrary action called
on_use on this particular object. This action will be saved on a
save() like anything else on the object and reloaded with
load(). This example assumes you will have an attribute on the object called
pictures_left that indicates how much film is left in the camera.
Note that the first callback on the list above does not actually do anything except return the current value of the attribute. But note that any non-zero number is considered to be boolean true, thus in this example, if the attribute is non-zero, it will allow the camera to be used, otherwise it will do the failure callback instead and stop.
There are several ways to invoke an action on an object. One way is to use the Games::Object
action() method, which would be invoked in the following manner:
$self->action( action => "object:$action", object => $object, other => $other, );
$self is the object on which the action is defined, and
$other and
$object are the objects to put in place of
O:other and
O:object respectively in the callbacks.
Using the example of the camera object we defined in the previous example, to invoke its
on_use action, we would do something like this:
$camera->action( action => "object:on_use", object => $plant, other => $player, );
The idea here is that
$player is taking a picture of a
$plant using the
$camera.
The only problem using the
action() method is that it may not seem particularly intuitive. A better way is to have the module create action methods for you. To turn on this feature, you will need to set a global variable to true as you did with attribute accessors:
$Games::Object::ActionMethod = 1;
What this will do is create two methods, one named after the action and one with the
on_ prefix stripped. The former can be thought of as passive syntax, and the latter as active syntax. In the above example, the passive form would be expressed this way:
$camera->on_use($player, $plant);
The active syntax, however, reads more like a subject-verb-object format (and yes, I know this is biased towards English language syntax). This format swaps
$self and
$other:
$player->use($camera, $plant);
Which could be read as "The player uses the camera on the plant."
Thus the general syntax can be expressed as:
$self->$passive_form($other, $object); $other->$active_form($self, $object);
Use whichever syntax make more sense to you.
It is possible to call either form of the syntax with only one argument. In this case, the passive syntax will assume the lone parameter is
O:other and in the active syntax it will assume it is
O:self.
You may have a situation where you wish to vary what an action callback does depending on conditions other than the objects themselves. Using the camera example, you may wish to, say, do something different depending on whether the player remembered to use the flash or not.
This can be done by passing a reference to a hash of key-value pairs that represent the additional arguments. This can be done either by specifying the
args parameter to
action(), like this:
$self->action( action => "object:on_use", object => $plant, other => $player, args => { flash => 'on' }, );
Or it can be done by specifying the hash ref as the last parameter to an action method, like this:
$camera->on_use($player, $plant, { flash => 'on' });
or this:
$player->use($camera, $plant, { flash => 'on' });
To utilize this parameter in your callback, simply put
A:flash wherever you want that argument. Example:
[ 'O:self', 'take_picture', 'O:object', 'A:flash' ],
You can specify as many key-value pairs as you want in the hash and use as few or as many of them as you wish in your callbacks. Note that there is automatically one predefined argument, no matter whether you use this feature or not.
A:action will return the action that triggered this callback. In the case of object-based actions, this will always have the format
object:$action. In the above example, this would be
object:on_use. This can be useful if you decide to code a method that is invoked for more than one action because of the commonality between them, but has a few crucial differences depending on the action being invoked.
Note that if you reference an object in a callback, the callback mechanism will expect that object to be defined when the callback is invoked via an action trigger. If an object referenced from the method parameters is not defined, this merely results in
undef being passed. But if the undefined object is the first member of a callback array (and thus the object on which the method call will take place), this is a problem.
By default, Games::Object will simply bomb if you do not define that object. For example, if you do not define
O:object, then this would not bomb, since it is simply referenced in the args to the method call:
[ 'O:self', 'foo_method', 'O:object' ]
But this would bomb, since there is nothing to call a method on:
[ 'O:object', 'bar_method', 'O:self' ]
There are two ways you can deal with this. One is to insert a call to the manager
find() method to validate the object before you attempt to access methods on it, like this:
[ [ 'O:manager', 'find', 'O:object' ], [ 'O:object', 'bar_method', 'O:self' ], ]
If
find() fails, it will return
undef, which is treated as false, and no further callbacks execute. Or, you could indicate that callbacks with missing objects can be simply skipped over by using the
ACT_MISSING_OK flag when calling the action. If we take our camera example again, say we want to simulate someone taking a picture of the scenery rather than a particular object (thus no
O:object parameter). We could do this in this manner:
$self->action( action => "object:on_use", other => $player, flags => ACT_MISSING_OK, args => { flash => 'on' }, );
Or as an extra parameter after the objects like this:
$camera->on_use($player, ACT_MISSING_OK, { flash => 'on' });
or this:
$player->use($camera, ACT_MISSING_OK, { flash => 'on' });
In the latter two examples, to say that the flag parameter takes the place of the object parameter would be wrong. This would also work:
$player->use($camera, $plant, ACT_MISSING_OK, { flash => 'on' });
and the code is smart enough to know which parameter is what. If
$plant happens to contain
undef, the code works as if you didn't even specify it.
Most actions are abitrary, in that you can conjure up whatever actions you need merely by defining them on an object. A few, however, are referenced internally and have special meaning:
This is invoked on the object when it is removed from the object manager. It is invoke before the object is physically removed or any of its object relationships broken. The
O:object object is always undefined in this case, and whether or not
O:other is defined will depend on how the original
remove() method was invoked.
This is invoked if the
destroy() method is explicitly invoked on an object. Note that an
on_remove() action will follow this if the object is managed.
This is invoked after an object has been loaded from a file. It allows you to do any special processing you may wish to do at this time. For instance, if you have special data that you saved with the object that is outside the object itself, you can use this to reload that data.
A:file is set to the open file object.
An especially good use for
on_load is when using a GUI with your game. For example, your game may have a window that represents the map of your world with the player at the center. On a game load, you would most likely need to redraw the map. You can trigger this by placing an
on_load on the object tracking the map.
This is invoked after an object has been saved to a file. It allows you to save any special data outside the normal scope of the object.
Be VERY careful using the
on_load and
on_save actions. You manipulate the file at your own risk. In most cases, you can do this better by encapsulating the extra data in a Perl object, defining
load() and
save() methods on it, and storing the object on the game object in an attribute.
As well as defining actions on object, you can also define actions on attributes within objects. These actions are defined exactly as they are on objects, and the callbacks have the same structure and parameters. There are a few important differences, however:
A:*parameters) is fixed and is dependent on the action type.
O:objectand
O:otherin your callbacks, you must use an object manager.
Attribute actions are defined when the attribute is created with
new_attr(). Like with object actions, these are recognized as parameters that start with
on_ (no
try_ style actions are currently implemented). The callback structure is exactly the same as for objects.
O:self is always the object on which the attribute is defined. If the attribute action is inherited,
O:self will always be the actual object that was referenced in the original call that modified the attribute, not the inherited object.
As mentioned in the previous section, there are a set number of action types, which are described below:
This is invoked when the attribute changes value. This is invoked right after the value has changed, and every time the value changes. This means if you have an attribute with a persistent incremental modifier, each turn it changes this action will be invoked.
The action is invoked if and only if the value changes. If you make a call to modify the attribute and specify the new value or modifier such that the value ultimately does not change, the action is not invoked.
The
on_change action has the following fixed argument list:
The name of the affected attribute.
The old value before modification.
The new value after modification.
How much the attribute changed by. The sign indicates the direction of the change. This is set only for attributes of type
number or
int.
Applicable only to attribute types that can have a minimum value, this is invoked when the attribute reaches the minimum value. It is called only once when the attribute reaches minimum. It will not be called again until the attribute has been modified above minimum and then back down to minimum again.
This shares the same parameters as
on_change with the following addition:
How much under the minimum the final value is (or would be if the attribute is set up to truncate modifications under the minimum).
Applicable only to attribute types that can have a maximum value, this is invoked when the attribute reaches the maximum value. It is called only once when the attribute reaches maximum. It will not be called again until the attribute has been modified below maximum and then back up to maximum again.
This shares the same parameters as
on_change with the following addition:
How much over the maximum the final value is (or would be if the attribute is set up to truncate modifications over the maximum).
In the case where an attribute was changed and it reached minimum or maximum in the same operation,
on_change is called first.
In the case of a split attribute, actions are invoked only on changes to the current value, never the real value.
Mentioned previously is the fact that you do not invoke attribute actions directly yourself, but indirectly via changes to the attribute. How then can you pass in values for
O:other or
O:object? By specifying them when you modify the attribute, that's how.
The
mod_attr() method (and any autocreated accessor methods that modify the attribute) can take addition parameters to set these values. Say you define an attribute called
hit_points. To use
mod_attr() to modify this attribute and pass the other values, simply specify these parameters in the call:
$player->mod_attr( -name => "hit_points", -modify => 5, -other => $wizard, -object => $healing_spell, );
Or through the appropriate accessor method:
$player->mod_hit_points(5, $wizard, $healing_spell);
Note that this is very much like invoking actions (passive syntax). And just like the action method, if you leave off an object, the one that is specified is assumed to be
O:other, while
O:object is left undefined.
You can define a small set of actions for flags in a similar fashion as you do for attributes.
Actions are defined when you create a new flag with the
new_flag() method, in a manner similar to the way you define actions for attributes. Like with object actions, these are recognized as parameters that start with
on_ (no
try_ style actions are currently implemented). The callback structure is exactly the same as for objects.
O:self is always the object on which the flag is defined. If the flag action is inherited,
O:self will always be the actual object that was referenced in the original call that modified the flag, not the inherited object.
The following is a list of the available actions for flags:
Invoked when the flag is set, but only if it was not already set when the
set() method was called. If the
set() call actually had no effect because the flag was already set, this action is not invoked.
Invoked when the flag is cleared, but only if it was not already cleared when the
clear() method was called. If the
clear() call actually had no effect because the flag was already cleared, this action is not invoked.
All actions above have a single predefined parameter.
A:name refers to the name of the flag that was altered.
In order for persistent modifiers and tend-to rate calculations to be performed on an object, the object in question must be processed. This is done by calling the
process() method, which takes no arguments:
$obj->process();
What this method really is is a wrapper around several other object methods and function calls that are invoked to perform the invidual tasks involved in processing the object. Specifically,
process() performs the following sequence:
This processes all queued actions for this object. These actions are generally deferred attribute modifications, changes to attributes resulting from cancelled persistent modifiers, or arbitrarily queued actions (using the queue() method).
The queue is continually processed until it is empty. This means that if new items are queued as process_queue() runs, these items will be processed as well. However, it is easy to see how such an arrangement could lead to an infinite loop (queued method A queues method B, method B queues method A, method A queues method B ...). To prevent this, process_queue() will not allow the same action to execute more than 100 times by default on a given call. If this limit is reached, a warning is issued to STDERR and any further invokations of this action are ignored for this time through process_queue() .
This processes all persistent modifiers in the order that they were defined on the object. Changes to attributes resulting from this processing may generate events that cause your event handlers to be queued up again for processing.
The default order that modifiers are processed can be altered. See the section "Attribute modifier priority" for further details.
This processes all split attributes' tend-to rates in no particular order. Like the previous phase, this one can also generate events based on attribute changes.
You can exert some control over the order in which attributes are processed in this phase. See section "Attribute tend-to priority" for details.
There is a timing issue reguarding persistent modifiers added as a result of events generated during the process_pmod() and process_tend_to() phases.
Recall that when a persistent modifier is added, it does not take effect until the next call to process() . This means that if an event is generated in either of the aforementioned phases, and these events add more persistent modifiers, they will not take effect until the next call to process() .
Worse, if you choose to reverse the order and do process_tend_to() first, then new mods added from events generated there will be processing this turn (since process_pmod() has not yet run), but ones generated from process_pmod() will not.
You can work around this problem via the -apply_now option introduced in 0.05. Setting this to a true value in your
mod_attr() call from the event handler will cause the modifier to be applied immediately, as if it had been generated before the process() call.
More likely than not, you are going to want to process all the objects that have been created in a particular game at the same time. This can be done if you use a Games::Object::Manager-based object manager. If you do, then all the objects added to the manager can be processed by using the
process() method on the manager itself:
$manager->process();
That's all it takes. This will go through the list of objects (in no particular order by default - see section "Priorities" for details on changing this) and call the
process() method on each object.
The nice thing about the manager's
process() method is that it is a generic method. With no arguments, it calls the
process() method on the individual objects. However, if you give it a single argument, it will call this method instead. For example, say you defined a method in your subclass called
check_for_spells() , and you wish to execute it on every object being managed. You can call
process() thusly:
$manager->process('check_for_spells');
Then there is yet one more form of this function call that allows you to not only call the same method on all objects, but pass arguments to it as well. For example:
$manager->process('check_for_spells', spell_type => 'healing');
As of version 0.10, you can provide a filter that restricts the list of objects that are actually processed. This allows you to selectively process your objects. To do this, you provide it with a CODE reference before the method name that is invoked for each active object. If the code returns boolean true, then the object will be processed; boolean false, and the object is skipped.
The CODE reference can be a reference to an existing function or it can be an anonymous
sub. For example, the following will invoke method
check_creature for only those objects who's
object_type attribute is set to "creature":
$manager->process( sub { shift->attr("object_type") eq "creature" }, "check_creature" );
The following does the same thing, just broken up over more lines for better readability:
sub filter_creature { shift->attr("object_type") eq "creature"; } $manager->process( \&filter_creature, "check_creature" );
The filter code will also be passed all the arguments that you are passing to
process() that are in turn passed to the method to be called.
It is permissable to specify a method that may not exist on all of your objects. This can happen if your manager consists of objects of several different classes. In this way you're not forced to define the method on all classes. Thus this acts as a built-in filter (which is done BEFORE any custom filter you define is invoked, so you will see only objects for which the method really exists).
The return code of the manager's
process() is the number of objects that was actually processed. Note that this can be zero if your filter eliminated all of the objects from consideration, or none had the specified method.
You can modify the order in which the
process_*() subfunctions are called, or you can define your own methods to be called instead of or in addition to the defaults. How do do this depends on how you are managing your objects.
If you are managing your objects yourself, you can control the process list via the function
ProcessList() in Games::Object. This is not exported by default, so you will need to import it. Example:
use Games::Object qw(ProcessList);
This function actually serves a dual purpose. With no arguments, it will return an array containing the names of the methods currently called when the object's
process() method is called. With parameters, this will set the process list to that list of methods. Thus if you simply wish to add a new method to the existing list, you can do the following:
ProcessList(ProcessList(), "check_for_spells");
If you use the Games::Object::Manager module to manage your objects, using its
process() method will always override the settings in Games::Object. However, you can set the process list separately for each of your managers.
You can do this when you first construct the manager. For example, say you want to create a manager that uses the default Games::Object sequence but adds one more method call that you have customized in your game object subclass:
use Games::Object qw(ProcessList); use Games::Object::Manager; my $manager = Games::Object::Manager->new(-process_list => [ ProcessList(), "check_for_spells" ]);
Or, you can modify the process list after the fact using the manager's
process_list() method. This works like the
ProcessList() function from Games::Object in that it can either be used to fetch the current list or modify it. Example:
$manager->process_list($manager->process_list(), "check_for_spells");
Each object has what is called a priority value. This value controls what order the object is processed in relation to the other objects when the objects are managed, and the manager's
process() method is called. When an object is first created new (as opposed to loading from a file, where it would get its priority there), it has a default priority of 0. This default can be modified via the priority() method:
$object->priority(5);
The higher the priority number, the further to the head of the list the object is placed when
process() is called on the manager. For example, say you created a series of objects with IDs
Player1,
RedDragon,
PurpleWorm,
HellHound, and then performed the following:
$manager->find('Player1')->priority(5); $manager->find('RedDragon')->priority(3); $manager->find('PurpleWorm')->priority(3); $manager->find('HellHound')->priority(7);
If you then called
process(), first the
HellHound object would be processed, then the
Player1 object, then the
RedDragon and
PurpleWorm objects (but in no guaranteed or reproducible order for these last two). Assuming that all other objects have a default priority, they would be processed at this point (again, in no particular order).
Object priority can be changed at will, even from a user action being executed from within a
process() call (it will not affect the order that the objects are processed this time around). The current priority of an object can be obtained by specifying
priority() with no arguments.
Object priority can be a nice way of defining initiative in dungeon-type games.
NOTE: Avoid using extremely large or extremely small priority numbers. Keep your priority numbers in the range of -999_999_999 to +999_999_999, which should be more than sufficient. Values outside this range are reserved for internal use.
Starting in version 0.05 of this module, you can force the module to process objects in a more deterministic fashion when the priority values are the same. This can be controlled by modifying the exportable variable
$CompareFunction from the Games::Object::Manager module.
Specifically, this contains the name of a sort subroutine to be passed to the Perl
sort() function. By default this is set to the string
_CompareDefault, which reproduces the behavior in 0.04 and prior versions. In this manner, compatibility is preserved with previous versions.
If you set
$CompareFunction to the string
_CompareAddOrder, then objects will be processed in the order that they were added to the manager when the priorities are the same. Note that this has been changed from previous versions, which used to call this
_CompareCreationOrder.
Because the value of
$CompareFunction is passed to the sort routine verbatim, you could theoretically place any function you wish in this variable, including one you define in your main program, though be sure to prefix it with
main::. Example:
use strict; use Games::Object; use Games::Object::Manager qw($CompareFunction); sub MyCompare { # Compare like the normal function (larger priorities go first) # but when same, pick randomly. my $cmp = $b->priority() <=> $a->priority(); $cmp == 0 ? ( rand(100) < 50 ? 1 : -1 ) : $cmp; } $CompareFunction = 'main::MyCompare';
Important note: This method of altering the sort order is most effective when you load and save all of your game objects at the same time. Partial loads, saves, and creation of new objects may not lead to a consistent object ordering.
By default, tend-to rates on attributes are processed in no particular order in process_tend_to(). This can be changed by specifying a -priority value when creating the attribute in question. For example:
$obj->new_attr(-name => "endurance", -value => 100, -minimum => 0, -maximum => 100, -tend_to_rate => 1, -priority => 10);
The priority can also be later changed if desired:
$obj->mod_attr(-name => "endurance", -priority => 5);
The higher the priority, the sooner it is processed. If a -priority is not specified, it defaults to 0. Attributes with the same priority do not process in any particular order that can be reliably reproduced between calls to process_tend_to() .
By default, persistent attribute modifiers are executed in process_pmod() in the order that they were created. This is can be altered when the modifier is first created by adding the -priority parameter. For example:
$obj->mod_attr(-name => "health", -modify => 2, -incremental => 1, -persist_as => "ability:extra_healing", -priority => 10);
Assuming that other modifiers are added with the default priority of 0, or with priorities less than 10, this guarantees that the modifier above representing healing will execute before all other modifiers (like, for example, that -15 health modifier from one angry red dragon ...).
The only drawback is that a modifier priority is currently set in stone when it is first added. To change it, you would have to add the same modifier back again in its entirety. This will probably be changed in a future release.
As explained above, there are many places where method calls are queued up in an object for later execution, such as when persistent modifiers are added. The module uses the
queue() method to accomplish this, and you can use this method as well to queue up arbitrary actions. The caveat is the same with events, that the action must be a method name defined in your module.
The
queue() method takes the action method name as the first parameter, followed by any arbitrary number of parameters to be passed to your method. For example, if you were to make the following call:
$obj->queue('kill_creature', who => 'Player1', how => "Dragonsbane");
Then when
process_queue() is next called on this object, the Games::Object module will do the following:
$obj->kill_creature(who => 'Player1', how => "Dragonsbane");
This is especially useful in conjunction with action methods to achieve a delayed effect. For example, let's return to the example of the camera object from an earlier section. You could delay execution of the action to when
process() is next called (maybe to achieve the effect of a timer on the camera, or simply to synchonize things with other game actions) by doing this:
$player->queue('use', $camera, $plant, { flash => "on" } );
Which would call this when processed from the queue:
$player->use($camera, $plant, { flash => "on" } );
Object relationships refers to the ability to relate objects to one another in a well-defined manner. For example, you may wish to define a type of object that can contain other objects. The condition of objects being contained in another is an object relationship.
In order to use object relationships, you must use the Games::Object::Manager module. This is because relationships are tracked in the manager and not in the individual objects. This is to minimize the number of circular references that need to be maintained, as well as avoid trying to store object state information at the class level.
The relationship model used in Games::Object::Manager allows you to control how and when relationships occur, as well as trigger additional actions on forging or breaking relationships, via action callbacks. For this reason, the manager module mirrors the way the Games::Object module works in this regard. Specifically, the symbolic object references refer to the following:
This is the object being related. Using the example of an object relationship in which one object could contain others, this would refer to something you're trying to put into a container.
This is the object being related to. In the same example from above, this would be the container.
This is the one that instigated the action. Whenever this is not specified, this is set to the same object as
O:self (i.e. the thing being related to is assumed to have triggered the action).
An object relationship is defined by calling the
define_relation() method on the manager. The best way to describe the syntax is to define the relationship that we've been using as an example, that of a container:
$manager->define_relation( -name => "contain", -relate_method => "insert", -unrelate_method => "extract", -related_method => "contained_in", -related_list_method => "contains", -is_related_method => "is_contained_in", -flags => REL_NO_CIRCLE, );
Here is an explanation for each of the parameters:
This is the unique name for the object relationship. This is the only required parameter in the list.
If you use a name that is already in use, you will not receive any warning or error. It will instead silently redefine the existing relationship. Note that if there are already objects related in this manner when you do this, they will continue to be related in this manner.
Other parameters are optional, and some default values are based on this one. In these cases, this parameter's value is refered to as
${name}
This defines the name of the method you would like to use to relate two objects together in this manner. This is created in the namespace of the Games::Object::Manager module, much in the same way accessor methods or action methods are created in Games::Object.
If you do not define this parameter,
${name} is used instead.
This defines the name of the method you would like to use to break an existing relationship from one object to another. If you omit this parameter, it defaults to
un${name} instead.
This defines the name of the method you want to use to return what an object is related to in this manner, if anything. In our running example here, this means the container in which the object resides. If you do not define this parameter, it defaults to
${name}_to.
This defines the name of the method you want to use to return a list of objects that are related to a specified object. In our example, this means a list of objects currently inside the container. If you omit this parameter, it defaults to
${name}_list.
This defines the name of the method you want to use to see if one object is related to another in this manner. In our example, it would check to see if a specific object is contained in another. If this parameter is omitted, it defaults to
is_${name}.
This allows you to define flags that affect the behavior of the relationship. Right now, the only flag that is available is
REL_NO_CIRCLE. This tells the manager to prohibit circular relationships. For example, if this flag is on, and you already have A related to B, and B related to C, an attempt to relate C to A will cause an error.
In the example of the container relationship, we do not want this to be circular, since it makes no sense to have two objects that are each other's container.
In order to use this flag, you will need to import it, like this:
use Games::Object::Manager qw(REL_NO_CIRCLE);
Once you have your relationship defined, you can now relate two objects together. This can be done in one of two ways. One is to use the predefined
relate() method on the manager. Say for this example we're attempting to have the player place an apple in a sack (the sack will contain the apple). You would do this:
$manager->relate( -how => "contain", -self => $sack, -object => $apple, -other => $player, );
But just like with object actions, it's easier to use the method that you told the manager to create for you to relate objects. Using things, you can simplify this to:
$manager->insert($sack, $apple, $player);
Note something important here: The order of the first two arguments is exactly that of action methods.
O:self comes before
O:object. From a "grammatical" point of view (well, English grammar anyway), this may seem a little backwards, but it maintains consistency with the way Games::Object orders these parameters in the active action syntax.
For example, just like you might do this to take a picture of a plant with the camera:
$player->use($camera, $plant);
You would also do this to put new film in the camera:
$manager->insert($camera, $film, $player);
That aside, there is something you should know about relating two objects together: You can control at the object level whether the relation is allowed.
When you attempt to relate two objects together, the first thing that the manager will do is check to see if the relationship is allowed. In our example, this is done by invoking the
try_insert method on
$sack. Generically, the manager will look for
try_ prefixed to the name of the relate method on the
O:self object.
In the container example, you may wish to limit how much a container can hold by, say, comparing the size of the object in question to the total size of the container and the collective size of the objects already contained within. Thus you can define on
$sack something like this:
try_insert => [ [ 'O:self', 'can_hold', 'O:object' ], FAIL => [ 'O:manager', 'output', "It won't fit." ], ]
Assuming that attribute
size is the size of an object,
max_hold is the max size that the container can hold, and
is_held is the total size it is holding now, we could define
can_hold like this:
sub can_hold { my ($self, $object) = @_; ( $self->is_held() + $object->size() ) <= $self->max_hold(); }
If, when you try to insert the
$apple into the
$sack, the
try_insert action fails, the relate method will return 0. If it succeeds, it returns 1. If no
try_insert exists on the container, this is treated as success.
If the
try action succeeds, the object relationship is formed. But before success is returned to the caller, one more thing happens. The manager will now invoke
on_insert on the
$sack object. Generically, the manager will invoke an action by the name
on_ prefixed to the relate method. To complete this example, you would define this on
$sack:
on_insert => [ 'O:self', 'mod_is_held', 'O:object->size()' ]
And in this case you don't even have to define a method! This will invoke the following if you successfully add the
$apple to the
$sack:
$sack->mod_is_held($apple->size());
Now each time you add something to the sack, it automatically updates its internal counter that tracks the total size of all the objects in the container.
There are some variations on the relate method. You can omit the
O:other object if you wish to say that the container instigates the action itself or it doesn't matter. For example, say we extend the container relationship to handle the player carrying objects in his inventory. You could do this to indicate the player picking up the apple:
$manager->insert($player, $apple);
In which case,
O:other will be set to
$player. Or to indicate that the apple is a gift from some other creature:
$manager->insert($player, $apple, $creature);
Finally, there is one last thing: If you remember the discussion on object actions, you can see that relationships follow the same style of syntax. So you may be wondering if you can pass arbitrary arguments to the
try_insert and
on_insert actions. Yes, you can, by either specifying the
args parameter to
relate() like this:
$manager->relate( how => "contain", self => $sack, object => $apple, other => $player, args => { how => "carefully" }, )
Or by adding a hash ref as the final parameter to the relate method you defined, like this:
$manager->insert($sack, $apple, $player, { how => "carefully" });
So you can do something like this on the sack:
on_insert => [ [ 'O:self', 'mod_is_held', 'O:object->size()' ], [ 'O:object', 'dropped', 'A:how' ], ]
And define a
dropped() method on the apple object like this:
sub dropped { my ($object, $how) = @_; if ($how ne 'carefully') { my $manager = $object->manager(); $manager->output("The apple develops a nice bruise on it."); $object->set("damaged"); } }
To break an established relationship between two objects, you can call the generic
unrelate() method. Say we're going to now remove the apple from the sack of the previous example:
$manager->unrelate( how => "contain", object => $apple, other => $player, );
Note we do not need to define
self, since this is already implied to be the sack, since this is what it is currently related to. Or, you could use the unrelate method you defined:
$manager->extract($apple, $player);
Like with the relate method, the unrelate method will also attempt to call, in this example,
try_extract on the sack first to see if the action is allowed. Here is an example of such an action definition:
try_extract => [ [ 'O:self', 'is', 'open' ], FAIL => [ 'O:manager', 'output', "You'll have to open the sack first." ], ]
If this succeeds, the unrelate will be done. If not, 0 is returned to the caller and the objects remain related.
And just like with relating objects, on a successful unrelate, it will call the corresponding
on_extract on the sack:
on_extract => [ 'O:self', 'mod_is_held', '-O:object->size()' ]
which does the opposite of
on_insert, namely subtract the size of the object being extracted from the sack's running total of contained object sizes.
Sometimes you will need to relate one object to another, but need to break the existing relationship. You can let the manager do this automatically for you. If you attempt to relate an already related object, it will automatically unrelate the object first and then relate it to the new target. IMPORTANT: It is possible for the unrelate to fail. If this happens, the old relationship is left intact.
Using our example, say you have the apple in the sack and wish the player to take it out of the sack. Rather than doing two commands like this:
if ($manager->extract($apple, $player)) { $manager->insert($player, $apple); }
You can just call this:
$manager->insert($player, $apple);
Here's the sequence of actions taken by the manager:
1) Invokes try_insert on $player to see if this relationship is allowed. Return 0 if not. 2) Calls unrelate() to extract $apple from $sack. Return 0 if fails. 2a) Unrelate first invokes try_extract on $sack. Return 0 if fails. 2b) Unrelate unrelates $apple from $sack. 2c) Unrelate invokes on_extract on $sack. 3) Relate $apple to $player, caused by $player. 4) Invoke on_insert on $player.
So if we assume a
try_insert define on
$sack as we had it in a previous example, then if the sack is not open, the unrelate will fail, and hence the new relate will fail, and
insert() will return 0.
Note that this matters only if dealing with the same type of relationship. For example, if you have a "contain" relationship and an "owner" relationship, one will not affect the other unless you specifically do so in your relate
on_ action. So if A is related to B in sense "owner", and you relate A to C in sense "contain", this does not affect A --> B.
To see if an object is related to anything in a particular sense, you can either use the
related() method:
my $container = $manager->related(how => "contain", object => $apple);
or using the method you defined for the purpose when you defined the relationship:
my $container = $manager->contained_in($apple);
If the object is not related to anything in this manner,
undef is returned.
To obtain a list of objects related to this one in a particular manner, use either the
related_list() method:
my @items = $manager->related_list($sack);
or the method name you selected:
my @items = $manager->contains($sack);
To check to see if one object is related to another, you can call either the generic
is_related() method:
$manager->is_related( -how => "contain", -self => $sack, -object => $apple, );
or use the method that you specified when you defined the relationship:
$manager->is_contained_in($sack, $apple);
You can choose to force a relationship to occur, or for an existing one to be broken. This means that the
try_* actions will not be invoked. The
on_* actions will still be invoked after the relate or unrelate is done, so in the container example, the internal counter will still be updated.
Forcing a relate or unrelate can only be done using the generic
relate() and
unrelate() methods (this may change in future versions of this module). This is done by adding
force => 1 to the parameter list:
$manager->relate( -how => "contain", -self => $sack, -object => $apple, -other => $player, -force => 1, );
In this example, we would bypass the
try_insert action on
$sack.
You may sometimes wish to remove an object from the manager (perhaps simulating an object being destroyed or a creature being killed), and that object may have objects related to it or be related to other objects. In this case, the manager needs to break existing relationships.
When removing an object, the manager will first break relationships going to the object being removed, then will break relationships from the object to be removed to other objects. In each case, the manager goes down the list of object relationship types (in no particular order), and for each will perform the needed unrelates.
Each unrelate is done with
force => 1, thus no
try_* actions will be invoked, so no unrelates can fail. All
on_* actions associated with the unrelate will be invoked, however.
It can be seen from the above sections that it is possible for an unrelate operation to be triggered indirectly, either through relating to another object or removing an object. You may want to do something different in your
try_* or
on_* actions depending on what caused the unrelate.
To allow you to do this, your actions associated with the unrelate will be passed an argument that can be referenced by
A:source in your callback parameters. This will be set to one of the following strings:
This was called directly from the user, thus it can be considered a "pure" unrelate operation.
This was invoked while attempting to relate an object already related to another. This is thus the call to
unrelate() to break the existing relationship.
This is being triggered from
remove(), and is a result of the manager breaking existing relationships to the object being removed. This means that
O:self is the object being removed, and
O:object is an object that was related to it.
This is being triggered from
remove(), and is a result of the manager breaking existing relationships from the object being removed. This means that
O:object is the object being removed and
O:self is the object from which it is being unrelated.
This is most useful when dealing with a relationship broken as the result of an object being removed. To illustrate, let's say we decide to extend the container relationship to also track items in rooms. Say, then, that the sack object is being held by a creature (hence contained in the creature), and the creature is removed from the game. We would like to have the objects that the creature is holding appear in whatever room the creature was in. Assuming that the original
on_extract action is defined on the creature, you could it like this:
on_extract => [ [ 'O:self', 'mod_is_held', '-O:object->size()' ], [ 'O:object', 'drop_if_removed', 'A:source', 'O:self->contained()' ], ]
The first callback would do as in the original example, which is to update the
is_held counter. The second callback then invokes
drop_if_removed() on the object being unrelated from the creature. This method is passed the
A:source string, plus the object that the creature itself is contained in (which would ostensibly be a room). The object's method could be defined to do this:
sub drop_if_removed { my ($object, $source, $contained) = @_; my $manager = $object->manager(); if ($source eq 'remove:to') { if ($contained) { $manager->insert($contained, $object); } else { # Oops, creature was in limbo, remove the object instead. $manager->remove($object); } } 1; }
This is the reason why
remove() always breaks relations to the removed object first, thus preserving the relationships from the removed object in case you wish to do exactly as we did in the example above.
Inheritance is an object relationship that is defined automatically for you when you create an object manager. This relationship is used in a special way in the Games::Object module to allow objects to inherit things from other objects.
Inheritance can be used to create classes of objects. You could create an object, for example, that represents a master object for all creatures, then create specific creature objects that inherit a set of common characteristics from this one. Inheritance has the potential to reduce the amount of memory that your game objects use.
For convenience, the object from which you are inheriting will be referred to as a class.
The inherit relationship can be controlled like any other relationship. The following methods are defined for this relationship:
Make one object inherit from another. Remember that
O:self is the thing being inherited from. Thus if wish
$object to inherit from
$class, you would do this:
$manager->inherit($class, $object);
Break an inheritance relationship. Example:
$manager->disinherit($object);
Return the class that an object is inheriting from. In the examples above, this:
$manager->inheriting_from($object);
would return
$class.
Returns a list of objects that are inheriting from this one. In our example above, this:
my @items = $manager->has_inheriting($class);
would have
$object as one of the array members.
Check to see if one object is inheriting from another. In the above examples, this would return true:
$manager->is_inheriting_from($class, $object);
Once an object is inheriting from another via the
inherit() method on the manager, you can inherit attributes from the class. For example, say you were designing a game that had lots of dragons modeled after a particular class, in which many attributes were shared among them. You could do something like this:
my $manager = Games::Object::Manager->new(); my $class = Games::Object->new(-id => "Class Dragon"); $class->new_attr(-name => "hit_points", -type => "int", -value => 50); ... my $dragon = Games::Object->new(-id => "Red Dragon"); $manager->inherit($class, $dragon);
If you do no further processing with the
$dragon object, you can access all the attributes defined on
$class from here. For example, this:
my $hp = $dragon->attr("hit_points");
would set
$hp to 50. For all intents and purposes,
hit_points exists on
$dragon. Even
attr_exists() will tell you that the attribute exists even though it is really getting it from
$class. If you really need to tell whether the attribute really physically exists on the object as opposed to being inherited, you can call
attr_exists_here() instead. In the above example, this method would return false.
Inheritance ceases, however, the moment you modify the attribute. In this case, the attribute becomes localized to the inheriting object. If you performed a relative modification, it is made relative to the current value of the inherited attribute at the time it was modified. For example, if you did this:
$dragon->mod_attr(-name => "hit_points", -modify => -8);
Then
$dragon will now have its own copy of
hit_points set to 42.
attr_exists_here() will return true. However, if at a later time you delete the attribute from the dragon object, it will go back to inheriting the attribute from the class object.
You can have mutiple layers of inheritance. For example
$class could itself inherit from a larger class of objects. When you attempt to access an attribute on an object, it will continue checking successive inheritance until it finds an object with the attribute defined. This means that defined attributes on objects lower down on the chain will mask the values of those higher up the chain.
It should be noted that persistent modifiers are NOT inherited. If
$class has a persistent modifier on
hit_points that decreased it by 1 each turn,
$dragon would see this change in the attribute until such time that it attempted a modify, in which case it has its own local copy that has no persistent modifiers on it.
You can choose to prohibit objects from inheriting an attribute. In order to do this, set the
ATTR_NO_INHERIT flag on the attribute when you create it on the class object. It will be treated as if it does not exist. You will need to import this symbol into your code if you need it, since it is not exported by default.
Also be aware that the
ATTR_STATIC flag is honored for inherited attributes. This means if the class has an attribute that is marked
ATTR_STATIC, and the inheriting object attempts to modify it, this will be treated as an error just as if you attempted to modify it on the class object directly.
Flags are inherited in the exact same way as attributes. Like attributes, they do not physically exist on the inheriting object until such time that you modify the flag value, in which case the object gets its own copy of the flag independent of the class.
Actions are inherited in the exact same manner as attributes. In fact, actions are stored as attributes with special names.
When you inherit an action, please note that
O:self will always refer to the inheriting object, NEVER the class. For all intents and purposes, everything acts as if the action were defined directly on the inheriting object.
This is one of the more powerful features of Games::Object. This essentially provides the functionality for a save-game action, freeing you from having to worry about how to represent the data and so on.
Saving the data in an object is simple. Open a file for write, and then call the save() method on the object:
$obj->save(-file => \*SAVEFILE);
You can pass it anything that qualifies as a file, so long as it is opened for writing. Thus, for example, you could use an IO::File object. Essentially anything that can be used between <> in a print() statement is valid.
You can also do this instead:
$obj->save(-filename => "object.save");
In this case, it will create and open a file for you, save the data, and then close it again. This is useful in programs that generate object templates for use with the
load() constructor, which was covered in an earlier section.
A far more useful way to load and save objects is via the object manager.
The Games::Object::Manager object contains a
save() method just like the Games::Object module. It is called exactly the same as well, which means you can do this:
$manager->save(-file => \*SAVEFILE);
or this:
$manager->save(-filename => "game.save");
When you save an object manager, not only will it save all the objects that it contains (by calling
save() on each), but it will also save its own internal settings, including things like the process list, the next available unique object ID, object relationships, etc. In effect, it creates a complete snapshot of the manager. Assuming that you're using one object manager for your game, you can save the game to a file with one command.
You can reload saved managed data in the same way you would load an individual object. The Games::Object::Manager module has a
load() constructor that will completely rebuild the manager and all its objects from a file. Since it is called exactly like the Games::Object version, you can do this:
my $manager = Games::Object::Manager->load(-file => \*LOADFILE);
or this:
my $manager = Games::Object::Manager->load(-filename => "game.save");
You will then have a manager restored to the exact state it was in when it was first saved.
You can also choose to do a "load in place", which means you wish to set an existing manager to the contents of a save file. In this case, simply call
load() as a method from an existing manager object.
destroy()vs.
remove()
Several times in this document, the object method
destroy() and the manager method
remove() are mentioned, both in the doc itself and in some of the callback examples. What exactly is the difference between these?
One difference is, assuming the object is managed, calling
destroy() will cause an exact action to be invoked.
on_destroy() will be called on the object prior to
on_remove(). Besides this, any differences depend on how you use it.
If
destroy() is invoked from a callback, the object is managed, and you are not maintaining any other references to it, then other than the call to an additional action, there is no difference between
destroy() and
remove(). The object will go out of scope once the callback finishes executing, thus the object and its structures go away.
Where a difference arises is when you call
remove() yourself from your main program, and preserve the object reference that is returned. In this case, even though the object is removed from the manager and will no longer interact with it, the object still exists. If it has persistent modifiers or split attributes, these will continue to update if you elect to call
process() on that object. You could even add the object to another manager.
destroy(), however, will specifically delete all the internal structure of the object, including attributes and actions.
Please refer to specific sections above for examples of use.
Example data was chosen to approximate what one might program in a game, but is not meant to show how it should be done with regards to attribute names or programming style. Most names were chosen out of thin air, but with at least the suggestion of how it might look.
This is currently an alpha version of this module. While the latest major changes will hopefully be the last interface changes, there's no guarantees while this module is still alpha.
If you look at the code, you will find some extra functionality that is not explained in the documentation. This functionality is NOT to be considered stable. There are no tests for them in the module's test suite. I left it out of the doc for the alpha release until I have had time to refine it. If you find it and want to use it, do so at your own risk. I hope to have this functionality fully working and documented in the beta.
The load and save features are sorely in need of error checking and diagnostics. For instance, saving is an all-or-nothing process on the object manager, so your best bet is to run it through eval() to prevent the program from aborting on nasty errors. This will be a priority for the next version.
The test suite is getting better, but still has a few gaps, largely the result of creeping featurism.
No testing whatsoever has been done on Windows as I don't have access to a Windows environment (only Linux and Solaris are available to me). Some of the documentation is hence UNIX-centric. The module SHOULD work on Windows, as there is nothing UNIX-centric in the code itself. If you get it to work (or not) on Windows, please let me know.
Please send email to the author of the module at Peter J. Stewart <p.stewart@comcast.net> with a description of the bug. Please include any error messages you may have received. Snippets of code that trigger the bug would be helpful as well.
Top priority for the next set of releases will be performance testing and improvement (if needed). I have done very little in this area, so for realtime application YMMV with this module.
Cloning an object would be useful functionality to have.
Processing order for objects has improved, but still could use some more extensions.
A form of "undo" functionality would be WAY cool. I have something like this in another (but non-CPAN) module. I just need to port it over.
Many, MANY thanks to Tels () for helping me make some great improvements to this module and allowing me to pick his brain for ideas.
Note to users of previous versions: I have a (yet another) new email address.
Please send all comments and bug reports to Peter J. Stewart <p.stewart@comcast.net>. Also feel free to drop me a comment if you decided to use this module for designing a game. It will help me plan for future functionality. | http://search.cpan.org/~pstewart/Games-Object-0.11/Object.pod | CC-MAIN-2016-30 | refinedweb | 18,561 | 59.94 |
In this codelab you will create a stable and reusable testing harness to run performance tests on a very simple existing app. The harness will automate the collection information such as systrace logs, location requests, batterystats, graphics profiling, and more. Test failures will also be logged to files and we'll show you an example of how to write a performance-based test. Wow, that's a lot, right?! Good luck!! :)
Since the number of moving parts and components within this codelab is rather large, you will enable each piece of the harness by uncommenting existing code. This should allow you to become familiar with the harness while also allowing you to perform similar steps on your own projects. We'll end up with a test harness that logically looks something like this.
Let's get started!
First, you need to setup your development environment.
A computer with the following packages installed:
The following environment conditions should also be met:
python --versionshould output something similar to
Python 2.7.10
$JAVA_HOME/%JAVA_HOME%). The command
javac -versionshould output something similar to
javac 1.7.0_79
echo $JAVA_HOMEor
echo %ANDROID_HOME%should output the directory of a working Android SDK.
Finally, you should have an Android device connected to your computer via USB cable that can be used to run tests.
In the next step, we will download and build the test app.
In this step, we build and run the provided test app on your Android device.
Run the following to download the sample code from GitHub. Or to download it directly as a zip file go here.
git clone
When this is done, you should have a folder on your machine called
android-perf-testing.
Open up Android Studio. On the Quick Start screen, click "Open an existing Android Studio project" (or select File > Open).
In the import chooser window open the
android-perf-testing folder cloned in the previous step. Select the
settings.gradle file and click Choose.
Open the Project Navigator by clicking on the Project text button on the top left edge of the Android Studio window. At the top of the Project Navigator you can select different view perspectives, often, you're defaulted to the Android perspective after an import. Change this to Project to ensure you can see all the files we'll be working with. This process be seen in the screenshot below.
Wait for the completion of the import process by looking at the very bottom of the Android Studio screen for a "Gradle build finished" message to appear in the status bar.
You may see build errors, but we will resolve those shortly. Once the Gradle build is complete, click the green Run icon in the top of the Android Studio menu to install and run the app.
If you haven't already, plug in your Android device and unlock the device's screen. Select the device from the list of devices available to run the app in the window that appears.
Once the app is running on your device, it should look similar to this. It can take a minute or two for the app to deploy and open the first time.
You'll notice the test app has very limited functionality. Use the app to become familiar with it:
TextViewas indicated above.
ListView. The implementation behind this
ListViewhas various performance problems.
RecyclerViewwith some of the previous performance problems eliminated.
Now we have the sample app's source code imported and the app build and runs. Before we automate some testing, let's take a quick look at how the app is performing and the tooling we would normally use to diagnose a performance issue, then we'll be better prepared to automate those steps.
We're going to manually inspect the performance issue in the app. We can't automate performance testing if we don't understand what we are looking for, so let's manually look for some jank.
Launch the app again and touch the Open List View button. You'll be presented with a screen that looks like this:
Scroll to the bottom of the list; the app gets jankier the farther you scroll. This is because the app is having trouble providing the rendering subsystem a frame every 16 milliseconds (the primary cause of most UI related performance issues); therefore, Android is skipping frames and causing a visual jank. The app skips more frames as you scroll down the page. If you're persistent enough, you'll even notice that it may crash before reaching the bottom of the list.
Luckily we don't have to depend on careful eyesight to view the jank on our device. Within the Developer Options on most Android devices there is a GPU rendering profile option (near the bottom of the list). Enable this option with the Show on screen as bars option then open the app and use the Open List View option again. Your screen should look similar to this.
The green line towards the bottom/middle of the screen on the Android device indicates the important 16 millisecond barrier your app should attempt to never cross while providing frames to the rendering subsystem. Frames are drawn as a time series horizontally across the screen with each vertical bar representing a frame. The height of the bar indicates how long the frame took to draw and when any colored part of the line goes above the green bar it indicates the frame missed the 16 millisecond timeout and caused jank. The colors of the bar indicate the amount of time spent in each major phase of frame rendering. The orange part of the bar indicates app process code; this app is wasting massive amounts of time.
When you see jank in a
ListView like this you typically turn to a tool called Systrace to dig deeper and figure out what's going on. Let's do that really quick.
We aren't going to deep dive into Systrace, but we will debug the app with systrace quickly to diagnose the jank issue. This step will also make sure Systrace is configured correctly on your system, but if you are well-versed in Systrace you can skip this step.
From the Android documentation:
Systrace is a tool that will help you analyze the performance of your application by capturing and displaying execution times of your applications processes and other Android system processes.
We're using Systrace to look for performance issues in our app. When we run Systrace while using our app, it will collect data from Android then format it into an html file we can view in a web browser. When we open the Systrace results, we're hoping it will be able to help us resolve some of the underlying issues associated with our app. So far all we know is that our app is janky; it would be nice if the tooling helped us figure out why.
Click the "Terminal" text button in the bottom left of the Android Studio window.
Run the following commands there:
On Mac / Linux:
python $ANDROID_HOME/platform-tools/systrace/systrace.py --time=10 -o ~/trace.html gfx view res
On Windows:
python %ANDROID_HOME%/platform-tools/systrace/systrace.py --time=10 -o %userprofile%/trace.html gfx view res
This will run Systrace for 10 seconds, giving you enough time to reproduce the janky behaviour you saw in previous steps. Run the above command and while systrace is running, open the app and scroll through the Simple List View again. Systrace will be collecting data while you use the app. It provides a filename of the results to the output file:
trace.html .
Open a browser and view the
trace.html file. You should see a display similar to this:
This is a visualization of the performance data from your app and the system as a linear timeline during the 10 second time period.
Again, this isn't a Systrace tutorial, but notice the floating navigation bar in the upper right corner of this window that puts your cursor into different modes to interact with the trace. From top to bottom in the following screenshot, the pictured icons allow your pointer to affect the screen in the following ways:
Systrace tool used for zooming and panning.
You can also use the W,A,S,D keys on your keyboard to zoom and pan if that's easier.
First focus your attention on the top-most horizontal section of Alerts.
The Alerts row here highlights possible issues that came up during the tracing; if you click on one, a detail panel will open at the bottom of your browser and you can read the alert details. For example:
You'll notice the app's
ListView implementation has multiple issues. The alerts give you detailed information about performance improvements as well as links to documentation that can assist in resolving the issue.
The next horizontal section, typically has a header with your package name in it. If it doesn't, use the arrows to the right of the other package names to collapse the respective sections until your package name is visible.
If this is your first time using the tool you will want to focus on the Frames row (see below for a preview).
You'll find explanations for non-green Alerts in the bottom of the browser window again. In particular, look for alerts indicating your app is missing the dreaded 16ms window of time to produce a frame. The Alerts also flag other issues like non-recycling of views or incorrectly timed Layout inflating. Click some red alerts in this row until you also find one that describes Inflation during ListView recycling. There should be a lot of them.
Think about why it might be telling you that. How you would go about resolving it?
Whenever you have performance issues, Systrace is one of the primary places you should start looking for the issue. Here we validated that frames are being dropped and we found an issue with our app. But we really shouldn't be finding this issue through coordinating our test run with the Systrace manually. In the next step we will automated the test we performed, then we'll follow up by automating Systrace.
Now, let's start automating the manual test we performed before: Opening the
ListView and scrolling the entire list.
As a quick Android testing primer: there are typically two types of tests that are written for Android apps. Unit tests typically exercise discrete bits of code. Android instrumental tests exercise app components and usually simulate user input and/or mock parts of Android not specifically being tested. The Espressolibrary is used to assist with Android instrumental tests.
Espresso is a testing library that provides APIs for writing UI tests to simulate user interactions within a single app. Most user interactions can be quickly and succinctly scripted in a test using Espresso and other parts of the Android Testing Support Library.
Note: Sometimes Android tests require specific architectural designs to allow mocking parts of the Android framework. This is a complicated subject outside the scope of this particular codelab.
The first step to using Espresso is adding the library dependency to the project. Add the library by uncommenting the following lines in the
app/build.gradle file within the dependencies section. This snippet includes a couple of other libraries that are typically used in conjunction with Espresso.
androidTestCompile "com.android.support:support-annotations:${supportLibVersion}" androidTestCompile 'com.android.support.test:runner:0.5' androidTestCompile 'com.android.support.test:rules:0.5' androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
Everytime you edit the Gradle script, Android Studio will ask if you would like to sync with Gradle in a yellow bar at the top of the file viewer. Click Sync Now and wait for the build and re-configuration of the project.
Now we'll write a test that scrolls the app
ListView the same way we did manually previously.
Navigate to the
androidTest source directory in
app/src/androidTest/java/. Some test classes are already defined within the
com.google.android.perftesting package. Open the
SimpleListActivityTest class. This class holds tests you would logically write for the
SimpleListActivity class.
Uncomment the
ActivityTestRule defined in the file (see below). This JUnit Rule ensures that the specified activity is created prior to running any tests defined in the class.
@Rule public ActivityTestRule<SimpleListActivity> mActivityRule = new ActivityTestRule<>(SimpleListActivity.class);
Next, uncomment the test method called
scrollFullList and review the test method code. The test obtains the ListView within the activity under test and scrolls the entire list. The test waits for the scrolling to complete. After reviewing the code you will need to resolve the missing import errors with a right click on each error in the file.
@Test @PerfTest public void scrollFullList() throws InterruptedException { ListView listView = (ListView) mActivityRule.getActivity().findViewById(android.R.id.list); ...
Finally, uncomment the
@PerfTest at the top of the
SimpleListActivityTest class declaration. This is important for ensuring your test class is picked up by the instrumentation later.
@PerfTest public class SimpleListActivityTest {
To run all tests configured for your app you will run the
connectedCheck Gradle task. There are a few ways to run this task in Android Studio. It's good to know all of them so run through the following. Remember to make sure your test device's screen is on the device is unlocked before running your tests.
connectedChecktask.
connectedCheckgradle task again.
./gradlew :app:connectedCheck
Again, as you ran the task you probably saw exceptions running the test. On most devices the poorly written
ListView causes an
OutOfMemoryException. This can be seen by navigating to the Gradle Console text button which is available in the bottom right of the Android Studio window.
Let's continue by automating Systrace so we detect jank in our test.
Automating systrace is a little tricky since it needs to be run in parallel with the test suite. The Android development kit comes with a tool called MonkeyRunner which we can use for this. MonkeyRunner allows you to create scripts using Python 2.7 syntax, allowing for orchestration with a connected Android device. This allows us to start Systrace and then kickoff the test suite in parallel threads (among other things).
A script to automate systrace and the test suite is rather long so it has been included in the repo as a file called
run_perf_tests.py. Review the function invocation calls at the end of the script as a summary of the logic required for automation. You will notice the script follows this general structure:
You'll notice the script takes two parameters, the (1) a directory to log data to and (2) an Android device ID. Since you're running this script manually you have to retrieve the device ID manually by running this command in the Android Studio terminal window.
On Mac / Linux:
${ANDROID_HOME}/platform-tools/adb devices -l
On Windows:
%ANDROID_HOME%\platform-tools\adb devices -l
It will output something similar to this; select the device ID on the left side of the screen to run the test on (in case you have more than one).
List of devices attached 84B0456625000123 device usb:337123368X product:angler model:Nexus_6P device:angler
Now run the script in the Android Studio terminal window by typing these two commands after replacing
<INSERT ID> with the device ID. Remember to unlock your connected Android device if it has gone to sleep prior to running the second command.
On Mac / Linux:
./gradlew :app:assembleDebug :app:assembleDebugAndroidTest :app:installDebug :app:installDebugAndroidTest ${ANDROID_HOME}/tools/monkeyrunner ./run_perf_tests.py ./ <INSERT_ID>
On Windows:
The output for the first command should complete look similar to the text below. Make sure that it confirms the APKs were installed onto your test device.
... :app:preDexDebugAndroidTest UP-TO-DATE :app:dexDebugAndroidTest UP-TO-DATE :app:packageDebugAndroidTest UP-TO-DATE :app:assembleDebugAndroidTest UP-TO-DATE :app:installDebug Installing APK 'app-debug.apk' on 'Nexus 6P - 6.0' Installed on 1 device. :app:installDebugAndroidTest Installing APK 'app-debug-androidTest-unaligned.apk' on 'Nexus 6P - 6.0' Installed on 1 device. BUILD SUCCESSFUL Total time: 21.073 secs
The second command should complete with a log similar to this.
Writing logs to: ./ Using device_id: 84B0115625000732 Your ANDROID_HOME is set to: /Users/paulrashidi/android_sdk2 Cleaning data files Waiting for a device to be connected. Device connected. Starting dump permission grant Starting storage permission grant Clearing gfxinfo on device Starting test Executing systrace Exception in thread TestThread:Traceback (most recent call last): File "/Users/paulrashidi/android_sdk2/tools/lib/jython-standalone-2.5.3.jar/Lib/threading.py", line 179, in _Thread__bootstrap self.run() File "/Users/paulrashidi/android_sdk2/tools/lib/jython-standalone-2.5.3.jar/Lib/threading.py", line 170, in run self._target(*self._args, **self._kwargs) File "/Users/paulrashidi/verytmp/android-perf-testing/./run_perf_tests.py", line 51, in perform_test print device.instrument(test_runner, params)['stream'] KeyError: 'stream' Done running tests Done systrace logging Systrace Thread Done Test Thread Done Time between test and trace thread completion: 0 Starting adb pull for test files FAIL: Could not find file indicating the test run completed. OVERALL: FAILED. See above for more information.
You should have a
perftesting directory that has a limited file set populated similar to the screenshot below.
Now, let's make the script a little bit more native to the development environment so we can run it from Gradle and/or Android Studio. The easiest way to do this is to create a Gradle task that will run the monkeyrunner script. In Gradle we can do this for a typical project by defining a new task in the
buildSrc directory; let's do that.
Navigate to
buildSrc/src/main/groovy/com/google/android/perftesting/RunLocalPerfTestsTask and uncomment the code there to implement the task. Android Studio might report build errors on these Gradle tasks in the file editing window related to duplicate class definitions, it is safe to ignore those.
You should also peruse the
buildSrc/src/main/groovy/com/google/android/perftesting/PerfTestTaskGeneratorPlugin file. This is a custom Gradle plugin that queries for connected Android devices and then sets up a
RunLocalPerfTestsTask Gradle task for each connected device. The custom Gradle plugin also creates an additional generic
RunLocalPerfTests task that, when run, executes each of the device-specific gradle tasks.
Now let's install the custom Gradle plugin into our project so that all of the custom Gradle tasks will be available.
Navigate to
app/build.gradle and comment in the following lines of code. It is important that this plugin be applied after the Android Gradle plugin is configured, therefore, it is placed at the end of the
build.gradle file.
// Create performance testing tasks for all connected Android devices using a Gradle plugin defined // in the buildSrc directory. apply plugin: PerfTestTaskGeneratorPlugin
Then add this code snippet as the very first line in the
app/build.gradle file.
import com.google.android.perftesting.PerfTestTaskGeneratorPlugin
There will be a message at the top of the Android Studio screen that asks if you want to sync the Gradle files again. Perform the Gradle file sync and then navigate to the Gradle task listing. You should see the new tasks that were added by the Gradle plugin. If you have multiple devices connected you will have more tasks than the screenshot below.
The
runLocalPerfTests Gradle task is the task that will run the performance tests. A major advantage to running the monkeyrunner script from Gradle is that we made the new performance test tasks dependent on the installation of the App and Test APKs. Anytime we make changes to the codebase, as long as we're using the Gradle tasks to execute the tests, Gradle will analyze all of the project files, and rebuild the associated APKs when necessary before running the tests.
Let's make sure the new task works. Double-click on the
runLocalPerfTests task to run it. Be patient, it might take a bit to build, install, run your app and start the monkeyrunner instrumentation. Ensure the screen of your device shows the performance test running.
To make things easier, let's go ahead and add the
runLocalPerfTests gradle task to the Run Configurations menu using the Save Configuration option as pictured here.
You should now have a run configuration for
runLocalPerfTests in your gradle sidebar like pictured below:
Great!! So now you can run the performance test across the devices connected to your computer from within Android Studio and both the app and test APKs will be rebuilt as needed as you make changes to the source code. You also have the Systrace
trace.html file in the
testdata directory for debugging, but currently you don't have a whole lot of data about the tests that are being run. Let's fix that.
We've enabled Systrace and test execution, but we want more information. Additionally, since we're now running the tests via MonkeyRunner we've lost the test success/failure information. Let's fix that.
The team developed some example JUnit Rules we can use. These rules are available in the
app/src/androidTest/java/ directory in the
com.google.android.perftesting.testrules package. Let's add these rules to the existing test.
Navigate to the
app/src/androidTests directory. Open the
SimpleListActivityTest class and uncomment the
@Rule annotated member variables where the Class name begins with
Enable, such as the lines below. Resolve the import errors as well.
@Rule public EnableTestTracing mEnableTestTracing = new EnableTestTracing(); @Rule public EnablePostTestDumpsys mEnablePostTestDumpsys = new EnablePostTestDumpsys(); @Rule public EnableLogcatDump mEnableLogcatDump = new EnableLogcatDump(); @Rule public EnableNetStatsDump mEnableNetStatsDump = new EnableNetStatsDump();
Each of these rules causes a different set of data to be logged.
EnableTestTracingcalls the
Trace#
beginSectionand
Trace#endSectionmethods before and after each test. This allows you to look at the Systrace and see when each test was running to give you more context during debugging.
EnablePostTestDumpsyscollects a graphics info dumpsys output after each test. On Android Marshmallow and greater devices this includes a "Janky" percentage summary. This Jank percentage is monitored by the existing
run_perf_test.pyscript that was setup earily. The script will alert when the percentage is above a configured threshold.
EnableLogcatDumpresets the Logcat buffer on the device prior to running a test then extracts the buffer after a test. This is useful when researching a regression failure or simply wanting to see Logcat output for a test.
EnableNetStatsDumpdumps the historical network information. This can be especially useful when debugging networking related issues. For instance, if a file download test timed out you might double check to see if the network became unavailable before deep diving into the issue.
Now uncomment the
GlobalTimeout Rule to add a performance constraint. This rule ensures that any test in this class will throw an error if it takes longer than the specified amount of time. You'll notice the
scrollFullList test method has a while loop at the end of it. The while loop and the
GlobalTimeout rule result in a failure if the
ListView code isn't performant enough to allow someone to scroll the whole list in a reasonable amount of time.
@Rule public Timeout globalTimeout= new Timeout( SCROLL_TIME_IN_MILLIS + MAX_ADAPTER_VIEW_PROCESSING_TIME_IN_MILLIS, TimeUnit.MILLISECONDS);
Now navigate to the
TestListener class in the same directory. Uncomment the code for
testRunStarted and
testRunFinished methods there, resolving import build errors.
@Override public void testRunStarted(Description description) throws Exception { Log.w(LOG_TAG, "Test run started."); // Cleanup data from past test runs. deleteExistingTestFilesInAppData(); deleteExistingTestFilesInExternalData(); .... @Override public void testRunFinished(Result result) throws Exception { Log.w(LOG_TAG, "Test run finished."); ....
This will enable a battery stats collection, test failure logging, and after the tests are complete this code will also move all log files that are being collected to an accessible location where they can be pulled via simple adb commands from the host computer.
Go ahead and run the performance tests again using the
runLocalPerfTests Run Configuration at the top of the Android Studio window.
You might notice that the monkeyrunner script already flags more issues since more files are now being pulled and can, therefore, be inspected. Navigate to the
testdata directory at in the root directory of your project. You'll find quite a bit of information now being logged to that directory in a directory structure similar to the test class package structure. Navigate these files to look over the information being logged.
In the next step we'll look at the output of the current script and start fixing performance issues with information from the harness.
In your last performance test run you had performance issues. Let's now utilize the information being gathered by the harness to resolve those issues.
1) scrollFullList(com.google.android.perftesting.SimpleListActivityTest) Script: org.junit.runners.model.TestTimedOutException: test timed out after 2500 milliseconds Script: at java.lang.Thread.sleep(Native Method) Script: at java.lang.Thread.sleep(Thread.java:1031) Script: at java.lang.Thread.sleep(Thread.java:985) Script: at com.google.android.perftesting.SimpleListActivityTest.scrollFullList(SimpleListActivityTest.java:101) Script: at java.lang.reflect.Method.invoke(Native Method) Script: at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) Script: at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) Script: at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) Script: at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) Script: at org.junit.internal.runners.statements.FailOnTimeout$CallableStatement.call(FailOnTimeout.java:298) Script: at org.junit.internal.runners.statements.FailOnTimeout$CallableStatement.call(FailOnTimeout.java:292) Script: at java.util.concurrent.FutureTask.run(FutureTask.java:237) Script: at java.lang.Thread.run(Thread.java:818)
This error is also logged in a file called test.failure.log in the subdirectory of the testdata directory that corresponds to the test class and method names.
If you open the gfxinfo.dumpsys.log file you'll see a line notating an excessive amount of jank is present (in the sample below it was approximately 92%).
** Graphics info for pid 31367 [com.google.android.perftesting] ** Stats since: 19840518836088ns Total frames rendered: 323 Janky frames: 296 (91.64%) 90th percentile: 117ms 95th percentile: 125ms 99th percentile: 133ms Number Missed Vsync: 290 Number High input latency: 0 Number Slow UI thread: 295 Number Slow bitmap uploads: 286 Number Slow issue draw commands: 15
Open the systrace and observe the number of Alerts present indicating performance issues.
The Systrace alerts are clearly pointing to
ListView recycling view issues as well as the fact that calling
getView() is taking too long. To fix the problem open up the
com.google.android.perftesting.contacts.ContactsArrayAdapter class and resolve the lint error displayed.
LayoutInflater inflater = LayoutInflater.from(getContext()); // This line is wrong, we're inflating a new view always instead of only if it's null. // For demonstration purposes, we will leave this here to show the resulting jank. convertView = inflater.inflate(R.layout.item_contact, parent, false);
Should become this
if (convertView == null) { LayoutInflater inflater = LayoutInflater.from(getContext()); convertView = inflater.inflate(R.layout.item_contact, parent, false); }
Run the perf test again and refresh the trace.html file in your web browser. Hmm... looks like getView() is still causing performance problems. After looking at Bitmap code in getView a little more you realize It should actually be using something that has a cache to load the Bitmap. a common choice is Glide. So change this code:
// Let's just create another bitmap when we need one. This makes no attempts to re-use // bitmaps that were previously used in rendering past list view elements, causing a large // amount of memory to be consumed as you scroll farther down the list. Bitmap bm = BitmapFactory.decodeResource(convertView.getResources(), R.drawable.bbq); contactImage.setImageBitmap(bm);
to this:
Glide.with(contactImage.getContext()) .load(R.drawable.bbq) .fitCenter() .into(contactImage);
Run the perf test again and refresh the
trace.html file in your web browser. You could keep optimizing, but you get the idea. Now you have a repeatable way of flagging issues and then running tests to see whether specific changes make a difference.
Congrats! You've finished the codelab. Let's take just a few more minutes to sum up what you've learned and some key things to remember.
We'd really appreciate if you could fill out some feedback on your codelab experience. Click the link below to fill out a short survey and we'll use this information to iterate and improve the codelab over time.
If you'd like to learn more about performance testing see Testing Display Performance on the Android Developer documentation site.
If you'd like to learn more about Systrace, see the official documentation here.
If you're more curious about Espresso and UI testing, check out these official docs. | https://codelabs.developers.google.com/codelabs/android-perf-testing/index.html?index=..%2F..%2Fbabbq-2015&viewga=UA-68632703-1 | CC-MAIN-2017-13 | refinedweb | 4,796 | 56.55 |
Magic of mushrooms
Monday Foggy morning; rain developing later in day C10
Get results of annual PDN fungus contest C1
Peninsula Daily News Port Townsend-Jefferson County’s Daily Newspaper
50 cents
November 29, 2010
Body ID’d Ride to the Ridge as missing fisherman Drowning believed cause of death; no evidence of foul play By Paige Dickerson Peninsula Daily News
OLYMPIC NATIONAL PARK — A badly decomposed body found on a Pacific Ocean beach near the Hoh River mouth was identified Sunday as that of missing Hoh tribal fisherman David Hudson Jr. The Jefferson County Sheriff’s Office late Sunday announced the positive identification. Hudson disappeared last month when he and his sister, Elva Hudson, were fishing, and the boat capsized in the river. Elva Hudson managed to reach shore, but her brother went missing. “We were able to identify the body using a photograph of a tattoo,” Sheriff Tony Hernandez said. Deputy Dave Thomas, who works on the West End for the Jefferson County Sheriff’s Office, met with the Hudson family Sunday night and showed a picture of the tattoo on the body.
Family confirms “The family was able to positively confirm that was him,” said Chief Criminal Deputy Joe Nole. The body now will be evaluated by Prosecuting Attorney/Coroner Juelie Dalzell to officially determine the cause of death, which is believed to be drowning, Nole said. “There is no evidence of foul play, but we will evaluate it,” Nole said. Hernandez said Dalzell will determine if a DNA test is needed to confirm it is Hudson, but the family’s identification was likely sufficient. “The tattoo is pretty confirmatory,” Nole said. The body was found Thursday near the mouth of the Hoh River near the site of the historical town of Oil City. Because of its decomposition, authorities could not make independent identification. The meeting with the family originally was planned to take place Saturday night but was rescheduled for Sunday. A funeral was held for Hudson last month. His remains are being held by Kosec Funeral Home in Port Townsend. After the coroner’s evaluation, the remains will be turned over to Hudson’s family.
__________ Reporter Paige Dickerson can be reached at 360-417-3535 or at paige.dickerson@peninsuladailynews.com.
Fire district, PT deal in the works
Chris Tucker (2)/Peninsula Daily News
A motorist drives down Hurricane Ridge Road on Sunday in front of snow-covered Olympic Mountains.
5-day-a-week transportation gasses up for December By Paige Dickerson Peninsula Daily News
OLYMPIC NATIONAL PARK — Five-day-a-week transportation is on the horizon for the upcoming all-week road to Hurricane Ridge. Adventure Tours owner Willie Nelson, the Port Angeles Regional Chamber of Commerce, the city of Port Angeles and Olympic National Park are working to transport passengers to the popular snowplay spot 17 miles south of Port Angeles as part of the new effort to keep the road to the Ridge open weekdays when weather permits. Until this year, Olympic National Park kept Hurricane Ridge Road open Fridays through Sundays. A city, civic and business effort to raise $75,000 to match federal funding pays for plowing the road on the remaining days — unless falling snow precludes Justin Parker, left, pulls Trisha O’Hara and her daughter, Layla the operation until the weather clears. Turn
Parker, 8 months, on a sled on Hurricane Ridge on Sunday. They
to
Ridge/A6 live in Port Angeles.
Shelter opens to first residents of season By Julie McCormick
For Peninsula Daily News
Pact an interim measure By Julie McCormick
For Peninsula Daily News
PORT TOWNSEND — Fire district and city officials are wrapping up the lengthy process needed to even out their financial relationship after rejection last spring by Port Townsend voters of a levy aimed at equal tax for equal service. The Port Townsend levy failure in April sent officials with the city and East Jefferson Fire-Rescue scrambling for a way to fix the resulting imbalance between what taxpayers outside the city limits pay for fire service versus the lesser amount still in force for city residents. The difference is 43 cents per $1,000 property valuation, and the debt has been accruing ever since. Turn
to
Deal/A6
Julie McCormick/for Peninsula Daily News
Erik Huwyler and his dog, Red, wait for a friend to stop by and take over the dog’s care for the night while his master spends at the Winter Shelter in Port Townsend.
PORT TOWNSEND — The Port Townsend Winter Shelter opened its doors for the season at 4 p.m. Sunday. By 4:05, a half-dozen mostly middle-aged men in caps and bulky coats were making up their cots for the night in the basement of American Legion Hall. More stood talking to the volunteers from Quimper Unitarian Universalist Fellowship, veterans of the six-year-old program who always take the first of the 16 weeks the shelter is open. The guests helped themselves to fresh coffee, and there were cheese and crackers and muffins. A hot dinner was scheduled for 5:30. William Gawne, 48, a wiry man with mental health issues, sat on a dark green wool blanket that covered
his cot and haltingly told his story. “Here’s the truth,” said the Navy veteran. “I went to treatment, and I went to a halfway house on Thomas Street. That didn’t work out, and I just kind of ended up on the streets. “I kinda fell through the cracks.”
Personal issues People with mental health and substance abuse problems make up about 40 percent of the shelter’s guests, which last year totaled 82 over the season, said deForest Walker, the housing services director for Olympic Community Action Programs, or OlyCAP. Most are older than 40, many are frail from ill health and disabilities and 30 percent are military veterans, she said. Turn
to
Shelter/A6
Inside Today’s Peninsula Daily News
055082143
COME play with us!
94th year, 279th issue — 3 sections, 22 pages
Classified C5 Comics C4 Commentary/Letters A7 Dear Abby C4 Deaths A6 Horoscope C4 Lottery A2 Movies C10 Nation/World A3
Puzzles/Games Sports Things To Do Weather
C8 B1 C3 C10
A2
UpFront
Monday, November 29, 2010
Peninsula Daily News
Peninsula Daily News
Dilbert
The Samurai of Puzzles
By Scott Adams
Copyright © 2010, 2010, Peninsula Daily News
Newsmakers Celebrity scoop ■ By The Associated Press
Celebrities go offline for charity ALICIA KEYS AND Lady Gaga take charity work seriously, and they’re going offline to prove it. Gaga, Justin Timberlake, Usher and other celebrities have joined a new camKeys paign called Digital Life Sacrifice on behalf of Keys’ charity, Keep a Child Alive. The entertainers plan to Lady Gaga
The Associated Press
Courtside
viewing
Rapper Lil Wayne, left, watches the first half of an NBA basketball game between the New Orleans Hornets and the San Antonio Spurs in New Orleans on Sunday. will accept donations through text messages and bar-code technology, featured in the charity’s Buy Life campaign. Raised efforts support families affected by HIV/AIDS in Africa and India.
He became known as a serious actor, although behind the camera he was a prankster. That was an aspect of his personality never exploited, however, until “Airplane!” was released in 1980 and became a huge hit. Producers-directorswriters Jim Abrahams, David and Jerry Zucker cast their newfound comic star as Detective Drebin in a TV series, “Police Squad,” which trashed the cliches of “Dragnet” and other cop shows. Despite good reviews, NBC canceled it after only four episodes. The Zuckers and Abraham converted the series into a feature film, “The Naked Gun,” with George Kennedy, O.J. Simpson and Priscilla Presley as Nielsen’s co-stars. Its huge success led to sequels “The Naked Gun 21⁄2” and “The Naked Gun 331⁄3.” His later movies included “All I Want for Christmas,” “Dracula: Dead and Loving It” and “Spy Hard.”
African American History in Chicago, one of the first museums devoted to black history and culture in the United States, died Sunday in Chicago. Her death was confirmed by her grandson, Eric Toller. Mrs. Burroughs, an artist and high school teacher, shared with her husband, Charles, an interest in history and a desire to celebrate the achievements of black resident of what would become the city of Chicago.
Passings By The Associated Press
LESLIE NIELSEN, 84, who traded in his dramatic persona for inspired bumbling as a hapless doctor in “Airplane!” and the accident-prone detective Frank Drebin in “The Naked Gun” comedies, died Sunday in Fort Lauderdale, Fla. The Canadianborn actor died from complications from pneumonia at a hospital near his Mr. Nielsen home at 5:34 p.m., surrounded by his wife, Barbaree, and friends, his agent John S. Kelly said in a statement. Mr. Nielsen came to Hollywood in the mid1950s after performing in 150 live television dramas in New York. With a craggily handsome face, blond hair and 6-foot-2 height, he seemed ideal for a movie leading man. Mr. Nielsen first performed as the king of France in the Paramount operetta “The Vagabond King” with Kathryn Grayson. The film.”
_______
MARGARET T. BURROUGHS, 95, a founder of the DuSable Museum of
Laugh Lines RATINGS FOR SARAH Palin’s show on TLC are way down. The ratings fell 40 percent. I guess she and President Obama do have something in common after all. Jimmy Kimmel
Seen Around Peninsula snapshots
AN ELDERLY WOMAN leaving a Port Angeles grocery store struggling with a cart full of groceries in a parking lot covered with slushy snow . . . WANTED! “Seen Around” items. Send them to PDN News Desk, P.O. Box 1330, Port Angeles, WA 98362; fax 360-417-3521; or e-mail news@peninsuladaily news.com.
Peninsula Daily News PENINSULA POLL FRIDAY/SATURDAY QUESTION: If North Korea continues to attack South Korea, do you expect the U.S. to get involved militarily?
Yes
No
71.7% 23.6%
Undecided 4.7% Total votes cast: 1,240, contact Executive Editor Rex Wilson at 360-417-3530 or e-mail rex.wilson@peninsuladaily news.com.
Peninsula Lookback
From the pages of the Peninsula Daily News
1935 (75 years ago)
time to further question Washington and British Naval Lodge No. 353 of Columbia transportation Elks in Port Angeles filed chiefs, including Black Ball articles of incorporation Transport Inc. executives. with the secretary of state The Hawaiians are in Olympia. interested in re-establishIncorporators are ing ferry service among the George S. Koester, Frank islands, and Alaskans have Hickock, Devillo Lewis, passed a $22 million bond Charles H. Younger, John F. issue to establish ferry sysHenson, H.J. Schuller, C.L. tems in southwest and northwest Alaska. Sarff, H.M. Fisher, Fred Epperson, B.D. Morehead and Andrew J. Cosser. 1985 (25 years ago) This is a new incorporaAnother wintry blast tion of the Elks Naval dumped up to 13 inches of Lodge to fulfill terms of a new snow and is blamed refinancing plan now being for the death of an 87-yearcarried out. old Port Angeles man. The plan will result in Many longtime residents lowering the indebtedness are calling the two storms that was incurred by build- which brought snow to the region the worst ever. ing the present temple at Police said Francis Hall First and Lincoln streets in was killed when he was 1927. struck by a pickup truck at Front and James streets 1960 (50 years ago) while Hall was crossing the A delegation of legislastreet. tors from the nation’s newest states are touring the region’s ferry transportaDid You Win? tion system and rode the State lottery results new MV Coho from Victo■ Sunday’s Daily ria to Port Angeles. Game: 8-6-9 The lawmakers from ■ Sunday’s Keno: 07-10Alaska and Hawaii, admit17-20-28-31-38-39-47-51-53ted to the Union last year, continued into Seattle last 57-58-66-67-73-74-75-78-79 ■ Sunday’s Match 4: night aboard the Coho and took advantage of the extra 03-10-18-22
Looking Back From the files of The Associated Press
TODAY IS MONDAY, Nov. 29, the 333rd day of 2010. There are 32 days left in the year. Today’s Highlight in History: ■. On this date: ■ In 1530, Cardinal Thomas Wolsey, onetime adviser to England’s King Henry VIII, died. ■ In 1864, a Colorado militia killed at least 150 peaceful Cheyenne Indians 1961, Enos the chimp was launched from Cape Canaveral aboard the Mercury-Atlas 5 spacecraft, which orbited earth twice before returning. ■ In 1967, Secretary of Defense Robert S. McNamara announced he was leaving the
Johnson administration to become president of the World Bank. ■ In 1981, actress Natalie Wood drowned in a boating accident off Santa Catalina Island, Calif., at age 43. ■ In 1986, actor Cary Grant died in Davenport, Iowa, at age 82. ■ In 1990, the U.N. Security Council voted to authorize military action to free Kuwait if Iraq did not withdraw its occupying troops and release all foreign hostages by Jan. 15, 1991. ■ Ten years ago: Bracing the public for more legal wrangling, Vice President Al Gore said in a series of TV interviews he was prepared to contest the Florida presidential vote until “the middle of December.” Lou Groza, the Cleveland
Browns’ Hall of Fame kicker and lineman affectionately known as “The Toe,” died at age 76. ■ Five years ago: The Vatican issued a document defending a policy designed to keep men with “deep-seated” homosexual tendencies from becoming priests but said there would be no crackdown on gays who were already ordained. ■ One year ago: A gunman shot and killed four Lakewood police officers at a coffee shop. Maurice Clemmons, the accused gunman, was shot to death by a Seattle police officer two days later. Iran approved plans to build 10 industrial scale uranium enrichment facilities in defiance of U.N. demands it halt enrichment.
Peninsula Daily News for Monday, November 29, 2010
Second Front Page
Page
A3
Briefly: Nation Reducing deficit could mean health care cuts
Add in strong spending earlier in the month and robust sales online, and retailers are feeling encouraged. That’s particularly true because shoppers also scooped up fashion and other items for WASHINGTON — Job-based themselves, though mostly health care benefits could wind where they saw bargains. up on the chopping block if The question remains how President Barack Obama and many dollars shoppers are precongressional Republicans get pared to spend before Dec. 24 in serious about cutting the deficit. an economy that’s still bumpy. Budget proposals from leadDiscounts, particularly earlyers in both parties have urged morning specials, were deep shrinking or eliminating tax enough that many shoppers breaks that help make employer said they bought more than health insurance the leading they had planned. source of coverage in the nation But some said that means and a middle-class mainstay. they’re done, and they spent The idea isn’t to just raise less than last year. revenue, economists said, but finally to turn Americans into frugal health care consumers by Full plate for Congress having them face the full costs WASHINGTON — The of their medical decisions. unemployed and millionaires. Such a re-engineering was Doctors and black farmers. Illerejected by Democrats only a gal immigrants hiding from the few months ago, at the height of law and gays hiding in the milithe health care overhaul debate. tary. But Washington has Along with just about everychanged, with Republicans back body else, they all have somein power and widespread fears thing at stake as Congress that the burden of government struggles to wrap up its work debt may drag down the econfor the year. omy. Lawmakers, after taking “There is no short-term pros- Thanksgiving week off, arrive in pect of enactment,” said former town today for the final stretch Senate Majority Leader Tom of the postelection session. Daschle, a leading Democratic At the top of the to-do list adviser on health care. are the George W. Bush-era tax “However, in a tax reform cuts, enacted in 2001 and 2003 [and] deficit reducing context in and due to expire at year’s end. the long term, the prospects are President Barack Obama much better.” and most Democrats want to retain them for any couple earnHoliday shopping ing $250,000 or less a year. Republicans are bent on NEW YORK — Holiday making them permanent for spending appears to be off to a respectable start, with shoppers everybody, including the richest. The cuts apply to rates on crowding stores and malls in bigger numbers than last year wage income as well as to diviFriday and maintaining steady dends and capital gains. traffic the rest of the weekend. The Associated Press
Briefly: World European Union agrees to give Ireland bailout
Korean artillery attack. As tensions escalated across the region, with North Korea threatening another “merciless” attack, China belatedly jumped into the fray. Beijing’s top nuclear envoy, BRUSSELS — European Wu Dawei, called for an emerUnion nations agreed to give gency meeting in early Decem$89.4 billion in bailout loans to ber among regional powers Ireland on Sunday to help it involved in nuclear disarmaweather the cost of its massive banking crisis, and sketched out ment talks, including North Korea. new rules for future emergenSeoul responded cautiously cies in an effort to restore faith to the proposal from North in the euro currency. The rescue deal, approved by Korea’s staunch ally, saying it should be “reviewed very carefinance ministers at an emerfully” in light of North Korea’s gency meeting in Brussels, recent revelation of a new urameans two of the eurozone’s 16 nium-enrichment facility, even nations have now come to as protesters begged President depend on foreign help and Lee Myung-bak to find a way to underscores Europe’s struggle to contain its spreading debt cri- resolve the tension and restore peace. sis. The fear is that with Greece Fraud alleged in Haiti and now Ireland shored up, speculative traders will target PORT-AU-PRINCE, Haiti — the bloc’s other weak fiscal Nearly all the major candidates links, particularly Portugal. in Haiti’s presidential election In Dublin, Irish Prime Minis- called for Sunday’s election to ter Brian Cowen said his counbe voided amid allegations of try will take $10 billion immedi- fraud and reports that large ately to boost the capital numbers of voters were turned reserves of its state-backed away from polling stations banks, whose bad loans were across the quake-stricken counpicked up by the Irish governtry. ment but have become too much Twelve of the 19 candidates to handle. endorsed a joint statement Another $25 billion will denouncing the voting as fraudremain in reserve, earmarked ulent and calling on their supfor the banks. porters to show their anger with demonstrations against the govWar games start ernment and the country’s Provisional Electoral Council, YEONPYEONG ISLAND, South Korea — A U.S. supercar- known as the CEP. The statement included all of rier and South Korean destroyer took up position in the the major contenders but one: tense Yellow Sea on Sunday for Jude Celestin, who is backed by the Unity party of President joint military exercises that were a united show of force just Rene Preval. The Associated Press days after a deadly North
The Associated Press
Obama
suffers busted lip
President Barack Obama looks on during an NCAA basketball game between Oregon State and Howard University on Saturday in Washington, D.C. Obama is back on the hard court, but this time as spectator; it took 12 stitches to patch up his lip after he took an errant elbow in the mouth Friday morning during a game of basketball with friends and family at Fort McNair, also in D.C.
Ore. Islamic center fire feared to be retaliatory By Jonathan Cooper and Nigel Duara The Associated Press
CORVALLIS, Ore. — Someone set fire to an Islamic center said they are shocked by the allegations against him and that he had given them no hint of falling into radicalism. The fire at the Salman AlFar.
No definite link to bombing today,.
Leaked American documents reveal international diplomacy By Matthew Lee
The Associated Press
Quick Read.
Published around the world.
. . . more news to start your day
Nation: ‘Harry Potter’ stays No. 1 at box office
Nation: Boy donates life savings to fire department
Nation: Boys disappear after attempted suicide
World: Billionaire bids $330,000 for two truffles, said the donation underscores community support for rebuilding. He said West Virginia schoolchildren have raised more than $5,000 already..”
A Macau casino mogul bid $330,000 for a pair of white truffles, including one weighing about two pounds, matching the record price he paid at the same event three years ago for one of the giant fungi. Billionaire Stanley Ho made the winning bid Saturday at a charity auction through representatives of his company, Sociedade de Jogos de Macau. The pair included a huge truffle dug up in the central Tuscany region weighing about two pounds as well as one found in Molise weighing about 14 ounces. In 2007, Ho paid $330,000 for a white truffle unearthed in Tuscany weighing about 3.3 pounds.
A4
PeninsulaNorthwest
Monday, November 29, 2010
20,000 pounds of pine boughs stolen Thieves could sell them for about $5,000 EDITOR’S NOTE: This story was posted last week at. wordpress.com, the state Department of Natural Resources “Ear to the Ground” website. By Ear
to the
Ground
FORKS — Holiday wreaths and garlands made from pine boughs are a wonderful sight to behold but, unfortunately, their seasonal popularity — and the opportunity to make some quick cash — can bring out the worst in a few people. The Department of Natural Resources’ Law Enforcement Services is investigating the recent theft of up to 20,000 pounds of pine boughs clipped from a 3-acre mixed stand of white pine on state trust land the department manages. A person hunting on the Department of Natural Resources North Olympic Peninsula A few of the several hundred trees near Forks about 40 miles north of stripped of their branches by thieves seeking Forks tipped off DNR as the pine boughs to sell. theft was taking place.
Thieves got canceled and the revenue lost. The losers are the schools, county services and other beneficiaries of state trust land revenues.
Committed to Providing the
Peninsula Daily News
Forks to host ‘Twilight’ DVD release party In “Eclipse,” an evil vampire, Victoria, creates an army of “newborn” — or FORKS — A midnight release of the newly made — vampires to enact “The Twilight Saga: Eclipse” DVD will revenge on the Cullens, who killed her have a bevy of fans flocking to this mate, James, in the first movie and Twilight-famous town Friday. book, Twilight. The DVD will be officially released The DVD releases for both “Twiat 12:01 a.m. Saturday, but events, light” and “New Moon” brought hunincluding music by the Mitch Hansen dreds of fans to Forks to pick up the Band and other Twilight-related festiv- movie in the town in which the saga is ities, will be available throughout the set. night. None of the filming for any of the Movies may be pre-ordered on the movies has taken place in Forks, howDazzled by Twilight store’s website, ever.. The last book, Breaking Dawn, is The Mitch Hansen Band will play being made into two movies and is curbeginning at 9 p.m. at the Twilight rently being filmed in British ColumLounge, 81. N. Forks Ave., before fans bia, with release expected in November head back to Dazzled by Twilight, 2011 and November 2012. 11 N. Forks Ave., to pick up the film. More than 70,000 fans have visited The special Forks edition of the Forks this year to see the town that is DVD with exclusive local artwork is home to the best-sellers and blockbustavailable from the store by pre-order. ers. The movie is the third in the series The Port Angeles Walmart Superbased on the four fictional books about center, which is open 24-hours a day, Forks teen Bella Swan and her vamwill also release the DVD at 12:01 a.m. Saturday. pire boyfriend Edward Cullen. Peninsula Daily News
Congress back from Thanksgiving break Eye on Congress
Peninsula Daily News news services
WASHINGTON — The House and the Senate will return from Thanksgiving break today to begin the Dicks, 800-947-6676 (fax, last weeks of a lame-duck 202-226-1176). E-mail via their websites: session. cantwell.senate.gov; murray. Contact our legislators senate.gov; house.gov/dicks. Dicks’ North Olympic (clip and save) Peninsula office is at 332 E. “Eye on Congress” is Fifth St., Port Angeles, WA published in the Peninsula 98362. It is open from 9 a.m. to Daily News every Monday when Congress is in session noon Tuesdays and 1 p.m. about activities, roll call to 4 p.m. Thursdays and by votes and legislation in the appointment. It is staffed by Judith House and Senate. The North Olympic Pen- Morris, 360-452-3370 (fax: insula’s legislators in Wash- 360-452-3502). ington, D.C., are Sen. Maria Cantwell (D-Mountlake State legislators Terrace), Sen. Patty MurJefferson and Clallam ray (D-Bothell) and Rep. counties are represented in Norm Dicks (D-Belfair). Contact information the part-time state Legisla— The address for Cantwell ture — now in recess until and Murray is U.S. Senate, January — by Rep. Kevin Washington, D.C. 20510; Van De Wege, D-Sequim; Dicks, U.S. House, Washing- Rep. Lynn Kessler, D-Hoquiam, the House ton, D.C. 20515. Phone Cantwell at 202- majority leader; and Sen. Hargrove, 224-3441 (fax, 202-228- Jim 0514); Murray, 202-224- D-Hoquiam. Write Kessler and Van 2621 (fax, 202-224-0238);
De Wege at P.O. Box 40600 (Hargrove at P.O. Box 40424), Olympia, WA 98504; e-mail them at kessler.lynn@ leg.wa.gov; vandewege. kevin Kessler, Van De We.
Young marijuana users Highest Quality pay the cognitive price of Service
The New York Times
to Port Angeles and Sequim Area.
Randall Baugh
Q. What makes your funeral home different from others? A. Great caring staff that will bend over backward for others. We expect to be inconvenienced. Q. To date, what has been most rewarding to you with your chosen career? A. There have been so many. It will be more clear to me when I retire. Q. If you could offer only one piece of advice to our public relative to funeral service, what would that be? A. Prearrange. The financial savings and some relief of emotional burden have much benefit for yourself and those whom you leave behind. Q. What are you most proud of relative to caregiving that you and your firm represent? A. We are a team. Internally we all support each other within the same goal; serving you. It is too difficult for just one or two people to perform.
FREE FA n o R R E m o T E Avalon Wood & Gas Stoves
with purchase of Gas or Wood Stove* * Expires Nov. 30, 2010 Tax Credit Ends Dec. 31. Up To $1500 on Wood & Pellet Stoves
Everwarm Hearth & Home 257151 Highway 101 • 452-3366
CELIAC DISEASE AND GLUTEN FREE MEDS by Joe Cammack, R.Ph. Celiac Disease (CD) affects 1 in every 100 Americans. CD can seriously damage the small intestine, but is often undiagnosed or misdiagnosed. Although not experienced by all persons, the most common signs and symptoms of CD include lactose intolerance, diarrhea, excessive flatulence (passing gas), abdominal pain and bloating. 80% of people with CD are sensitive to gluten, a protein found in wheat, barley and rye. Gluten is also found in many medications, vitamins, processed foods and alcoholic beverages. Gluten consumption can damage villi (tiny protrusions in the small intestine that absorb nutrients), leading to malabsorption of nutrients with increased risk of immune and nervous system disorders. A gluten-free diet can improve the quality of life for many people with CD. We can compound gluten-free medications. Ask our pharmacist for more information.
Proud members of the Dignity Memorial® Network
105 West 4th Street Port Angeles, WA 98362 360-452-9701
108 West Alder Street Sequim, WA 98382 360-683-5242
at least 16 when they started, scientists reported last week. The findings cognitive and clinical neuroimaging at McLean, a Harvard-affiliated hospital in Belmont, Mass.. At 15, Gruber said, the brain is still changing, and “the part that modulates executive function is the last part to develop.”
Who’s playing? Visit our website and online store 452-4200
0B700945
Sequim valley Funeral CHapel 0B5103084
Harper ridgeview Funeral CHapel
0B5102000
Q. Why did you choose funeral service as a career? A. I like serving others. It seems like people really need help the most when they have just lost someone close to their heart. Q. What do you enjoy most about your job, and why? A. Helping and watching my staff provide caring, meaningful service to others. I know they are receiving personal rewards just as I have in the past. Q. How long have you worked in funeral service? A. 37 years, both on the funeral home and cemetery side of our industry. Q. What do you like most about your company? A. It is very resourceful. Through our parent company we have the greatest amount of service options that no other local provider may offer. Q. What specific resource(s) do you have available to you that you like the most in serving clientele, and why? A. Prearrangements that have National Transferability. If you move, it will move with you and will be honored to the penny, by another establishment. Q. What positive changes in funeral service have you participated in? A. More personalized service versus that of old. As new generations get older, their personal desires are different. I have learned to adapt accordingly.
BOSTON — Marijuana smoking often starts in adolescence — and the timing could not be worse, a new study suggests.
Young adults who started using the drug regularly in their early teens performed significantly worse on tests assessing brain function than did subjects who were
John Nelson’s “Live Music” column tells you. Thursdays in
Peninsula Daily News
PeninsulaNorthwest
Peninsula Daily News
Monday, November 29, 2010
A5
Legislature faces possible special session State lawmakers deal with the most significant budget deficit By Curt Woodward The Associated Press
OLYMPIA — Republican gains, Democratic leadership shake-ups and a conservative fiscal mandate from voters will shape the way Washington’s new-look Legislature deals with its most significant budget deficit yet. That work could start early next month with a possible special legislative session to rebalance the current budget. Another round of diminished tax forecasts has plunged the state’s books back into the red, and Democratic Gov. Chris Gregoire appears to be nearly out of options for fixing things within her limited authority. January’s regularly scheduled 105-day session also provides no respite, with lawmakers staring at an estimated $5.7 billion deficit in the roughly $33 billion two-year general fund. Options for plugging the hole are limited. Recession-weary voters
rejected new taxes and effectively froze revenue for two years by passing Initiative 1053. Lawmakers do have the very uncertain choice of sending a tax increase to the ballot. Meanwhile, a tidal wave of federal spending that bailed out many programs in the last two-year budget came with strings attached, leaving fewer options for cutting medical services and college spending. Although they lost members in the November elections, Democrats remain in control of both chambers. That gives them broad control of the Legislature’s agenda, from deciding which bills get heard in committee to setting the terms of the final budgetbalancing task. The minority party can have an effect, however, if its margin is close enough to build a philosophical majority on particular policies. (On the North Olympic Peninsula, incumbent state Rep. Kevin Van De Wege,
D-Sequim, was reelected to a third twoyear term. (Steve Tharinger, D-Sequim, is keeping Tharinger his seat as one of the three Clallam County commissioners while also serving in the state House as the succes- Van De sor to retir- Wege ing Rep. Lynn Kessler, D-Hoquiam. (Both Van De Wege and Tharinger beat their Republican opponents in the Nov. 2 election.)
27-22 in favor of Dems Senate Republicans made perhaps the most consequential inroads in that regard, gaining four seats by winning back suburban seats they had lost during the George W. Bush administration. That puts the Senate balance at 27-22 in favor of Democrats, with one race still headed for a recount but thought unlikely
to change. As Senate Minority Leader Mike Hewitt notes, attracting just three votes from moderate and conservative Democrats would give Republicans enough votes to get something passed or blocked in the Senate. “I’ve made it very clear to the governor and others that we’re not willing to give them any political cover if they’re not going to be serious about making this (budget) sustainable going forward,” said Hewitt, R-Walla Walla. “We’ve been asking for this now for five years.” A smaller margin isn’t the end of changes for Senate Democrats. The biggest shift is leadership of the budget-writing Ways and Means Committee, which gets a new chairman in Sen. Ed Murray, D-Seattle. Veteran Sen. Margarita Prentice, D-Renton, is stepping down from that post to become the chamber’s president pro tem, where she will preside over floor sessions when Lt. Gov. Brad Owen is unavailable. Murray will be the Senate’s lead budget writer, delegating less of the nitty-
gritty work than Prentice did in years past. Construction budget duties will be handled by Vice Chairman Derek Kilmer, D-Gig Harbor, who takes over for Sen. Karen Fraser, D-Olympia. Fraser is seeking to become chairwoman of the majority caucus, presiding over the Democrats’ closed strategy meetings.
Two more recounts Republicans had a bigger gap to make up in the House, where Democrats had compiled an impressive 61-member majority out of 98 seats before this year’s elections. The House GOP was able to claim an open seat in the Vancouver area, retake a Spokane-area spot and knock off three incumbent Democrats. Two of those races are heading for recounts but reversals can be difficult in legislative races because the pool of votes is so small. Republicans also count one intraparty Republican battle as a net gain: J.T. Wilcox defeated Rep. Tom Campbell, R-Roy, who acted as an independent and actually was granted a com-
mittee chairmanship by the Democrats. House Democrats have their own leadership shakeups. Rep. Pat Sullivan, D-Covington, will succeed Kessler as House majority leader — the caucus’ second-ranking position behind Speaker Frank Chopp, D-Seattle. “We’ve got to get beyond politics and get to the point where people can feel free to suggest ideas. Boy, we certainly need them,” Sullivan said. “It’s a different time and the way we do government has to be much different.” The House also could have a new budget-writer, since sitting Ways and Means Committee Chairwoman Kelli Linville, D-Bellingham, may be defeated in a very close race. House Minority Leader Richard DeBolt, R-Chehalis, echoed Hewitt’s hope for more bipartisan cooperation following the elections. “Maybe one-party control will not be so lopsided and allow for different opinions and different solutions to the problems that we face,” he said.
Washington prisoners helping save endangered frogs By Stacia Glenn.
Tacoma News Tribune
LITTLE ROCK, Thurston County — in Little Rock called “Frogga Walla,” the two men spend nine hours a day feeding and tending to the endangered species. “We baby them like little kids,” said Goodall, who is serving time at the prison near Littlerock for possession of drugs with the intent Getting a head start to deliver. The amphibians then “They’ve got personaliare coddled and cared for ties, too, it seems like.” over a nine-month span before being released in the ‘Like little kids’ wetlands at Joint Base Much to the surprise of Lewis-McChord. “It gives them a head research scientists and zookeepers also participating start so once they’re put in a “head start” program to back into the wild, they bolster the dwindling popu- have a better chance of surlation of the frogs, Goodall, viving, reproducing and themselves,” 45, and Greer, a 46-year-old protecting convicted robber, have Ellis said. After years of raising the raised the biggest, healthifrogs, their keepers have est amphibians. “People may not think learned little tricks to help prisons are the right place the endangered amphibians for this type of environmen- survive and strengthen. They now know to monital work, but it’s the ideal place,” said Chad Lewis, tor the water constantly, to spokesman for the state reduce the number of tadDepartment of Corrections. poles kept in each tank and “We have folks with to be on the lookout for plenty of time in a con- aggressive frogs that might trolled environment. That’s snap up all the food before their meek brethren get a what you need.” The Oregon spotted frog bite. was listed as an endangered At Cedar Creek, Gre.
your
AFFORDABLE
SUPPORT
Proven Security Systems make anytime access safe and enjoyable with your own security access key Access to 2 locations on the Peninsula PLUS 1,300 clubs nationwide to use when you travel
Shhh... Bob’s sleeping... He’s dreaming of his boyhood home in snowy Montana. His Dad just gave him a gift certificate to the Bushwhacker Restaurant.
457-3200
10% OFF
portangeleswa@anytimefitness.com
Corner of Sequim Ave, & Old Olympic Highway
Adjacent to Joshua’s Restaurant
112 Del Guzzi Dr.
“Little Bobby, it’s a dream restaurant you’ll realize some day. It will make a lot of people happy.”
COUPON
sequim@anytimefitness.com
10135 Old Olympic Hwy
Sweet Dreams...
Gift
CERtIFICatES Coupon good through 12/31/10.
Toyota’s Special Camry LE Lease
00 189 or $ 1,000 Toyota Cash Back $
MO.*
*
or
0.0 % APR
Up to 60 mos.** plus Toyota’s 2 Year Maintenance included
TesT DRive ToDay – see iTs value *36 Month Closed-End Lease. $2,244 due at signing, plus tax, license and negotiable documentary fee. Residual is $13,779.50, Purchase Option. Security deposit waived. TFS Tier 1+ On Approval of Credit. **0.0% APR up to 60 months for TFS Tier 1, 2, 3 Customers On Approval of Credit. Offer expires 1/1/11. Does not include tax, license & documentation fees. All vehicles subject to prior sale. Photos for illustration purposes only. Not responsible for typographical errors. A negotiable dealer documentary fee up to $150 may be added to the sale price. See Dealer for details.
You Can Count On Us!
WILDER
95 Deer Park Road • Port Angeles – 1-800-927-9379 • 360-457-8511
0B5104726
683-4110
Port Angeles
The besT CaRs CosT you less!
By Bushwhacker Bob
(360) 457-4113
05097024
Sequim
CaMRy
Confessions of a Restaurateur
You’ll get a FREE personal training session to help you get started
2011 ToyoTa
MPG
1527 East First Street
Easy monthly payments. Single, Couple, and Family plans
NEW
EPA estimate, actual mileage will vary.
“Be kind to yourself and each other” ~ Bob G.
Now you can fit exercise into your busy schedule ANYTIME. Once the eggs hatch and The Associated Press grow to about an inch long, the tadpoles are given free A female Oregon spotted frog from the Owyhee reign of the tank and fed a Mountains of Southwestern Idaho, rests in the hand of a researcher. labor-intensive meal.
31
0B5104130
ANYWHERE.
“Dad, you have made me happy.”
neighborhood club!
SECURE
Frogs released doubles
“Dad, what’s the Bushwhacker Restaurant?”
ANYTIME 24/7.
A6
PeninsulaNorthwest
Monday, November 29, 2010 — (J)
Peninsula Daily News
Toys for Tots Ridge: Bus to make daily trips drive starts in Clallam Continued from A1
By Rob Ollikainen Peninsula Daily News
If Daniel Abbott had his way, the Marine Corps Reserve Toys for Tots program would be called Toys for Tots to Teens. Abbott, Toys for Tots coordinator in Clallam County, said it’s not just the young kids whose families need help providing Christmas presents. Abbott said there are about 2,000 kids — including teenagers — in the county who will qualify for the annual holiday toy collection program. “I spend most of my time buying toys for teens,” Abbott said. The program gets toys to needy families to ensure that every kid receives a Christmas present, Abbott said.
Drop locations “We have drop locations all over the county,” Abbott said. There are 42 toy dropoff locations in Clallam County — 20 in Port Angeles, 17 in Sequim and five in Forks — where new, unwrapped toys can be dropped off. The list is available at. toysfortots.org. Live drop offs are staged on the weekends at the Port Angeles and Sequim
Starting in mid-December, Nelson’s 12-passenger bus will leave twice a day Wednesdays through Sundays from the Port Angeles Visitor Center, in front of The Landing mall at 121 E. Railroad Ave., and the Vern Burton Community Center, 308 E. Fourth St. “As it sits right now, we’ll be departing from the [visitor center] at 9 a.m. and 1 p.m. and the Vern Burton at about 9:05 a.m. and 1:05 p.m.,” Nelson said. “The Vern Burton will be a good place for people because there is free parking in the city’s lot there. “We are looking at returning at about 11 a.m. and 3:30 p.m.” The city will be using its Chris Tucker/Peninsula Daily News senior services van for backup Numerous vehicles sit parked at the Hurricane Ridge Visitor Center, on days when Nelson and his located 5,242 feet above seal level, on Sunday. bus might not be available, City Manager Kent Myers road open daily, except for said. avalanche danger and “[The service’s] intention is for locals and weather closures, this winter visitors who would like to go up and spend a Begins Dec. 17 thanks to more than $75,000 The five-day transporta- in donations raised on the few hours but don’t want or can’t drive tion service will begin North Olympic Peninsula. themselves.” Dec. 17, when a “grand openThe National Park SerWillie Nelson ing” will be held at the top of vice will contribute $250,000 offering transportation service to Hurricane Ridge Hurricane Ridge to celebrate to cover the rest of the anticithe fact that the road will be pated cost. drive it, said Russ Veenema, Reservations are accepted open seven days a week. Hurricane Ridge Road executive director of the Port and encouraged, Nelson said. “We really look forward to being able to have that ser- currently is on an “extended Angeles Regional Chamber To make a reservation or vice for people,” Nelson said. weekend” schedule open Fri- of Commerce. for more information, phone day through Sunday as workBecause about $2,000 Nelson at 360-565-1139 or “Its intention is for locals and visitors who would like ers are trained to properly more than the required 360-460-7131. $75,000 was raised to keep to go up and spend a few plow the road. For Hurricane Ridge The Park Service requires the road open, those funds hours but don’t want or can’t weather information, a all motorists to carry chains will be used as a subsidy to drive themselves.” recorded hot line can be past the Heart O’ the Hills help maintain service, Veen- reached at 360-565-3131 or The cost is $10 per person for the ride and a $5 fee to get entrance station about five ema said. via the Internet at http:// He did not have the exact tinyurl.com/hurridge. into the park, said park miles south of Port Angeles. The details of the Dec. 17 amount on hand Sunday. spokeswoman Barb Maynes. __________ People arriving from VicAn Olympic National grand opening have not yet toria via ferry also frequently Park annual pass or related been set. Reporter Paige Dickerson can be Because chains are are in search of a ride, Veen- reached at 360-417-3535 or at paige. federal passes will cover the required to ascend the Ridge, ema said of Nelson’s shuttle dickerson@peninsuladailynews. $5 fee, she said. com. The park will keep the many motorists don’t want to service.
Walmart stores. Usually, a member of the American Legion or a Marine Reserve is on hand. “Sometimes Santa Claus is there,” Abbott said. Toys for Tots has live drops at the Port Angeles Walmart Supercenter, 3471 E. Kolonels Way, the next three Saturdays from 10 a.m. to 5 p.m. The Sequim Walmart, 1110 W. Washington St., will have live drops on the next three Fridays and Saturdays from 9 a.m. to 5 p.m. Cash or check donations are also accepted. Toys for Tots uses the money to buy gifts. “All money and all toys collected in Clallam County stay in Clallam County,” Abbott said. “It goes nowhere else.” At least two toys are distributed to every child who qualifies for Toys for Tots. “It started in 1947 in California by a [Marine] captain and it has mushroomed up to a full foundation,” Abbott said. Kids qualify for Toys for Tots through foster parents and a variety of organizations, including the Salvation Army, West End Outreach and Mount Pleasant Grange. “We work with a lot of organizations,” Abbott said.
Shelter: Man volunteers to stay connected every year. “I don’t know what I’d do without this place,” he said. Single women are accepted at the Winter Shelter on a temporary basis because there’s only a small separate room in the Legion’s brightly lighted downstairs room to house them, said Skip Cadorette, chairman of Community Outreach Action Shelter Team, the six-year-old crew of individuals, churches and service organizations whose sole mission is the Winter Shelter for people who are homeless. “COAST is really responsible for galvanizing this community,” said Walker.
Continued from A1 And some have turned their lives around, getting sober while without permanent shelter. That’s what Michael Rosser, 46, plans to do. He quit drinking a year ago and goes to regular AA meetings. He’s in Port Townsend to be near his 9-year-old daughter, who moved here from California, and has been living in his van for two years. “I do a lot of volunteer work up here because it helps me stay connected and stay sober,” said Rosser, who hopes to start up a little day-labor business with friends.
‘It’s hard’ Gawne and two of his running buddies, Don Pruitt and Erik Huwyler, spend their days looking for work, walking around or hiding out at their camp, the tents they use during the warmer seasons when there is no
The big three There is other local shelJulie McCormick/for Peninsula Daily News ter for people with children, and the shelter team can Volunteers Diane Bommer, left, and Willy Stark get things going in the usually find better shelter kitchen for an evening meal at the Winter Shelter in Port Townsend. for single women, Cadorette said. shelter for single adults in who is plagued with physi- without a permanent home It’s a team effort for the for nearly a decade and has big three, COAST, OlyCAP cal problems. Jefferson County. Huwyler said he’s been come to the shelter and the Legion, said Cador“It’s hard,” said Pruitt,
Continued from A1 which has also provided service to the city for five District voters readily years, to assess the legally agreed to raise their own allowed maximum of $1. But city voters were pretaxes to allow the district,
Gourmet
Pizza & Mexican
EBT accepted for all U-Bake Menu items
$1 & We Bake It! Stop by or call for more info!
DOCUMENT PREPARATION DISSOLUTION SSA, DSHS Get Yourself a “Pair
‘o’ Legal Feet”
FREE
30 MINUTE CONSULTATION
360.808.6350 CALL NOW
095094107
417-5600
Needs volunteers COAST organizes the 450 volunteers who will help the shelter stay in business, but there’s one week still open, Cadorette said. “We can find ways to put folks into the process,” he said. “If we got an organization that wants to step in, that would be golden.”
________ Julie McCormick is a freelance writer and photographer living in Port Townsend. Contact her at 360385-4645 or juliemccormick10@ gmail.com. To volunteer at the Winter Shelter, phone Skip Cadorette at 360385-5669.
Deal: City voters balked at increase
Van Goes
Mon-Sat: 10:30am - 8:00pm Sunday 10:30am - 6:00pm 814 South C Street ◆ PA
ette, whose day job is pastor at Port Townsend Baptist Church. When they started, the shelter rotated from church to church, he said. A permanent location was a godsend. “None of us could do this alone,” he said.
3430 East Hwy 101, Ste 26 PA By Appointment cindy@p2sweb.com EIN#20-8318779
Supply limited 360-797-1123 Located at The Pennyman Coin Shop 205 S. Sunnyside Ave., Sequim
095096522
085090727
peninsuladailynews.com
FREE vial of true anointing oil with copy of this ad.
Responsible Stewardship Continues Beyond Our Lifetimes Funeral Home & Crematory
(360)385-2642
1615 Parkside Dr. Port Townsend
We are dedicated to reducing our carbon footprint by
new governance structure to replace the less permanent arrangement that has existed for the last five years, when the city ceased operation of a separate fire department and began contracting with the district. “What we did was trade roles and responsibilities,” Timmons said. Consolidations are happening nationwide and in nearby Clallam and Kitsap counties as officials recognize the efficiencies to be achieved, said Gordon Proposed agreement Pomeroy, chief of the disA new amendment to its trict. interlocal agreement with “It’s sort of a giant poolthe fire district commits the ing of resources,” he said. city to deed its fire station to the district — the dis- Annexation? trict’s $60,000 annual lease of the building would end Once the amendment to — and also pay both princi- the interlocal agreement is pal and interest on an completed, officials next anticipated $3.8 million dis- will begin looking at trict bond for capital proj- whether or not there should ects. be an annexation of the city The three fire commis- into the fire district or cresioners Tuesday held what ation of a regional fire was likely their final meet- authority. ing with City Manager Depending on how David Timmons before the they’re designed, each offers agreement goes before the different levels of authority City Council on Monday, for city officials at a level Dec. 6, and there were few they do not have under the problems. existing interlocal agreeThe agreement is an ment. interim measure, however. Officials would like to City and district officials put such a merger on the also are working toward a ballot next year, but it could
sented with a less straightforward question. The city asked for an additional $1.43 cents for fire and another 57 cents for the city’s general fund for unspecified purposes. City voters balked, and suddenly the city owed more money toward the joint operation than it could pay. “It was just too complicated a measure,” said City Manager David Timmons.
T
he city asked for an additional $1, 43 cents for fire and another 57 cents for the city’s general fund for unspecified purposes. take longer to work out, said Staph, especially since voters are likely to be facing multiple ballot measures on other topics in 2011.
________ Julie McCormick is a freelance writer and photographer living in Port Townsend. Contact her at 360385-4645 or juliemccormick10@ gmail.com.
Death Notices Catherine Ann (Hutton) Gockerell Feb. 6, 1950 — Nov. 16, 2010
Catherine Ann Gockerell died in Port Angeles died of natural causes. She was 60. Services: Saturday, Dec. 4, 5 p.m., memorial at Unity in the Olympics, 2917 E. Myrtle St., Port Angeles, with John Wingfield officiating. Linde Family Funeral Service, Sequim, is in charge of arrangements.
Peninsula Daily News for Monday, November 29, 2010
Commentary
Page
A7
Ready to make some tough choices? On Nov. 19, Rasmussen Reports published results from a national telephone poll. It showed Thomas that 47 percent Friedmancreation engines and the latest international education test results that show our peers outeducatingbuilding. If we fail to come together and invest, spend and cut really wisely,
we’re heading for a fall — and if America becomes weak, your kids won’t just grow up in a different country, they will grow up in a different world. We have to manage America’s foreign policy, and plan its rebuilding at home, at a time when our financial resources and our geopolitical power are more limited than ever while our commitments abroad and entitlement promises at home are more extensive than ever. That is why. That hybrid politics will require hard choices. n We need to raise gasoline and carbon taxes to discourage their use and drive the creation of a new clean energy industry, while we
Peninsula Voices Global warming A Sequim man wrote a pithy letter to the editor [“That warm feeling,” Nov. 24 PDN] to debunk global warming because, he said, “I just scooped 12 inches of global warming off of my sidewalks.” He’s right, I suppose. That 12 inches probably was “global warming,” because the records show that the alternation of La Nina (cooling) and El Nino (warming) currents in the Pacific has become more rapid and intense in recent years. In other words, global warming encompasses the present La Nina, even if this seems counter-intuitive. Rob Young, a scientist from Western Carolina University, related a personal story recently during one of his visits to the North Olympic Peninsula. His father-in-law, a global warming doubter, showed him a map he had kept in which he charted
all of his fishing holes on the Neuse River over time. Young quickly noticed that the dates showed the locations of his favorite fishing holes steadily moved up river from year to year. He told his father-in-law: “Dad, right here you have an excellent data set demonstrating global warming.” As sea water warms, it increases in volume and intrudes farther up river. I’m just saying, if the trend continues, it will become impossible to debunk global warming. The separate but important question is: What can we do? The question one five-hundred-thirtydemands consideration. John Merton Marrs, eighth of the total voters. In 2008, that number Lake Sutherland was 244,011.3513. There were 31 states Electoral College with 196 electoral votes. Each presidential elecThus, they should have tion has 538 electoral votes. 196 times 244,011.3513 Thus, each Electoral voters. But they don’t. What they had was College vote must carry
cut payroll and corporate taxes to encourage employment and domestic investment. n We need to cut Medicare and Social Security entitlements at the same time as we make new investments in infrastructure, schools and government-financed research programs that will spawn the next Google and Intel. n We need to finish our work in Iraq, which still has the potential to be a long-term gamechanger in the Arab-Muslim world, but we need to get out of Afghanistan — even if it entails risks — because we can’t afford to spend $190 million a day to bring its corrupt warlords from the 15th to the 19th century.. After all, he owns the biggest bully pulpit in the world. It’s because the 40 percent of
Our readers’ letters, faxes
199,496 votes per electoral vote, a difference of 44,515, making them cheap votes. The other 20 states had 342 electoral votes. Their votes are worth 269,523 regular votes each, a difference of 25,512 each more than 244,011 Those votes were expensive.. Thomas L. Friedman is a three-time Pulitzer Prize-winning columnist for The New York Times. His column appears in the Peninsula Daily News on Mondays. E-mail Friedman via http:// nyti.ms/3eBGV.
and e-mail
The 20 states lost a total of 8,969,283 not-countable voters. Where did they go? Can you guess? They are hidden in the 196 electoral votes of the 31 states with too many electoral votes. Their short votes are exactly the same as the 8,969,283 lost votes
in the 20 states. Washington was one of the 20 states. We lost 352,753 votes, while Idaho, with four electoral votes, had a shortage of 320,744 votes, which means that most of our lost votes are hiding in Idaho electoral votes. What is most shocking is that Florida lost 1,802,437 votes, the equivalent of seven electoral votes. In all, about 37 electoral votes are hiding in the exchanged votes. That’s enough to make three more Washington states (33) plus another Idaho with four votes. This is what the Electoral College gives us. Periodically, I shall be offering discussions on the topic under Electoral Reform Group in Clallam County. My information above is derived from. Clint Jones, Sequim
Rich aren’t bad guys but should pay more MOST AMERICANS DISLIKE class-warfare talk aimed at rich people. It does not follow that Froma they don’t want Harrop the wealthiest among us to pay more taxes. Polls show they do. That puts Democrats in the mainstream on such matters. But Democrats still need a sophisticated way to discuss this, one that does not rely on simpleminded culturedriven causes of poverty is intellectually dishonest and alienates middle-class voters coping with
Interim (). “The phrase casts income as something that is consumed, not as something that is produced.”fund ■ Jennifer Jackson, Port Townsend Neighbor columnist, 360-379-5688; jjackson@olypen. Froma Harrop is a columnist for the Providence (R.I.) Journal. Her column appears here every Monday. Contact her at info@creators. com or at 40 Creators Syndicate Inc., 5777 W. Century Blvd., Suite 700, Los Angeles, Calif.
Peninsula Daily News
Monday, November 29, 2010
Better Hearing WitH a Human toucH
50%
OFF
S-Series Digital Hearing Aids Good Thru 12-31-10
In-store specIals on In-stock Instruments
E-Series Digital Hearing Aids
(M.S.R.P.)
Starting at Good Thru 12-31-10
799
$
00
0% FInancIng avaIlable
M ountain View HEARING AID CENTERS, INC. (360) 681-4481 • 1-800-467-0292
0B5104285
Monday through Thursday, 9am - 4pm 625 5th Ave. N #3, Sequim, WA
Call for an Appointment Today
Peninsula Daily News for Monday, November 29, 2010
Sports
S E CT I O N
B
SCOREBOARD Page B2
BCS
The Associated Press
Stanford quarterback Andrew Luck celebrates after defeating Oregon State 38-0 in Stanford, Calif., on Saturday.
Stanford big poll winner By Ralph D. Russo The Associated Press
NEW.
Biggest jump of. Turn
to
BCS/B3
The Associated Press (2)
Kansas City’s Dwayne Bowe breaks a tackle from Seattle cornerback Kelly Jennings to drive in for a touchdown in the second half Sunday in Seattle. It was one of Bowe’s three touchdowns in the game.
Chiefs stomp Hawks Carroll: ‘We played like garbage out there’ By Tim Booth
The Associated win over the Seattle Seahawks on Sunday. The Chiefs completely dominated the Seahawks both offensively and defensively. “We played like garbage out there,” Carroll said. “That’s what it is.”wise that is the worst anyone could play on defense, 200 yards on the ground alone, that’s just the worst game ever,” Seattle linebacker Aaron Curry said.
Seattle (5-6) still has the benefit of playing in the mediocre NFC West, Next Game but even that margin of Sunday error is clos- vs. Panthers ing. at Qwest Field S e a t t l e Time: 1 p.m. dropped its On TV: Ch. 13 fourth in the past five games after a 4-2 start to fall into a tie with St. Louis, and was booed in the closing moments for a second straight home game.
Two interceptions. Turn
to
Hawks/B3
Seattle tight end Chris Baker spikes the ball after scoring a touchdown against Kansas City.
Federer beats Nadal in ATP final No. 2 men’s player captures fifth season-ending title 6-3, 3-6, 6-1 The Associated Press
LONDON — Roger Federer turned his high-profile, seasonendingranked Swiss player. In Grand Slam finals, Nadal is 5-2 against Federer, but Federer has now beaten Nadal all three times they have faced each other in the final tournament of the season. In the first set Sunday at the The Associated Press O2 Arena, Federer lost only three Switzerland’s Roger Federer returns the ball to points on his serve, and broke Spain’s Rafael Nadal during the singles final tennis Nadal once. match at the ATP World Tour Finals at the O2 Arena in Turn
to
Tennis/B3
London on Sunday.
B2
SportsRecreation
Monday, November 29, 2010
Today’s
Peninsula Daily News
Latest sports headlines can be found at www. peninsuladailynews.com.
Scoreboard Calendar
Today
Go to “Nation/World” and click on “AP Sports”
7 a.m. (47) GOLF EPGA, Dubai World Championship, Final Round, Site: Jumeirah Golf Estates - Dubai, UAE Noon (25) FSNW Volleyball NCAA, Pac-10 Wild Card 4 p.m. (27) ESPN2 Basketball NCAA, Virginia vs. Minnesota, ACC/ Big Ten Challenge - Minneapolis (Live) 5:30 p.m. (26) ESPN Football NFL, San Francisco 49ers vs. Arizona Cardinals, Site: University of Phoenix Stadium - Glendale, Ariz. (Live) 7 p.m. (25) FSNW Football NCAA, Missouri vs. Kansas (encore), Site: Arrowhead Stadium - Kansas City, Mo. 12:30 a.m. (27) ESPN2 Football NCAA, North Carolina State vs. Maryland (encore), Site: Byrd Stadium - College Park, Md.
SPORTS SHOT
Today
SPORTS ON TV
Boys Basketball: Jamboree at Port Angeles main gym, 5:30 p.m. Girls Basketball: Port Angeles at South Kitsap, 7 p.m.
Tuesday Boys Basketball: Klahowya at Chimacum, 7 p.m. Girls Basketball: Chimacum at Klahowya, 7 p.m. Girls Bowling: Sequim at Olympic, 2:45 p.m.
Wednesday Boys Basketball: W.F. West at Port Angeles, 7 p.m.; Sequim at Bainbridge, 7 p.m.; Crosspoint at Quilcene, 7 p.m. Girls Basketball: North Kitsap at Chimacum, 7 p.m.; ; Crosspoint at Quilcene, 5:30 p.m.
Football NFL Schedule All Times PST Thursday’s Games New England 45, Detroit 24 New Orleans 30, Dallas 27 N.Y. Jets 26, Cincinnati 10
game between the teams. ECHL KALAMAZOO WINGS_Announced G Riley Gill was loaned to Worcester (AHL). VICTORIA SALMON KINGS_Announced D Yann Sauve was reassigned to the team by Manitoba (AHL). at Indianapolis, late
The Associated Press
Grey Cup
Today’s Game San Francisco at Arizona, 5:30 p.m. Thursday Houston at Philadelphia, 5:20 p.m. Sunday, Dec. 5 San Francisco at Green Bay, 10 a.m. Denver at Kansas City, 10 a.m. Buffalo at Minnesota, 10 a.m. Jacksonville at Tennessee, 10 a.m. Cleveland at Miami, 10 a.m. Chicago at Detroit, 10 a.m. Washington at N.Y. Giants, 10 a.m. New Orleans at Cincinnati, 10 a.m. Oakland at San Diego, 1:05 p.m. Carolina at Seattle, 1:15 p.m. St. Louis at Arizona, 1:15 p.m. Atlanta at Tampa Bay, 1:15 p.m. Dallas at Indianapolis, 1:15 p.m. Pittsburgh at Baltimore, 5:20 p.m. Monday, Dec. 6 N.Y. Jets at New England, 5:30 p.m.
Chiefs 42, Seahawks 24 Kansas City Seattle
7 14 0 21 — 42 7 3 7 7 — 24 First Quarter KC—Bowe 7 pass from Cassel (Succop kick), 11:31. Sea—Thomas 10 blocked punt return (Mare kick), :31. Second Quarter KC—Smith 1 run (Succop kick), 7:18. KC—Bowe 36 pass from Cassel (Succop kick), 1:12. Sea—FG Mare 43, :00. Third Quarter Sea—Baker 13 pass from Hasselbeck (Mare kick), 14:03. Fourth Quarter KC—Charles 3 run (Succop kick), 14:54. KC—Bowe 9 pass from Cassel (Succop kick), 12:43. Sea—Obomanu 87 pass from Hasselbeck (Mare kick), 10:16. KC—Moeaki 6 pass from Cassel (Succop kick), 3:36. A—66,370. First downs Total Net Yards Rushes-yards Passing Punt Returns Kickoff Returns Interceptions Ret. Comp-Att-Int Sacked-Yards Lost Punts Fumbles-Lost Penalties-Yards Time of Possession
KC 28 503 48-270 233 2-17 2-32 2-26 22-32-0 0-0 5-36.4 1-1 5-50 41:03
Sea 13 288 12-20 268 1-(-2) 7-115 0-0 20-37-2 2-14 4-40.3 2-1 3-26 18:57
INDIVIDUAL STATISTICS RUSHING—Kansas City, Charles 22-173, Jones 20-68, Cassel 5-28, Smith 1-1. Seattle, Lynch 7-20, Forsett 3-2, Hasselbeck 2-(minus 2). PASSING—Kansas City, Cassel 22-32-0-233. Seattle, Hasselbeck 20-37-2-282. RECEIVING—Kansas City, Bowe 13-170, Jones 3-14, Charles 2-3, Tucker 1-24, Cox 1-10, Copper 1-6, Moeaki 1-6. Seattle, Obomanu 5-159, Stokley 5-51, Tate 2-21, Lynch 2-13, Butler 2-9, Baker 1-13, Forsett 1-8, Washington 1-5, Carlson 1-3. MISSED FIELD GOALS—Kansas City, Succop 43 (BK).
Hockey NHL Standings All Times PST EASTERN CONFERENCE Atlantic Division GP W L OT Pts GF GA Philadelphia 25 15 6 4 34 87 61 Pittsburgh 25 15 8 2 32 76 61 N.Y. Rangers 25 14 10 1 29 73 66 New Jersey 24 8 14 2 18 45 69 N.Y. Islanders 22 5 12 5 15 46 72 Northeast Division GP W L OT Pts GF GA Montreal 24 15 8 1 31 60 47 Boston 22 12 8 2 26 59 46 Ottawa 24 11 12 1 23 57 71 Buffalo 25 9 13 3 21 62 73 Toronto 22 8 11 3 19 48 61
Montreal Alouettes slotback Jamel Richardson, left, runs for yardage against Saskatchewan Roughriders cornerback Omarr Morgan during the first quarter of the Canadian Football League’s 98th Grey Cup on Sunday in Edmonton, Alberta. Montreal captured the Grey Cup with a 21-18 victory.
National Football Conference St. Louis Seattle San Francisco Arizona
W 5 5 3 3
L 6 6 7 7
T PCT 0 .455 0 .455 0 .300 0 .300
HOME 4-2-0 3-2-0 3-3-0 2-2-0
Philadelphia NY Giants Washington Dallas
W 7 7 5 3
L 4 4 6 8
T PCT 0 .636 0 .636 0 .455 0 .273
HOME 3-2-0 4-2-0 2-4-0 1-5-0
Chicago Green Bay Minnesota Detroit
W 8 7 4 2
L 3 4 7 9
T PCT 0 .727 0 .636 0 .364 0 .182
HOME 4-2-0 4-1-0 3-2-0 2-3-0
Atlanta New Orleans Tampa Bay Carolina
W L 9 2 8 3 7 4 1 10
T PCT 0 .818 0 .727 0 .636 0 .091
HOME 6-0-0 4-2-0 3-2-0 1-5-0
CONF 3-5-0 4-3-0 1-6-0 2-5-0
PF 213 209 160 188
PA 231 275 219 292
DIFF -18 -66 -59 -104
STRK Won 1 Lost 2 Lost 1 Lost 5
CONF 5-3-0 5-2-0 4-4-0 2-6-0
PF 310 277 215 256
PA 257 240 262 301
DIFF +53 +37 -47 -45
STRK Lost 1 Won 1 Lost 1 Lost 1
CONF 6-3-0 5-3-0 4-4-0 2-6-0
PF 222 269 189 258
PA 172 166 239 282
DIFF +50 +103 -50 -24
STRK Won 4 Lost 1 Won 1 Lost 4
CONF 6-1-0 7-2-0 5-2-0 1-7-0
PF 276 265 219 140
PA 209 197 223 276
DIFF +67 +68 -4 -136
STRK Won 5 Won 4 Lost 1 Lost 5
CONF 4-4-0 4-3-0 3-4-0 2-6-0
PF 285 274 255 250
PA 231 211 256 323
DIFF +54 +63 -1 -73
STRK Won 2 Won 3 Lost 2 Lost 2
CONF 7-1-0 7-2-0 4-4-0 1-7-0
PF 264 334 205 229
PA 187 266 225 295
DIFF +77 +68 -20 -66
STRK Won 4 Won 3 Won 1 Lost 1
CONF 6-2-0 6-2-0 2-5-0 1-7-0
PF 250 254 216 225
PA 188 181 229 288
DIFF +62 +73 -13 -63
STRK Won 2 Won 2 Won 1 Lost 8
CONF 4-3-0 5-3-0 4-4-0 2-5-0
PF 268 240 264 257
PA 216 294 287 218
DIFF +52 -54 -23 +39
STRK Lost 1 Lost 1 Won 1 Lost 4
American Football Conference Kansas City San Diego Oakland Denver
W 7 5 5 3
L 4 5 6 8
T PCT 0 .636 0 .500 0 .455 0 .273
HOME 5-0-0 4-1-0 4-2-0 2-4-0
NY Jets New England Miami Buffalo
W 9 9 6 2
L 2 2 5 9
T PCT 0 .818 0 .818 0 .545 0 .182
HOME 4-2-0 5-0-0 1-4-0 1-5-0
Baltimore Pittsburgh Cleveland Cincinnati
W 8 8 4 2
L 3 3 7 9
T PCT 0 .727 0 .727 0 .364 0 .182
HOME 5-0-0 3-2-0 3-3-0 1-4-0
Indianapolis Jacksonville Houston Tennessee
W 6 6 5 5
L 4 5 6 6
T PCT 0 .600 0 .545 0 .455 0 .455
HOME 4-0-0 4-2-0 3-3-0 2-3-0
Southeast Division GP W L OT Pts GF GA Washington 25 17 6 2 36 86 68 Tampa Bay 24 13 8 3 29 73 78 Atlanta 24 12 9 3 27 77 72 Carolina 23 10 10 3 23 70 74 Florida 22 10 12 0 20 57 57 WESTERN CONFERENCE Central Division GP W L OT Pts GF GA Detroit 21 15 4 2 32 73 56 Columbus 22 14 8 0 28 62 53 Chicago 26 13 11 2 28 79 74 St. Louis 22 12 7 3 27 57 57 Nashville 22 9 8 5 23 51 60 Northwest Division GP W L OT Pts GF GA Vancouver 22 12 7 3 27 68 59 Colorado 23 13 9 1 27 83 71 Minnesota 22 11 9 2 24 56 62 Calgary 23 9 12 2 20 64 69 Edmonton 22 6 12 4 16 55 88 Pacific Division GP W L OT Pts GF GA Dallas 22 13 8 1 27 64 61 Phoenix 22 11 6 5 27 66 65 Los Angeles 22 13 9 0 26 63 55 San Jose 22 11 7 4 26 65 63 Anaheim 25 11 11 3 25 64 77 NOTE: Two points for a win, one point for overtime loss. Saturday’s Games New Jersey 2, Philadelphia 1, SO Florida 4, Tampa Bay 3, SO N.Y. Rangers 2, Nashville 1, SO Pittsburgh 4, Calgary 1 Montreal 3, Buffalo 1 Ottawa 3, Toronto 0 Dallas 2, St. Louis 1 Anaheim 6, Phoenix 4
AFC WEST ROAD DIV 2-4-0 1-2-0 1-4-0 1-2-0 1-4-0 3-0-0 1-4-0 1-2-0 AFC EAST ROAD DIV 5-0-0 3-0-0 4-2-0 2-1-0 5-1-0 1-2-0 1-4-0 0-3-0 AFC NORTH ROAD DIV 3-3-0 2-1-0 5-1-0 2-1-0 1-4-0 1-2-0 1-5-0 1-2-0 AFC SOUTH ROAD DIV 2-4-0 1-2-0 2-3-0 2-1-0 2-3-0 2-2-0 3-3-0 1-1-0
Colorado 7, Minnesota 4 San Jose 4, Edmonton 3 Chicago 2, Los Angeles 1 Sunday’s Games Washington 3, Carolina 2, SO Atlanta 4, Boston 1 Detroit 4, Columbus 2 Today’s Games Pittsburgh at N.Y. Rangers, 4 p.m. Dallas at Carolina, 4:30 p.m. Edmonton at Ottawa, 4:30 p.m. Minnesota at Calgary, 6 p.m. Los Angeles at Anaheim, 7 p.m. Tuesday’s Games Tampa Bay at Toronto, 4 p.m. Phoenix at Nashville, 5 p.m. St. Louis at Chicago, 5 p.m. Atlanta at Colorado, 7 p.m. Detroit at San Jose, 7:30 p.m.
Transactions BASEBALL Major League Baseball MLB_Announced Chiba Lotte (Japan Pacific League) has accepted the highest bid, submitted by the Minnesota Twins, for the negotiating rights to INF Tsuyoshi Nishioka. American League DETROIT TIGERS_Agreed to terms with C-DH Victor Martinez on a four-year contract. National League LOS ANGELES DODGERS_Agreed to terms with RHP Jon Garland on a one-year contract.
COLLEGE NEW MEXICO_Suspended senior WR Bryant Williams, sophomore LB Joe Harris and junior LB Julion Conley one game apiece, after being arrested on battery, aggravated battery and public affray charges.
NFL STANDINGS NFC WEST ROAD DIV 1-4-0 1-2-0 2-4-0 3-1-0 0-4-0 1-1-0 1-5-0 1-2-0 NFC EAST ROAD DIV 4-2-0 2-1-0 3-2-0 1-2-0 3-2-0 2-1-0 2-3-0 1-2-0 NFC NORTH ROAD DIV 4-1-0 3-0-0 3-3-0 3-1-0 1-5-0 1-3-0 0-6-0 0-3-0 NFC SOUTH ROAD DIV 3-2-0 2-0-0 4-1-0 3-1-0 4-2-0 2-2-0 0-5-0 0-4-0
Central Hockey League MISSOURI MAVERICKS_Signed F Bill Vandermeer. Traded F Tab Lardner traded to Fort Wayne for future considerations. RIO GRANDE VALLEY KILLER BEES_Signed F Nick Sucharski. WICHITA THUNDER_Placed F Chris Moran on waivers.
BASKETBALL National Basketball Association CHICAGO BULLS_Signed G John Lucas III. MIAMI HEAT_Assigned F Dexter Pittman to Sioux Falls (NBADL).
FOOTBALL National Football League NFL_Fined New York Giants RB Brandon Jacobs $20,000 for unsportsmanlike conduct toward fans before last week’s game at Philadelphia. Fined Oakland DT Tommy Kelly $20,000 for unnecessarily striking a Pittsburgh player in the head area. MIAMI DOLPHINS_Signed DL Chris Baker. Waived DL Clifton Geathers. SEATTLE SEAHAWKS_Placed TE Anthony McCoy on injured reserve. Claimed DE Clifton Geathers off waivers from Miami.
HOCKEY National Hockey League CHICAGO BLACKHAWKS_Signed D Garnet Exelby and assigned him to Rockford (AHL). DALLAS STARS_Placed D Mark Fistric on the injured reserve list, retroactive to Nov. 22. MINNESOTA WILD_Assigned F Matt Kassian to Houston (AHL). PHOENIX COYOTES_Assigned RW Petr Prucha to San Antonio (AHL). VANCOUVER CANUCKS_Assigned D Ryan Parent to Manitoba (AHL). American Hockey League AHL_Suspended Hamilton F Ian Schultz two games and Adirondack F Zac Rinaldo one game as a result of their actions in a Nov. 24
UNC GREENSBORO_Announced the resignation of sports information director Mike Hirschman, effective Nov. 30.
Basketball NBA Standings All Times PST EASTERN CONFERENCE Atlantic Division W L Pct GB Boston 12 4 .750 — New York 9 9 .500 4 New Jersey 6 11 .353 6 1/2 Toronto 6 11 .353 6 1/2 Philadelphia 4 13 .235 8 1/2 Southeast Division W L Pct GB Orlando 12 4 .750 — Atlanta 11 7 .611 2 Miami 9 8 .529 3 1/2 Charlotte 6 11 .353 6 1/2 Washington 5 10 .333 6 1/2 Central Division W L Pct GB Chicago 9 6 .600 — Indiana 7 7 .500 1 1/2 Cleveland 7 9 .438 2 1/2 Milwaukee 6 10 .375 3 1/2 Detroit 6 11 .353 4 WESTERN CONFERENCE Southwest Division W L Pct GB San Antonio 14 2 .875 — Dallas 12 4 .750 2 New Orleans 12 4 .750 2 Memphis 7 10 .412 7 1/2 Houston 5 11 .313 9 Northwest Division W L Pct GB Utah 13 5 .722 — Oklahoma City 11 6 .647 1 1/2 Denver 9 6 .600 2 1/2 Portland 8 8 .500 4 Minnesota 4 13 .235 8 1/2 Pacific Division W L Pct GB L.A. Lakers 13 3 .813 — Phoenix 8 8 .500 5 Golden State 8 9 .471 5 1/2 Sacramento 4 11 .267 8 1/2 L.A. Clippers 3 15 .167 11 Saturday’s Games Atlanta 99, New York 90 Orlando 100, Washington 99 Cleveland 92, Memphis 86 Philadelphia 102, New Jersey 86 Golden State 104, Minnesota 94 Dallas 106, Miami 95 Milwaukee 104, Charlotte 101 Chicago 96, Sacramento 85 Sunday’s Games Atlanta 96, Toronto 78 New York 125, Detroit 116,2OT San Antonio 109, New Orleans 95 Utah 109, L.A. Clippers 97 Houston 99, Oklahoma City 98 New Jersey 98, Portland 96 Phoenix at Denver, late Indiana at L.A. Lakers, late Today’s Games Washington at Miami, 4:30 p.m. New Orleans at Oklahoma City, 5 p.m. Houston at Dallas, 5:30 p.m. Milwaukee at Utah, 6 p.m. Tuesday’s Games Boston at Cleveland, 4 p.m. Detroit at Orlando, 4 p.m. Portland at Philadelphia, 4 p.m. New Jersey at New York, 4:30 p.m. L.A. Lakers at Memphis, 5 p.m. Indiana at Sacramento, 7 p.m. San Antonio at Golden State, 7:30 p.m.
SportsRecreation
Peninsula Daily News
Monday, November 29, 2010
B3
Hawks: Kansas City passes, runs past Seattle Continued from B1 out and played today.” If Cassel’s passing wasn’t Their only touchdown in enough of a problem for the first half came when Seattle’s defense, there was Kennard Cox went the Chiefs’ running game untouched to block Dustin that backed up their rankColquitt’s punt and rookie ing as the best in the NFL. Charles’ effort was part Earl Thomas returned it 10 of the 270 yards rushing yards for a touchdown. Seattle did cut the Chiefs from Kansas City that lead to 21-17 after Hassel- included 68 from Thomas beck hit Chris Baker for a Jones and a scrambling 28 touchdown on the first drive yards from Cassel, more than Seattle’s total of 20 of the second half. But that was as close as yards rushing as a team. Backup defensive tackle Seattle got. Hasselbeck added an Shaun Smith added a 87-yard touchdown pass to 1-yard touchdown plunge in Obomanu early in the the second quarter and Kansas City won its second fourth quarter. Cassel finished 22-of-33 straight overall and ninth for 233 yards, finding Bowe consecutive game against 13 times to match his NFC West opponents. More importantly, the career-best set just two weeks ago against Denver. Chiefs (7-4) remained on Bowe had 170 yards top of the division. receiving and caught touch“We just know we have a downs of 7, 36 and 9 yards. good offense and we just Jamaal Charles ran for need to keep it up,” Charles 173 yards on 22 carries, top- said. ping 1,000 yards for the “It comes from practice. season, and added a 3-yard If you don’t work hard in TD run on the first play of practice, don’t show up on the fourth quarter that gave Sundays.” the Chiefs a 28-17 lead. Cassel was the kid CarBowe extended his roll didn’t pick to be the streak of at least one TD starter at USC when Carcatch to seven straight son Palmer left. games. Carroll instead went Cassel’s 129.3 passer with Matt Leinart, who was rating on Sunday was the part of the most dominant third best of his pro career. run in college football in Not too shabby for some- recent history. one who was Carroll’s Cassel was the backup backup at USC. that barely saw mop-up “I knew that this was a duty. big game for the Kansas Leinart is now the third City Chiefs and this by no string QB in Houston and means was about coach Cassel is quickly growing Carroll and myself,” Cassel into a star. said. So too is Bowe, who has “I played for him six 32 receptions for 465 yards years ago, I’ve had some and seven touchdowns the time to move on from there. past three games. At this point, I’m just really “I don’t keep count until proud of how our team came Monday. I don’t want to
The Associated Press
Kansas City Chiefs’ Shaun Smith pressures Seattle quarterback Matt Hasselbeck in the second half Sunday in Seattle. know my stats until Monday,” Bowe said. When told what they were, Bowe said, “Not yet, I’ve still got more to go.” Cassel completed 15-of20 in the first half, picking apart Seattle’s pass defense, connecting with Bowe in the first quarter, then on a
Chargers rip Indianapolis The Associated Press
IND48 (6-5) finished with only 24 yards rushing. The Colts..
36-yard TD in the second when Seattle’s.
Trufant leaves game with injury The Associated Press
SEATTLE — Seattle Seahawks cornerback Marcus Trufant left Sunday’s game against Kansas City with a leg injury suffered in the first quarter, but returned late in the second quarter. Trufant was hurt on a 2-yard run by Thomas Jones
late in the first quarter. He initially rolled around holding his left leg and was tended to by trainers before a cart was brought on the field to take him to the locker room. The Seahawks did not announce which leg or the specifics of Trufant’s injury,
but initially said he was out for the game. With 3:50 left in the half and after going through tests on the sideline, Trufant returned to the game. Trufant started on Sunday despite suffering a concussion last week against New Orleans.
Tennis: Federer wins Continued from B1 reeled off the next four points — the last when He then lost five points Nadal sent a forehand wide on serve in both the second — to earn the break and and third sets, but four of essentially end Nadal’s them came in one game, chances of winning. On match point, Federer giving Nadal his only break hit a forehand winner on of the match. “I don’t want to say I the line, but the crowd gave it to him, but obviously apparently thought the ball Rafa is good enough off sec- was out as they sat quietly ond serves he’s going to win in the arena. Then Nadal started comat least 50 percent off them usually, unless you’re on a ing to the net to shake roll and he doesn’t kind of hands with Federer, who figure out your second raised his arms in victory to set off a standing ovation. serve,” Federer said. Federer has won a record “But at that point, he was into the match. He 16 Grand Slam titles, the knew the importance of it. last coming at this year’s He was able to find a way to Australian Open, and he and Nadal have combined break me in that game.” The decisive shift came to win 21 of the past 23 early in the third set on majors. “Everybody saw the Nadal’s serve with the match of yesterday, so Spaniard trailing 2-1. He took a 40-15 lead everybody’s free to think his when Federer sent a return own opinion,” Nadal said. long, but Federer then .”
BCS: Fiesta Bowl bids Continued from B1 Atlantic Coast Conference championship, with the The Sooners beat Okla- winner getting an Orange homa State 47-41 on SatBowl bid. urday night to make the Connecticut is in comjump up the standings. mand of the Big East race. The Sooners will play The Huskies will clinch Nebraska in the conference the league and a BCS bid championship game and by winning at South Florida on Saturday. the winner lands a Fiesta If UConn loses, West Bowl bid. Virginia could win the Virginia Tech and Florleague and the BCS bid by ida State will play in.
Chris Tucker/Peninsula Daily News
Flying
high
Caden Crozier, 11, of Port Angeles, gets ready to take a tumble after trying to jump his snowboard on Hurricane Ridge on Sunday. Dozens of skiers, snowboarders and snowshoers were out on the ridge that day. The snow was several feet deep.
B4
SportsRecreation
Monday, November 29, 2010
Peninsula Daily News
Texans shut out Titans 20-0 The Associated Press
HOUSTON — Andre Johnson finally had enough from Cortland Finnegan, sparking a fistfight that led to both players being ejected and could end up in further discipline from the NFL. The Texans snapped a four-game losing streak while Johnson and Finnegan were ejected for their fight in the fourth quarter of a 20-0 Houston win over Tennessee on Sunday. Arian Foster rushed for 143 yards and caught nine passes for the Texans (5-6), who posted their first shutout since 2004.. The incident came at the end of a tumultuous week for the Titans (5-6), who’ve lost four in a row. Houston cornerback Glover Quin set a franchise record with three interceptions off Titans rookie quarterback Rusty Smith, who struggled in his first career start in replacing the injured Vince Young. Titans offensive coordinator Mike Heimerdinger was on the sideline calling plays after he was diagnosed with cancer this week. He’s due to start chemotherapy today.
Steelers 19, Bills 16 OT ORCHARD PARK, N.Y. — Shaun Suisham kicked a 41-yard field goal with 2:14 left in overtime to lift the Steelers. Buffalo (2-9) blew an opportunity to win it with 10:30 left in overtime. Wide receiver Stevie Johnson got in behind the Steelers secondary but dropped a 40-yard pass on the run, while he was 2 yards into the end zone. The Bills overcame a 13-point first-half deficit and forced overtime with 2 seconds left in regulation when Rian Lindell hit a 49-yard field goal. Rashard Mendenhall had 151 yards rushing and scored a 1-yard touchdown, while Suisham hit all four field-goal attempts, including a 48-yarder in a game the Steelers (8-3) never trailed. The decisive field goal
The Associated Press
Houston cornerback Glover Quin (29) intercepts a pass intended for Tennessee tight end Jared Cook, right, as Texans linebacker Brian Cushing (56) defends in the fourth quarter Sunday in Houston. Quin had three interceptions. capped a 13-play, 58-yard early injury. drive in a game both teams Favre went 3-for-3 on the had chances to win. Vikings’ opening possession, which ended with Peterson’s 5-yard touchFalcons 20, down run. Packers 17 The 41-year-old quarterATLANTA — Matt Bry- back was 5-for-5 on the first ant kicked a 47-yard field drive of the second half, goal with 9 seconds remain- capped by a 5-yard TD from ing to give the NFC-leading rookie Toby Gerhart, who Falcons their fifth straight took over after Peterson left win. in the second quarter with a The Falcons (9-2) have bad right ankle. their longest winning streak Favre scrambled for a since 1998 and assured first down on third-and-8 themselves of a third right before the two-minute straight winning season. warning, then hugged sevOf course, they have eral teammates. much higher aspirations Minnesota (4-7) ended sitting atop the conference its nine-game road losing standings with five weeks streak, less than a week to go. after firing coach Brad ChilAaron Rodgers guided dress and promoting FraGreen Bay (7-4) on a 90-yard zier. drive to tie the game with Washington is 5-6. 56 seconds remaining. He converted a pair of Giants 24, fourth-down passes, includJaguars 20 ing a 10-yard touchdown EAST RUTHERFORD, pass to Jordy Nelson that N.J. — Eli Manning threw a made it 17-all. But Eric Weems broke 32-yard touchdown pass to loose on the kickoff return Kevin Boss with 3:15 to and was dragged down by play and the Giants rallied Matt Wilhelm with a fla- to snap a two-game losing streak and end the Jaguars’ grant facemask tackle. The Falcons took over at three-game winning streak. Manning also threw a the Green Bay 49, Matt 26-yard touchdown pass to Ryan completed four straight short passes and Mario Manningham, Lawrence Tynes kicked Bryant made the winning three field goals and the kick. defense came up with three consecutive sacks and a late Vikings 17, turnover with 1:25 to go as Redskins 13 the Giants (7-4) rallied from LANDOVER, Md. — an 11-point halftime defiBrett Favre was perfect on cit. David Garrard and two scoring drives, and Minnesota won Leslie Frazier’s Rashad Jennings ran for NFL head coaching debut touchdowns and Josh Scodespite Adrian Peterson’s bee kicked two field goal as
Cherry rist Hill Flo Proud to offer You…
0A5096461
Rams 36, Broncos 33 DENVER — Rookie Sam Bradford threw for three touchdowns and had his first 300-yard game as St. Louis escaped with a rare road win, which came just over a day after the NFL fined the Broncos and their coach for a videotaping scandal. The Rams had a seemingly safe 33-13 lead heading into the fourth quarter, but the Broncos (3-8) pulled within three points on Brandon Lloyd’s TD catch from Kyle Orton with 2:35 remaining. The Rams (5-6) held on and now share first place in the NFC West with Seattle, which lost to Kansas City. Bradford was 22-of-37 for 308 yards.
Gary’s Plumbing
Want to Buy: Home in
Since 1965
SEWER & DRAIN CLEANING
Monterra community.
EMERGENCY SERVICES AVAILABLE
681-8536
01309057
Remodel • Repipe • RepaiR Residential & Mobile Homes SEWER & DRAIN liNeS JeTTeRS • SeWeR CameRa • SeWeR liNe loCaTiNG WaTeR HeaTeRS •BUilT-iN VaCUUm CleaNeRS
(360)457-8249
WA State Journeyman #COLLIBG0030 Licensed • Bonded • Insured 0B5075441
507 S. Cherry Hill St. 360-457-0494
seaweed d l u o h s Where job? a r o f k o lo
won a franchise recordtying eighth straight game at home...
We Can Solve Your Plumbing, Drain & Sewer Problems
Same day delivery to P.A. and Sequim Fresh flowers arranged or wrapped Green and blooming plants Specializing in wedding and sympathy flowers Designer on site with over 30 years experience
Check us out on Facebook
the Jaguars (6-5) lost for ran for 95 yards and a score only the third time in eight for the Dolphins (6-5), who won for the fifth time in six games. road games to keep their playoff hopes alive. Browns 24, The Raiders (5-6) Panthers 23 returned home following a CLEVELAND — John 35-3 beating in Pittsburgh Kasay missed a 42-yard and put together another field goal that grazed the dud. left upright as time expired, Fan favorite Bruce Gradallowing the Browns to kowski got the nod ahead of escape and give ex-Panthers Jason Campbell at quarterquarterback Jake Del- back, but threw two interhomme a little satisfaction. ceptions. Kasay had a chance to win it for the Panthers Bears 31, (1-10) after rookie quarterEagles 26 back Jimmy Clausen drove CHICAGO — Jay Cutler them to Cleveland’s 25, completing a beautiful side- tied a career high with four line pass to Brandon LaFell touchdown passes and Chicago took sole possession of with five seconds left. After the play was first place in the NFC reviewed, Kasay pulled his North. The win was the Bears kick just wide to the left, ending another tight game (8-3) fourth straight and for coach Eric Mangini and put them a game ahead of the Browns (4-7), who led Green Bay. 21-7 at halftime. Michael Vick and the Cleveland’s Peyton Hillis Eagles (7-4) had won three rushed for 131 yards and straight, but were unable to three touchdowns, and Del- break off big plays against homme passed for 245 yards one of the league’s stingiest in his first start at home for defenses and fell into a tie the Browns, who signed him with the Giants for the NFC in March after he was East lead. released by Carolina. Vick threw for 333 yards and two touchdowns. But he also threw his Dolphins 33, first interception of the year Raiders 17 when he got picked off by OAKLAND, Calif. — Chris Harris in the end Chad Henne returned from zone late in the first half, a benching and injury to stopping a potential gothrow for 307 yards and two ahead scoring drive. scores, and Dan Carpenter kicked four field goals for Ravens 17, Miami. Buccaneers 10 Davone Bess had 111 BALTIMORE — Joe yards receiving in his first game as a pro in his home- Flacco threw two touchtown, and Ricky Williams down passes, and Baltimore
PO Box 255 • Port Angeles, WA 98362
In th “Kelp Wa e nte section! d” 0B5102991
Peninsula Daily News for Monday, November 29, 2010
SECTION
c
Our Peninsula
CLASSIFIEDS, COMICS, PUZZLES, DEAR ABBY In this section
Mushroom mania
Eric Shields found this orange cup fungus, known as aleuria aurantia, in the woods near Forks. As pretty as it might be, it is not very tasty.
A Fungus Fustivus Editors note — Columnist Matt Schubert’s work usually appears in Sports, Page B1, on Thursdays and Fridays. This bonus column chronicles the PDN’s third annual mushroom photo contest.
Thus, it is with great pride that I announce this year’s winners and thank each and every one of you for participating. (Also, a special thanks goes to the PDN’s resident mycologist, Sam Nugent, who helped identify the MANIA HIT A fevered winning submissions.) pitch this fall. Without further ado, But it here are the results: had noth- Matt ■ Mushroom most ing to do likely to distract a Twiwith Port Schubert Hard (aka “prettiest Angeles mushroom”) — As this City category proved once again, Council. fungi can indeed be fair. No, The most popular catemy dear gory for the second straight Peninsuyear (35 entries), it was by lites, this far the toughest to judge. phenomeAfter going back and non was forth for several hours, I all about decided on the orange cup the funfungus (aleuria aurantia) gus among us. found by Eric Fields in the Mushroom Mania: A woods near Forks. Fungus Festivus returned While this magnificent to the North Olympic Pen- piece of mold is technically insula this fall edible, it isn’t recomAnd once again, the mended by Nugent that PDN’s third annual mush- you actually do so. room photo contest Instead, just look and inspired dozens to march admire. deep into the dark recesses ■ Largest mushroom of the edge of the Earth. — Thank goodness for They found fungi large social media. and small, dreamy and If not for Facebook, we deformed, so that we could might never have been able all celebrate our shrooms to enjoy the Peninsula’s the way Mother Nature most mammoth mushroom intended. of the season. Some might call these Courtney Popp and brave and bold PeninsuAnthony Graham found a lites heros. giant puffball mushroom Others might say they (calvatia gigantea) growing broke the mold. in their Sequim front yard A Mushroom Mania and posted a photo of it on record 74 photos were sub- Popp’s Facebook page. mitted to the contest. One of their “friends” That made for some informed them of the long hours in front of the Mania, and soon enough, a computer screen for the picture of their 2-year-old contest’s official judges son, Ryder, riding the (yours truly and my special mushroom like a horse lady friend). found its way to my inbox. With so much first-class Of the 27 entries for the fungi staring us in the face, category, it was the largest. we took our duties quite seriously. Turn to Mania/C2
Courtney Popp and Anthony Graham of Sequim found this gigantic puffball mushroom (Calvatia gigantea) growing in their front yard. Their 2-year-old son, Ryder Graham, even attempted to ride the thing.
The Townsend family of Port Angeles stumbled upon this peculiarly shaped mushroom while traipsing around the Sol Duc Valley this fall. The mushroom, which was unidentified, bares a distinct resemblance to Franklin the Turtle of cartoon fame. It is the winner of the “Mushroom most resembling a notable figure” category.
Feel Free To Bring Your own Camera!
Wed. Dec. 1 Thur. Dec. 2 Fri. Dec. 3 Sat. Dec. 4
4 to 7 4 to 7 4 to 7 4 to 7
Wed. Dec. 8 4 to 7 Thur. Dec. 9 4 to 7 Fri. Dec.10 4 to 7 Sat. Dec. 11 12 to 4
The “Original” Since 1957
PORT ANGELES, WA U.S.A. © 2010 Swain’s General Store Inc.
0B5102132
The Townsend family found this coral mushroom (Clavariaceae) in the Sol Duc Valley.
602 East First PORT ANGELES 452-2357
C2
PeninsulaNorthwest
Monday, November 29, 2010
Peninsula Daily News
Pat-downs enhanced, but hardly thorough TSA agent fails to find coins, keys in passenger’s pocket By Ariel Kaminer The New York Times
NEW YORK —.
Firsthand experience Last week. Did I have any metal objects in my pockets? No. Would I prefer a private screening area? No. Then the officer’s hands did as she warned me they would. They poked around the back of my collar, they extended along my shoulders, they ran up and down..
‘Freaking out’. (It wasn’t successful, according the TSA, with only a minority nationwide opting purposely for the pat-downs.)
Accomplishes little?
The Associated Press
A passenger undergoes a pat-down search from a TSA officer Wednesday at Seattle-Tacoma International Airport.
a “you don’t know the half of it” look. Then she worked her way over my belly and inside the waistband of my jeans. A note to airline travelers: You might want to rethink those fashionably low-waist pants. I wished I Unsuccessful ‘opt-out’ had. Then it was up and down Still, opting out of them my thighs again and over a may shield you from prying “sensitive area” indeed. electronic eyes, but it just lands you where I was, right Afterwards, a yogurt in the palm of the security agency’s roving hands. How many films and So, were people freaking novels have imagined thrilling physical encounters out? My screener flashed me between traveling strang-.
ers,. 8 trips through security Oh, well. I exited the secure area, All told, I submitted to put a battery in my pocket the security agency’s 10-fin-
g.
Accessing the issues.
Inconvenience worth it The inconvenience is worth it, of course, if it works — if it uncovers potential dangers before they board a plane. That’s what a spokesman for the TSA.
Does smoking cigarettes actually relieve stress? Studies find opposite to be true The New York Times
NEW YORK —, not fall. For those dependent on smoking, the only stress it relieves is the withdrawal between cigarettes. In a recent study conducted at the London School of Medicine and Dentistry,
RECLINER SALE! Quality • Price • Selection
50
$
452-3936 • 2830 Hwy. 101 East • Por t Angeles
Continued from C1 came close. ■ Mushroom most Although there were resembling a notable figa number of cauliflower ure — Not surprisingly, mushrooms that this was the most enter-
Sequim Shoe Repair
Leather Goods, Shoe Findings, Sheepskin Slippers
The Peninsula Daily News wants to congratulate North Olympic Peninsula businesses celebrating anniversaries in December. On Dec. 10th, we will publish a FREE ad listing the businesses who respond to this special event by Dec. 6th. Is your business having an anniversary later this year? You can use this coupon now to let us know the date.
425 East Washington Ste. #5, Sequim
095096520
683-8637
Celebrating 50 years of Snack Bar Available!
8th & Laurel • Port Angeles, WA 98362
457-5858
01123197
Business Name _____________________________________________________________________ Address____________________________________________________________________________ City__________________ State________________ Type of Business________________________ Zip Telephone________________________________ What date is your anniversary?_______________________________________________________ Which anniversary is your business celebrating?______________________________________________ Please Mail or Bring to: Peninsula Daily News 305 W. 1st St., P.O. Box 1330, Port Angeles, WA 98362 Attn: ANNIVERSARY EVENT
MOUNTAIN VIEW HEARING
We’d like to help you celebrate! During your anniversary month, you can run an ad at the following discount prices: (One time only – any day of the week. No variations of size or price) PDN 0C5077208
Full Page..............................$1000 Half Page...............................$650 Quarter Page..........................$450 Plus we will give you 1 COLOR FREE
BETTER HEARING with a human touch
Shannon & Robert
MOUNTAIN VIEW Monday through Thursday, 9am- 4pm
625 N. 5th Ave, Ste. 3 • Sequim
85309511
(360) 681-4481 • 1-800-467-0292
taining of the three categories this year. A total of 12 photos were submitted, with entries going across the entire spectrum from the good (Mother Teresa) to the bad (Jacob Marley) to the ugly (Jabba the Hut). One particularly motivated shroomer, Vickie DeMott of Port Angeles, came up with three fungal look-alikes worthy of recognition. That included a stunningly similar mushroom match of the late comedian Jimmy Durante (featured in last Friday’s outdoors column). In the end, however, I had to go give the nod to the Townsend family of Port Angeles. Clay, Stacey and their three children (7-year-old Gracie, 4½-year-old Ezra and 4-month-old Lucy) scoured the Sol Duc Valley in search of shrooms. The found some catching coral mushrooms, a chanterelle that looked like the Batman symbol and, best of all, a piece of fungus that was a dead-on ringer for Franklin the Turtle. You know what they say, a family that finds fungus together . . . Actually, I’m not sure how that goes.
________
HEARING AID CENTERS, INC.
(360) 417-3541 • FAX (360) 417-3507 • 1-800-826-7714
nicotine cravings and thus had eliminated a frequent and significant source of stress. Other studies have also found that smokers experience higher levels of stress and tension between cigarettes and lower levels over all when they quit. The bottom line, according to the studies: The calming effect of a cigarette is a myth, at least in the long term.
Turtle mushroom wins
0B5104491
Mon-Sat 9:00 a.m. - 5:30 p.m. • Sun 11:00 a.m. - 4:00 p.m.
had ‘
Mania: Franklin the
O F F
any recliner in stock. Choose from Benchmaster, Best and Catnapper. FINANCING AVAILABLE 6 Months Same As Cash OAC NEW FURNITURE AND MATTRESSES
Matt Schubert is the outdoors and sports columnist for the Peninsula Daily News. His column regularly appears on Thursdays and Fridays. He can be reached at matt.schubert@peninsuladaily news.com.
PeninsulaNorthwest
Peninsula Daily News
Monday, November 29, 2010
C3
Canadian Coast Guard unready for oil spill Audit exposes a lack of training, aging equipment news services
OTTAWA — The Canadian Coast Guard lacks the training, equipment and management systems to fulfill Coast Guard employees are trained on an “ad hoc, regional basis,” with no national training strategy. Meanwhile, the Coast Guard is relying on aging equipment — the operating status of which it is unable to track — and manage-
ment controls are “either out-of-date, not functioning or not in place.” “As such, assurance cannot be provided that the conditions exist to enable [environmental-response] services to be provided in a national consistent manner,” states the audit, which was completed just more than a month before an explosion at BP’s Macondo well in the Gulf of Mexico unleashed the biggest offshore oil spill in history this spring.
Lead agency Under Canada’s patchwork response regime, the lead agency would depend on the nature and location of a spill. Off the East Coast, joint federal-provincial petroleum boards would oversee the cleanup of a spill at a drilling rig, while the National Energy Board would handle that responsibility in Arctic waters. But the Coast Guard would take the lead in any
Things to Do Today and Tuesday, Nov. 29-30, in: n Port Angeles n Sequim-Dungeness Valley n Port TownsendJefferson County n Forks-West End
The Answer for Youth — Drop-in outreach center for youth and young adults, providing essentials like clothes, food, Narcotics and Alcoholics Anonymous meetings, etc. 711 E. Second St., 3 p.m. to 7 p.m.
The star, known as HIP 13044, has been around for at least 6 billion years and has only several million years of life left, Setiawan said.
Plaza Jewelers
Diamonds
“
fix everything.”
Walk on the Wild Side
of our beautiful Olympic Peninsula. Special winter rates at our luxurious hot tub fireplace cabins on the banks of the Sol Duc River. Sun. - Thur. stay 2 nights at $150 per night, 3rd night free. Fri. and Sat. $175 per night, 2 night min.
Visit for slide shows and details (360) 327-3755
SIBLING DISCOUNTS AVAILABLE!
From left: Nathaniel, Marti & Katie
511 E. Washington Street • Sequim (next to Sequim Sunnyside Mini-Storage) • 360-683-1418 • Open Tues.-Fri. 10-5; Sat. 10-4; closed Sun. & Mon.
ENROLL ANYTIME NO SESSIONS
Sign Up for Winter Classes! Classes for ages 2 & up Available Weekdays & Saturdays
Located at 3318 Acorn Lane, PA (West of McCrorie Carpet One) paathletics.com 457-5187 • klahhanegymnastics@gmail.com
Serenity thrift Stores open 7 Days a Week!
Shop early for your holiday Decorations!
360-681-3800
suncrestvillage@legacysrliving.com
Pain-Free Is The Point!© Treating
• Acid Reflux • Irritable Bowel • Fibromyalgia • Crohn’s Disease • Chronic Constipation/ Diarrhea
With
• Personalized Holistic 1 on 1 care • Professional Staff • Medicine With Over 2,000 Years of Proven Effectiveness • Free Phone Consultation
Call for an appointment today!
Pat Flood
leS
!
502 east 1st Port angeles 452-4711
215 N. Sequim ave. Sequim 683-8269
Store Hou ew Mon. - Fri. 8- 6 Sat. 9- 5 CHeCk out our
Weekly SpeCialS
“HAY!”
Come on in and say
173 Mt. Pleasant Rd.
M.S., L. Ac.
Pat has been practicing, teaching, and speaking on Acupuncture and Traditional Chinese Medicine Since 1993
Ch out eCk Dailour Sa y
(previously Mt. Pleasant Country Supply)
Open Monday thru Saturday
M-F 8-6 • Sat. 9-5
360.452.1400 360.461.1091
0B5103722
251 S.FIFTH AVE. SEQUIM
417-8870
035076349
M-F 7-6 • Sat 10-3
095096601
INCOME LIMITS APPLY VISIT US TODAY YOU COULD BE ENJOYING YOUR RETIREMENT YEARS RIGHT NOW !
Tom’s
0B5101557
and includes ultilities, except for phone & cable TV. SERVICE FEES $381/MONTH
53 Valley Center Place, Sequim (Across from old Costco)
Few million years left
0A5097301
Rent is 30% of your adjusted income.
planet to pick up other materials and grow,” Setiawan said. It is unclear whether the planet ever had life forms, since it is a gaseous planet like Jupiter. Its distance from its host star is only a tenth of that between the Earth and the Sun, making life on any nearby planets that may exist virtually impossible because of high temperatures.
rs
0B5101850
360-681-50
Mangosteen
at the Max Planck Institute for Astronomy in Heidelberg, Germany. “The most important thing is to understand how a planetary system evolves, and maybe our solar system will experience the same process in the next 2 or 3 billion years.”
Currently, the star and its planet are in the Milky Way. The star has a low metallicity, which is a measure of elements other than hydrogen and helium. An abundance of metal is thought to help planets form, so it is surprising the star has only about 1 percent of the metallicity of our sun. “Metal helps form planetary embryos, and you need an embryo for the
& Natural Wellness Clinic
COMPARE T HESE FEATURES
Ultimate Health with
NEW YORK — A new planet the size of Jupiter with origins outside the Milky Way galaxy has been discovered, according to a study in the journal Science. The finding is important because the planet orbits a very old star that is nearing the end of its life span and may soon collapse. “We want to study this and see how far the star can evolve until the whole planet is engulfed or destroyed,” said Johny Setiawan, the study’s lead author and an astronomer
603 E. 8th, Suite E Port Angeles
We Carry
Itchy? Scratchy K9?
The New York Times
0B5103720
General discussion group — Port Angeles Senior Center, 328 E. Seventh St., 1:30 p.m. to 4 p.m. No specified topic. Open to public.
Scientists hope to learn about life cycle of system
0B5102990
Mental health drop-in center — The Horizon Center, 205 E. Fifth St. , 4 p.m. to 6:30 p.m. Port Angeles For those with mental disorders and looking for a place to Today socialize, something to do or a Overeaters Anonymous — hot meal. For more information, St. Andrew’s Episcopal Church, phone Rebecca Brown at 360510 E. Park Ave., 9 a.m. Phone 457-0431. 360-477-1858. Senior meal — Nutrition Pre-3 Co-op Class — For program, Port Angeles Senior parents and toddlers10 months Center, 328 E. Seventh St., to 31⁄2 years. First Baptist 4:30 p.m. Donation of $3 to $5 Church, Fifth and Laurel per meal. Reservations recomstreets, 9:30 a.m. to 11:30 a.m. mended. Phone 360-457Associated with Peninsula Col- 8921. lege, quarterly cost is $75 with annual $25 registration fee. Port Angeles Toastmasters Club 25 — Clallam Transit Walk-in vision clinic — Business Office, 830 W. LauridInformation for visually impaired sen Blvd., 6 p.m. to 7:30 p.m. and blind people, including Open to public. Phone Bill accessible technology display, Thomas at 360-460-4510 or library, Braille training and vari- Leilani Wood 360-683-2655. ous magnification aids. Vision Loss Center, Armory Square Bingo — Masonic Lodge, Mall, 228 W. First St., Suite N. Phone for an appointment 360- 622 Lincoln St., 6:30 p.m. 457-1383 or visit Doors at 4 p.m. Food, drinks and pull tabs available. Phone lossservices.org/vision. 360-457-7377. Guided walking tour — Historic downtown buildings, Tuesday an old brothel and “UnderPA Vintage Softball — ground Port Angeles.” Chamber of Commerce, 121 E. Rail- Co-ed slow pitch for fun, fellowroad Ave., 10:30 a.m. and 2 ship and recreation. Phone p.m. Tickets: $12 adults, $10 Gordon Gardner at 360-452senior citizens and students, 5973 or Ken Foster at 360-683$6 ages 6 to 12. Children 0141 for information including younger than 6, free. Reserva- time of day and location. tions, phone 360-452-2363, ext. 0. Tai chi class — Ginger and Ginseng, 1012 W. 15th St., 7 Volunteers in Medicine of a.m. $12 per class or $10 for the Olympics health clinic — three or more classes. No 909 Georgiana St., noon to 5 experience necessary, wear p.m. Free for patients with no loose comfortable clothing. insurance or access to health Phone 360-808-5605. care. Appointments, phone 360-457-4431. Port Angeles Business Association — Joshua’s ResFirst Step drop-in center taurant, 113 DelGuzzi Drive, — 325 E. Sixth St., 1 p.m. to 4 7:30 a.m. Open to the public, p.m. Free clothing and equip- minimum $2.16 charge if not ment closet, information and ordering off the menu. referrals, play area, emergency supplies, access to phones, Turn to Things/C5 computers, fax and copier. Phone 360-457-8355.
pay them any attention, they’re always at the end of the line for any budget,” said Rob Huebert, associate director of the Centre for Military and Strategic Studies at the University of Calgary. Huebert said the federal government should consider arming the Coast Guard with better spill-response tools, given the fact that offshore drilling and tanker traffic is expected to intensify in Canada’s Arctic waters. Several oil companies have acquired licenses to explore for oil in Canada’s portion of the Beaufort Sea, although drilling isn’t expected to take place for at least a few years. A spokeswoman for the Department of Fisheries and Oceans, which is responsible for the Coast Guard, said the audit’s recommendations have been “incorporated into the environmental response work plan. “Work has started on many of the initiatives and we remain on target for completion,” the spokeswoman said in a statement. The Coast Guard recently acquired 20 new “environmental response barges,” she added.
Astronomers keep eye on new planet circling old star
N
Peninsula Daily News
the agency lacks a way to monitor what training has been received by staff. Similar issues dog the Coast Guard’s equipmentmanagement system, leaving staff with no “current, reliable, up-to-date information on the operational status of equipment. “The last major investment in equipment in the program was . . . in the 1990s. “Since then, there has Postmedia News been no consistent, nationCanadian Coast Guard icebreaker Louis S. St. ally co-ordinated investLaureate. ment in equipment. “Equipment acquisitions spill from an oil tanker, or a like a loose alliance of are on a regional basis and “mystery spill” whose origin regional offices than a based on the availability of funding throughout the national organization. is unknown. The audit team “found year,” the audit states. The Coast Guard’s “environmental-response” unit that there were no nationdeals with roughly 1,300 ally consistent, detailed ‘Political orphan’ reported pollution incidents standard operating proceOne academic expert each year, despite having dures, only regional operatwho has studied the Coast ing procedures that are not only about 80 staff and a modest budget of $9.8 mil- approved by headquarters.” Guard said the agency has Internal auditors also become a “political orphan” lion. found that information that, unlike the Canadian about incidents was not Forces, doesn’t get much ‘Loose alliance’ recorded in a manner that political or public support The agency has 12 would allow for the review when lobbying for budget increases. staffed depots, with equip- of incident responses. “The Coast Guard tends ment spread across the The Coast Guard hasn’t country at 70 additional identified the level of knowl- to be one of these organizalocations. edge, skills and tools tions that is very profesThe audit describes an required for all environ- sional in what they do but agency that operates more mental-response staff, and because most people don’t
C4
Monday, November 29, 2010
Fun ’n’ advice
Tundra • “Cathy” has been retired; we’re auditioning this comic. Share your thoughts: comics@peninsuladailynews.com.
Peninsula Daily News
Cheating son-in-law worries mother
For Better or For Worse
Dear Aghast: Once a gift is Van Buren.
Abigail
Dear Abby: It will soon be that time of year when adult children will wrack their brains to find Christmas gifts for their elderly parents. Two years ago, my daughter gave me the gift of a lifetime — my pets’ Dear Sick with Worry: Because lives. your son-in-law continued being Knowing how much my dog and unfaithful to your daughter more cats mean to me since I live alone, than once, I seriously doubt that he’s she and my son-in-law called to say going to quit. that instead of giving me another When a man — or woman — knickknack for Christmas, my birthforms a pattern of cheating, it rarely day or Mother’s Day, they would pay stops. all my veterinary bills for the life of I hope your daughter understands each pet. that before having children. It was a welcome surprise and a special, thoughtful gift. Dear Abby: My 6-year-old Pets bring companionship and daughter “Kaylee” recently spent a comfort to those of us who live alone weekend with her grandparents. on fixed incomes. While she was there, they bought Knowing they will have the her several gifts. proper veterinary care is, indeed, the Today, her grandmother called gift of a lifetime. and asked to have one of the gifts Even if you can’t assume all the back. costs of your parents’ pets, chipping A friend of hers would like to in on holidays would help a lot. have the decorative musical instruAppreciative Mom in Illinois ments she gave to Kaylee. Grandma’s idea is to offer to buy Dear Appreciative Mom: I something else for my daughter and agree, and that’s why I’m printing “trade.” your letter. I don’t know how to handle this. With so many people feeling I can’t imagine asking someone to stressed economically, your letter return a present I had given him or may provide the “purr-fect” solution her. to what to get for an older relative. Kaylee loves the instruments and ________ has been playing with them every Dear Abby is written by Abigail Van day since she received them. Buren, also known as Jeanne Phillips, However, I think her grandma and was founded by her mother, Pauline (my stepmother) will be upset if I Phillips. Letters can be mailed to Dear don’t go along with her plan. Abby, P.O. Box 69440, Los Angeles, CA Abby, help. 90069 or via e-mail by logging onto www. Aghast in San Francisco dearabby.com.
Pickles
Frank & Ernest
Garfield
Momma
The Last Word in Astrology By Eugenia Last
near future. 4 stars
feed your creativity. 4 stars
ARIES (March 21-April 19): Don’t waste time arguing about something you cannot change. Be prepared for whatever comes your way and realize that responding, instead of reacting, will bring you much closer to getting what you want. A tight budget is a must. 3 stars
LEO (July 23-Aug. 22): Impulsive action due to emotional upset will not pay off in the end. Concentrate more on work and productivity and less on spending money. Face any challenge with confidence and play to win. Avoid useless arguments. 3 stars
SAGITTARIUS (Nov. 22-Dec. 21): Stay put. You will only make matters worse if you push your way in where you don’t belong. Travel and communications will not be your strong point. Challenging circumstances are apparent and remaining calm is essential. 2 stars
VIRGO (Aug. 23-Sept. 22): You’ll have to juggle things around if you don’t want to upset the people with whom you spend most of your time. An emotional matter will catch you off guard but that doesn’t mean you should let anyone take advantage of you. Act fast, but not in anger. 3 stars
CAPRICORN (Dec. 22-Jan. 19): Caution must be maintained, especially where institutions and financial matters are concerned. Look after your own statements and personal paperwork if you want to make sure that everything is taken care of properly before year’s end. 5 stars
LIBRA (Sept. 23-Oct. 22): There will be a lot of information left unsaid. Dig deep before you make a decision. You have to be fully aware of what is going on behind the scenes. An old friend can give you an intuitive look at what you should be aware of. 3 stars
AQUARIUS (Jan. 20-Feb. 18): You have to dedicate time, space and your skills to something that will help you make gains financially, legally or contractually. Don’t be afraid to speak up in your defense. Timing is crucial. 3 stars
TAURUS (April 20-May 20): A greater understanding regarding your position and how far you can go in the future will help you determine if you should make a move now or stay put. Humanitarian causes will lead to new friendships and a chance to make self improvements. 5 stars
Rose is Rose
GEMINI (May 21-June 20): Look over all the information made available before you react harshly to something or someone. Unnecessary purchases may be a quick fix for depression but, in the end, will only add to debt. Hard work and innovation are your best solutions. 2 stars
Elderberries
CANCER (June 21-July 22): Focus on home, family and keeping a stellar reputation. Consider any responsibilities thrown at you to be a test that allows you to show off and impress others. The way you handle situations will lead to a position in the
Dennis the Menace
dear abby
Doonesbury
SCORPIO (Oct. 23-Nov. 21): Saying and not doing will lead to a poor reputation that can hinder your chance to advance. Any show of indecision or frustration will work against you. An unusual alteration at home will help
The Family Circus
Now you can shop at!
PISCES (Feb. 19-March 20): Observe but don’t be too quick to move. You have to be sure you have the facts. Playing Russian roulette regarding your personal or professional partnerships will end in disaster. Control your emotions. 3 stars
PeninsulaNorthwest
Peninsula Daily News
Things to Do Continued from C3 Mahina 3390.
Pre-3 Co-op Class — For parents and toddlers 10 months to 3 1/2 years. First Baptist Church, Fifth and Laurel streets, 9:30 a.m. to 11:30 a.m. Associated with Peninsula College, quarterly cost is $75 with annual $25 registration fee. Tatting class — Golden Craft Shop, 112-C S. Lincoln St., 10 a.m. to noon. Phone 360-457-0509. Guided walking tour — Historic downtown buildings, an old brothel and “Underground Port Angeles.” Chamber of Commerce, 121 E. Railroad Ave., 10:30 a.m. and 2 p.m. Tickets: $12 adults, $10 senior citizens and students, $6 ages 6 to 12. Children younger than 6, free. Reservations, phone 360-452-2363, ext. 0.
Lazzaro
Chess game — Students elementary through high school. Port Angeles Public Library, 2210 S. Peabody St., 3:30 p.m. to 4:30 p.m. Chess boards available. Phone 360-417-8502 or click on. Parenting class — “You and Your New Baby,” third-floor sunroom, Olympic Medical Center, 939 Caroline St., 4 p.m. to 5:30 p.m. Free. Phone 360417-7652. Watercolor class — With artist Roxanne Grinstad. Holy Trinity Lutheran Church, 301 E. Lopez St., 11 a.m. to 1 p.m. $40 for four-week session. Drop-ins welcome. Senior meal — Nutrition Phone 360-452-6334 or e-mail program, Port Angeles Senior rcgrinstad@hotmail.com. Center, 328 E. Seventh St., Veterans Wellness Walk — 4:30 p.m. Donation of $3 to $5 Port Angeles Veterans Clinic, per meal. Reservations recom1005 Georgiana St., noon. mended. Phone 360-457Open to all veterans. Phone 8921. 360-565-9330. Wine tasting — Bella Italia, Bingo — Port Angeles 118 E. First St., 4:30 p.m. to Senior Center, 328 E. Seventh 6:30 p.m. Tasting fee $10 to St., 12:30 p.m. to 3 p.m. Phone $15. Taste four different wines from restaurant’s wine cellar. 360-457-7004. Reservations suggested. First Step drop-in center Phone 360-457-5442. — 325 E. Sixth St., 1 p.m. to 4 Open mic jam session — p.m. Free clothing and equipment closet, information and Host Victor Reventlow. Fairreferrals, play area, emergency mount Restaurant, 1127 W. supplies, access to phones, U.S. Highway 101, 5:30 p.m. to computers, fax and copier. 8:30 p.m. All musicians welcome. Phone 360-457-8355. Asian brush painting (sumi) trees class — With Roxanne Grinstad. Holy Trinity Lutheran Church, 301 E. Lopez St., 1 p.m. to 3 p.m. $40 for four-week session. Drop-ins welcome. Phone 360-452-6334 or e-mail rcgrinstad@hotmail. com. Beginning Hula for Adult Women — Port Angeles Senior Center, 328 E. Seventh St., 1 p.m. to 2 p.m. $28 for four weekly sessions. Drop-ins welcome. Bring water, wear a long skirt that doesn’t touch floor, go barefoot or may wear socks/ soft shoes. Phone instructor
Music jam session — Veela Cafe, 133 E. First St., 7 p.m. to 9:30 p.m. Bring instruments.
C5
. . . planning your day on the North Olympic Peninsula
360-809-
Good News Club — For students 5 to 12 years. Jefferson Elementary School Reading Room, 218 E. 12th St. 1:45 p.m. to 3 p.m. Phone 360-4526026 or visit.
Monday, November 29, 2010.
Senior Swingers dance — Port Angeles Senior Center, 328 E. Seventh St., 7:30 p.m. to 9:30 p.m. First visit free. $5 cover all other visits. Music by Wally and the Boys. “Meet me in St. Louis” — Port Angeles Community Playhouse, 1235 E. Lauridsen Blvd., 7:30 p.m. Tickets $14 available online at communityplayers.com or Odyssey Bookshop, 114 W. Front St.
Sequim and the Dungeness Valley Today
Sequim Duplicate Bridge — Masonic Lodge, 700 S. Fifth Ave., 12:30 p.m. All players welcome. Phone 360-681-4308 or partnership 360-582-1289. Women’s weight loss support group — Dr. Leslie Van Romer’s office, 415 N. Sequim Ave. Family Caregivers support group — Trinity United Methodist Church, 100 Blake Ave., 1 p.m. to 3 p.m. Phone Carolyn Lindley, 360-417-8554. German class — Sequim Bible Church, 847 N. Sequim Ave., 2 p.m. Phone 360-6810226.
Health clinic — Free mediVinyasa Yoga — 92 Plain Jane Lane, 6 a.m. and 6 p.m. cal services for uninsured or Phone 206-321-1718 or visit under-insured. Dungeness Valley Health & Wellness Clinic,. 777 N. Fifth Ave., Suite 109, 5 Walk aerobics — First Bap- p.m. Phone 360-582-0218. tist Church of Sequim, 1323 Trivia night — The Islander Sequim-Dungeness Way, 8 Pizza & Pasta Shack, 380 E. a.m. Free. Phone 360-683- Washington St., 5:30 p.m. Free. 2114. Prizes awarded. Must be 21. Phone 360-683-9999. Exercise classes — Sequim Community Church, 1000 N. Women’s barbershop choFifth Ave. Cardio-step, 9 a.m. to rus — Singers sought for 10:15 a.m. Strength and toning Grand Olympics Chorus of class, 10:30 a.m. to 11:30 a.m. Sweet Adelines. Sequim Bible Cost: $5 a person. Phone Shel- Church, 847 N. Sequim Ave., ley Haupt at 360-477-2409 or 6:30 p.m. Phone Wendy Foster e-mail jhaupt6@wavecable. at 360-683-0141. com.
Port Angeles Zen Community — Meditation, dharma talk and discussion on Buddhist ethics from Robert Aitken Roshi’s The Mind of Clover. 7 p.m. to 8:30 p.m. Phone 360Free blood pressure 452-9552 or e-mail portangeleszen@gmail.com to screening — Faith Lutheran make an appointment for new- Church, 382 W. Cedar St., 9 a.m. to 11 a.m. Phone 360comer instruction. 683-4803. Line dancing — Vern BurSenior Singles — Hiking ton Community Center, 308 E. Fourth St., 7 p.m. to 8:30 p.m., and a walk, 9 a.m. Phone 360797-1665 for location. $2.
Tuesday Vinyasa Yoga — 92 Plain Jane Lane, 6 a.m. Phone 206321-1718 or visit www. sequimyoga.com. 18-Hole Women’s Golf group — Cedars at Dungeness Golf Course, 1965 Wood-
cock Road, 8 a.m. check-in. dance each month. Sequim New members and visitors wel- Prairie Grange Hall, 290 come. Macleay Road. Beginner, 7 p.m.; intermediate, 8:10 p.m. Senior Singles — Coffee $8 per week per class. Interand a walk, 9 a.m. Phone 360- mediate couples who have 797-1665 for location. attended previous classes can continue with beginning WIC program — First classes. Cost for both classes Teacher, 220 W. Alder St., 9 is $12. Phone 360-582 0738 or a.m. to 4 p.m. Phone 360-582- e-mail keendancer@q.com. 3428. Sequim Senior Softball — Port Townsend and Co-ed recreational league. Jefferson County Carrie Blake Park, 9:30 a.m. for practice and pickup games. Monday Phone John Zervos at 360Cabin Fever Quilters — Tri681-2587. Area Community Center, 10 Insurance assistance — West Valley Road, Chimacum, Statewide benefits advisers 10 a.m. Open to public. Phone help with health insurance and Laura Gipson, 360-385-0441. Medicare. Sequim Senior Center, 921 E. Hammond St., 10 Puget Sound Coast Artila.m. to noon. Phone Marge lery Museum — Fort Worden Stewart at 360-452-3221, ext. State Park, 11 a.m. to 4 p.m. 3425. Admission: $3 for adults; $1 for children 6 to 12; free for chilSequim Museum & Arts dren 5 and younger. Exhibits Center — Small Wonders interpret the Harbor Defenses Show and Sale. 175 W. Cedar of Puget Sound and the Strait St., 10 a.m. to 4 p.m. Free. of Juan de Fuca. Phone 360Phone 360-683-8110. 385-0373 or e-mail artymus@ olypen.com. Overeaters Anonymous — St. Luke’s Episcopal Church, Jefferson County Histori525 N. Fifth St., noon. Phone cal Museum and shop — 540 360-582-9549. Water St., 11 a.m. to 4 p.m. Admission: $4 for adults; $1 for Bereavement support children 3 to 12; free to historigroup — Assured Hospice cal society members. Exhibits Office, 24 Lee Chatfield Ave., 1:30 p.m. to 3 p.m. Phone 360- include “Jefferson County’s Maritime Heritage,” “James 582-3796. Swan and the Native AmeriBar stool bingo — The cans” and “The Chinese in Islander Pizza & Pasta Shack, Early Port Townsend.” Phone 380 E. Washington St., 4 p.m. 360-385-1003 or visit www. Free. Prizes awarded. Must be jchsmuseum.org. 21. Phone 360-683-9999. Quilcene Historical Olympic Mountain Clog- Museum — 151 E. Columbia gers — Howard Wood Theatre, St., by appointment. Artifacts, 132 W. Washington St., 6 p.m. documents, family histories to 9 p.m. $5 fee. Phone 360- and photos of Quilcene and surrounding communities. New 681-3987. exhibits on Brinnon, military, Olympic Peninsula Men’s millinery and Quilcene High Chorus — Monterra Commu- School’s 100th anniversary. nity Center, 6 p.m. For more Phone 360-765-0688, 360information, phone 360-681- 765-3192 or 360-765-4848 or 3918. e-mail quilcenemuseum@ olypen.com or quilcene Bingo — Helpful Neighbors museum@embarqmail.com. Clubhouse, 1241 Barr Road, Agnew, 6:30 p.m. Dinner, Silent war and violence snacks available. Nonsmoking. protest — Women In Black, Adams and Water streets, 1:30 Boy Scout Troop 1491 — p.m. to 2:30 p.m. St. Luke’s Episcopal Church, 525 N. Fifth Ave., 7 p.m. Open Overeaters Anonymous — to public. Phone 360-582- St. Paul’s Episcopal Church, 3898. 1032 Jefferson St., 5 p.m. Phone 360-385-6854. Social dance classes— Turn to Things/C10 Different ballroom or Latin
Peninsula MARKETPLACE Reach The North Olympic Peninsula & The World
IN PRINT & ONLINE
Place Your Ad Online 24/7 with Photos & Video PLACE ADS FOR PRINT AND WEB:
Visit | Call | 360.452.8435 | 800.826.7714 | FAX 360.417.3507 IN PERSON: PORT ANGELES: 305 W. 1ST ST. | SEQUIM: 150 S. 5TH AVE #2 | PORT TOWNSEND: 1939 E. SIMS WAY
peninsuladailynews.com 22 Community Notes 23 Lost and Found 24 Personals
22
24/7
Adult Family Home RN Homecare near Sequim has a private room available. Dementia and elder care, respite. Competitive prices. 683-1967.
23
Lost and Found
FOUND: Cat. Gray, obviously someones pet. McComb Road and Old Olympic Hwy. area. 683-6350
It’s easy, quick and what you see is what you’ll get!
• All from the comfort of your own Home
NEED EXTRA CASH!
• Choose the package that fits your needs
Sell your Treasures!
• See your ad before it prints • Add a border, logo or photo
360-452-8435 1-800-826-7714 91313079 dailynews.com PENINSULA CLASSIFIED
92313082
305 W. 1st St. P.O. Box 1330 | Port Angeles, WA 98362
Community Notes
Adult care home in Sequim has a private room available. Best care at best rates. Call Wild Rose at 360-683-9194
WITH OUR NEW CLASSIFIED WIZARD
PENINSULA DAILY NEWS
Monday - Friday 8AM - 5PM
TO PLACE A CLASSIFIED AD:
PLACE YOUR AD
• Pay online with debit or credit card
Office Hours
C6
MONDAY, NOVEMBER 29, 2010
23
Lost and Found
31
FOUND: Cat. Tortoise shell. Taylor Cutoff Road area, Sequim. 683-5414 LOST: Cat. Adult long-hair grey calico tortoiseshell. Missing since 11/23. Area of Cedar and 7th, P.A. 461-2099
25
31
Help Wanted
AIDES/RNA OR CNA Best wages, bonuses. Wright’s. 457-9236. Bank CSR positions. midsound.hr@washin gtonfederal.com
CAREGIVERS Due to growth, new positions available. 408 W. Washington Sequim. 360-683-7047 office@ discovery-mc.com
COOK: Experienced. Apply Shirley’s Cafe, 612 S. Lincoln, P.A. DRAFTS PERSON. Skilled in mechanical, structural and electrical 2D and 3D drafting using AutoCad and/or Solidworks with 5 years relevant experience. Working knowledge of mechanical engineering. Full-time position with benefits for manufacturer of industrial refrigeration systems. Email resume to info@imspacific.com or fax 360385-3410.
Help Wanted
Adult care home in Sequim needs a caregiver on weekends. (4) different shifts. Call 683-9194.
LABORER: License/ transportation needed. 683-9619 or 452-0840.
51
Work Wanted
Winterize lawns, rake leaves, etc. 797-3023
ROOFER: Experienced, valid license, own transportation, wage DOE. 683-9619/452-0840
TAXI DRIVER: Parttime, nights. Must be at least 25, clean driving record. Call 360-681-4090 or 253-377-0582
CLINIC DIRECTOR Responsible for the day-to-day administrative functions of Olympic Medical Center’s Primary Care and Internal Medicine Clinics. Bachelor’s Degree in Business Administration, Medical Administration or comparable experience. 3-5 previous successful clinic management experience required. Apply online at olympicmedical.org or email nbuckner@ olympicmedical.org.
31 Help Wanted 32 Independent Agents 33 Employment Info 34 Work Wanted 35 Schools/Instruction
34
Help Wanted
TAX PREPARER CPA or EA with active license for Tax Season. Sequim. Call Kathryn at 681-2325
Personals
SANTA’S GIFT Santa is still trying to find that special country lady, close to height/weight proportionate who wants that life full of love, togetherness, being best friends and a partner that she has never had before. What is inside is what counts. No smoking, no drugs. Santa has that special gift that has been waiting for the right lady for sometime and he will keep looking until that special lady comes into his life. White male, 60, 6’, height/weight proportionate, nonsmoker, brown hair, hazel eyes, beard, excellent health, who is very affectionate, romantic, caring, giving from the heart, down to earth, loves the outdoors and animals, home life, sense of humor. Honesty and respect is very important also. Santa has that special gift just waiting to be unwrapped by that right country lady that wants a life full of love that will grow every day. santa@olypen.com
31
Classified
LEGAL ASSISTANT Full -time, for personal injury law firm. Strong phone, typing and grammatical skills required. Case mgmt. experience a plus. Drop off or mail resume to 601 S. Race St. Suite A, P.A.
SELL YOUR HOME IN PENINSULA CLASSIFIED 1-800-826-7714
WANTED: Front office person for busy solo family practice. Insurance and coding exp. preferable. Send resume to: Peninsula Daily News PDN#184/Front Office Pt Angeles, WA 98362
34
Work Wanted
ADEPT YARD CARE Weeding and mowing. 452-2034 Hannah’s helping hands. Great worker, reliable, efficient, and timely. Will clean your home for the holidays and help to hang decorations too. Working in Joyce, Port Angeles, and Sequim. Please call Hannah Hope at 360-775-1258 HOLIDAY HELPER Lights, decor, gifts, etc. 360-797-4597. House Cleaning- Professional cleaning service, owner for over 10 years. $20/hr *See my online ad with photo* Excellent local references. 360-797-1261 home. 360-820-3845 cell. Ask for Julie. In-home care available for your loved ones. Experienced caring RN available, flexible hours, salary negotiable. Call Rae at 360-681-4271.
Sewing. I Sew 4U Hemming, curtains, alterations, any project. Don't wait! Call me today! Patti Kuth, 360-417-5576 isew4u.goods.officeliv e.com I'm Sew Happy! VHS to DVD copying services. Call Nancy 360-774-0971
51 Homes 52 Manufacured Homes 53 Open House 54 Lots/Acreage 55 Farms/Ranches 57 Recreational 58 Commercial Publisher’ster’s
A GREAT OPPORTUNITY Sunland for less than $200,000. Comfortable, easy to live with floor plan. Cozy fireplace for those chilly evenings. Great kitchen and dining area combo for easy living. All appliances included. $195,000. ML131039/251993 Cath Mich 683-6880 WINDERMERE SUNLAND A PLACE TO HANG YOUR STOCKINGS Best entertaining floor plan around with a well planned kitchen and fantastic entertainment center in the living room. You’ll love it and so will your friends. Lots of storage for your toys in the oversized garage plus detached double garage/ workshop. $409,000. ML250601 Pili Meyer 417-2799 COLDWELL BANKER UPTOWN REALTY
51
Homes
ACREAGE IN TOWN Charming 4 Br., 2 bath home on acreage in town. Nice updates with great features. Cozy and country describes this formal dining room area with separate living room and family room. In addition to the carport with storage, it has a 3 bay detached garage with over 1,300 sf. Minutes from downtown. $329,900. Jean Irvine 417-2797 COLDWELL BANKER UPTOWN REALTY BEACH YOURSELF Water views, beach and tidelands access (rights). 2 Br., 2+ bath. Bonus room, 1,732 sf, 2 car garage, master with private deck, french doors, hot tub. Come and FEEL what this home has to offer. $369,000. ML250446. Chuck Murphy and Lori Tracey 683-4844 Windermere Real Estate Sequim East BEST OF BOTH Close to town but with acreage, 3 Br., 2 bath, 1,808 sf home on 1.02 acres close to central Sequim. Single story, cedar siding, heat pump, two car garage plus RV garage/workshop. $250,000. ML252323 Steve Marble Blue Sky Real Estate Sequim 683-3900, 808-2088 Colonial home on a very private 6.32 acres. Great unobstructed view of the Olympic Mts./43085 Terry Neske 457-0456 WINDERMERE P.A.
WHY PAY SHIPPING ON INTERNET PURCHASES? SHOP LOCAL peninsula dailynews.com
PENINSULA DAILY NEWS
51
Homes
51
Homes
GREAT OLDER HOME Located in Sequim, this home features 2 Br., 2 baths, 2 living rooms both with fireplaces, covered patio with ramp to the home, large detached 2 car garage/shop with alley access and a fenced in back yard. $148,000. ML251950. Tom Blore Peter Black Real Estate 683-4116 HOME ON 2 ACRES 1.96 cleared acres with small barn/ workshop, 2 garden sheds. House has had some recent updates. There is 111’ of Dungeness River frontage. This property would be a wonderful investment or starter home. $219,900. ML250991. Linda Ulin 683-4844 Windermere Real Estate Sequim East
COUNTRY HAVEN Do you need a new and large 3 car garage? A newly restored historical cabin? A nice 3 Br., 2 bath home on 2+ acres? A private setting with a year around creek? This is it, look no further. Located not too far from the casino and Sequim Bay. $299,000. ML251651 Becky Jackson 417-2781 COLDWELL BANKER UPTOWN REALTY DUPLEX - SELLER FINANCING Duplex on 0.21 acre private lot. Built in 1975, each unit has 768 sf, 2 Br., 1 bath. Very stable rental history with longterm tenants. New roof in 2004. Seller financing possible. $215,000. ML250464. Marc Thomsen 417-2782 COLDWELL BANKER UPTOWN REALTY ESCAPE TO BLACK DIAMOND Just minutes from town, fantastic 4 Br., 2 bath on 3+ acres. 2,128 sf, recently treated to a tasteful kitchen update, new paint inside and out plus windows. MABD with walk-in closet and jetted tub in MABA. Large Detached shop all nicely landscaped with evergreens and fruit trees. $259,500. ML251628. Alan Burnwell 683-4844 Windermere Real Estate Sequim East
FANTASTIC VIEWS Strait, city lights, Victoria and Mount Baker. Vaulted cedar tongue and groove ceilings, skylights, fireplace with propane insert and two free standing propane stoves, separated MABD. Large wood deck off family room. RV parking with dump, water and electric. $397,000. ML251615. Karen Kilgore 683-4844 Windermere Real Estate Sequim East
NEAR THE WATER Nice 2 Br., 2 bath home. Great room has a freestanding fireplace where you can stay warm and cozy as you watch the ships go by via the partial water view. Master Br. is very large and has a sliding door that goes out to the front of the house. Walk in closet is very large and there is also an office/den. $165,000. ML252339/153095 Dave Stofferahn and Heidi Hansen 477-5542, 477-5322 COLDWELL BANKER TOWN & COUNTRY
The pros at PENINSULA DAILY NEWS can design AND print your publication. Great quality at competitive prices. Call Dean at 360-417-3520 1-800-826-7714
SEE THE MOST CURRENT REAL ESTATE LISTINGS: dailynews.com
51
Homes
Homes
FAIRWAY VIEW HOME Beautiful single level townhome, generous sized rooms throughout. Updated kitchen. Extra deep 2 car garage (golf cart/ shop). $314,500. ML129689/251966 Brenda Clark 683-6880 WINDERMERE SUNLAND
Lovingly restored Cherry Hill Victorian. 3 Br., 2 bath + cozy guest cottage and shop. $238,000. 360-457-6845
NEW CONSTRUCTION Experience stunning architecture and design in this 3 Br., 2 bath custom built home in a superbly planned residential community in Port Angeles. $234,900. ML252334/152434 Don Fourtner 461-5948 COLDWELL BANKER TOWN & COUNTRY
SALTWATER VIEW Single story 4 Br., 2.75 bath, gourmet kitchen elegance on one floor! Bamboo floors, 3 car garage, bonus room and beautiful grounds! Beach Club membership, too! $399,000. ML55633. Bryan Diehl 360-437-1011 Windermere Port Ludlow
NORTHERN LIGHT Backing onto one of SunLand’s common area green belt, the view and light coming in to this home are wonderful. 3 Br., 2 bath, with living room AND family room. $189,000. ML251645. Jane Manzer 683-4844 Windermere Real Estate Sequim East P.A.’S BEST KEPT SECRET Have you ever dreamed about living on a boat, a lakeside retreat or mountain top? Do you crave seclusion, saunas and relaxing dips in a hot tub? Looking for a place with city conveniences, elbow room and a quirky country feeling? Then this is the home for you! NW Contemporary with solar design features. Open concept floor plan with many nooks and crannies. Vaulted wood ceilings, sauna, hot tub, professional grade shop and unbelievable privacy on nearly a half-acre of land. $223,900. ML250920. Dick Pilling Carroll Realty 457-1111 PARKWOOD HOME 2 Br., 2 bath 1,998 sf home. Master Br. with sitting area. Oversized 2 car garage with work bench. Enclosed patio and landscaped yard. Large corner lot. $130,000 ML251593/108036 Deb Kahle 683-6880 WINDERMERE SUNLAND
P.A.: Cute home, 2 Br., 1.75 ba, wood stove, big garage, ramp, nice yard. $95,000. 360-452-2758, 360-775-7129
SEAMOUNT ESTATES In the premier west side neighborhood, this 2 story contemporary home has 4 Br., 2.5 bath, a large family room, formal dining and living rooms. With vaulted ceilings, exposed staircase, hardwood floors and a newer heat pump. $289,000. ML231193. Linda Debord 452-3333 PORT ANGELES REALTY STATELY ELEGANT HOME 3 Br., 2.5 bath on .43 acre lot in SunLand. Granite counters and cherry cabinets in kitchen. Master suite opens to nice yard. Covered tile patio and gazebo. 3 Car garage with 1,296 sf finished loft. RV bay and shop. $650,000 ML93595/251378 Team Schmidt 683-6880 WINDERMERE SUNLAND Step across the threshold and back in time to the days of opulence. This beautifully restored Victorian will take you back to days when rooms were ample and homes were comfortable places to gather. Three porches, seven gardens, a dining room big enough to serve 15, a two-story shop with water view. . . just begin the list of amenities. Priced below value. $385,000. ML250558/42161 Doc Reiss 457-0456 WINDERMERE P.A.
PENINSULA DAILY NEWS
LAWN/YARD LAWN CARE CAREROOFING
Lund Fencing
BBob’s ob’s TTractor ractor Service Ser vice
Specializing in; Custom Cedar, Vinyl Chain Link
Specializing in: Field Mowing, Rototilling, Landscaping. Lawn Prep, Back Hoe, Drain Works, etc., Post Holes, Box Scraper, Small Dump Truck, Small Tree and Shrub Removal
Chad Lund
LARRYHM016J8
Roofing & Remodeling "Lindquist Roofing"
TIME TO PRUNE Clean-up Fruit Trees All Shrubbery
All phases of construction
Bob 452-4820 "There's No Substitute for Experience"
Call now for your appt. 17 yrs. experience
KITCHENS/BATHS/DOORS
CONSTRUCTION
Carruthers Construction
AIR DUCT CLEANING
HANDYMAN
Professional, Honest & Reliable FREE ESTIMATES
360-460-0147
PORT LUDLOW KIT & CABOODLE PET & HOUSE SITTING
WANTED: Wind Damaged
& Leaky Roofs ARLAND GROOFING
75289698
Quality roofing at a reasonable price References
457-5186
360-452-2054 Kenneth Reandeau, Inc.
360-452-8435 or 1-800-826-7714
EXCAVATING Driveway - Drainage Systems - Clearing Brushing - Demolition - Site Prep - Park Outs Rock Walls - Concrete Removal - Stump & Brush Removal - Brush Hog - Field Mowing Crushed Rock - Fill Dirt
LANDSCAPING Design & Installation Maintenance & Renovation - Hard Scapes Custom Rockeries - Stone Terraces - Paths Patios - Irrigation - Lawn Restoration Top Soil - Bark - Compost - Landscape Boulders
025073138
Call NOW To Advertise
Contr#KENNER1951P8 72289323
We buy, sell, trade and consign appliances.
• Fences • Decks • Small Jobs ok • Quick, Reliable
360-775-6678 • 360-452-9684 COLUMC*955KD
PPROFESSIONAL RScanning O F E SPriSntiIngOServices NAL S c a n n i n g & Printing Se r v i c e s
Contractors Lic. GARLACM*044ND
EXCAVATING/LANDSCAPING
Washers • Dryers • Refrigerators • Ranges
Full 6 Month Warranty
• Doors/Windows • Concrete Work • Drywall Repair
670.1122
Small Jobs A Specialty
Reconditioned Appliances • Large Selection
Quality Work
PRINTING
ROOFING
360-531-1241
YOUR LOCAL FULL-SERVICE DEALER & PARTS SOURCE Please call or visit our showroom for lowest prices on:
Columbus Construction
PET & HOUSE SITTING
Daily, Weekly, Monthly, Overnight Licensed • Insured • Bonded Specialized in pets with health concerns
914 S. Eunice St. PA • 457-9875
Port Angeles Sequim
ANYTIH5904MN
0B5102607
M-F 8-5 Sat. 10-3
360
Glen Spear Owner Lic#DONERRH943NA
• Tile • Kitchen & Bath • Custom Woodwork • Water Damage/Rot
Jeff Hudson
Licensed & Insured #CARRUC*907KJ
APPLIANCES
Interior/Exterior Home Repairs Masonry Carpentry I DO ODD JOBS
If it’s not right, it’s not Done Right! FREE Estimates
REPAIR/REMODEL
ANYTIME HANDYMAN SERVICES
• Kitchen and Bath Updates and Remodels • Additions, Garages, Framing and Siding • Finish Carpentry, Cabinets, Trim, Doors, etc. • Tile: Floors, Showers, Walls and Countertops • Concrete Driveways, Walks and Retaining Walls • Drywall: New, Repair, Painting and Texture • Creative Help with Design and Layout • Small Jobs, OK
Decks & Fences Windows & Doors Concrete Roofs
D DESIGN ESIGN S SCANNING CANNING FFILM ILM O OUTPUT UTPUT P PRINTING RINTING P PACKAGING ACKAGING M MEMENTOS EMENTOS
86313195
(360) 477-1805 Every Home Needs “A Finished Touch�
0B5104227
Reg#FINIST*932D0
“From Concrete to Cabinets�
Remodels Appliances Handicap Access Painting
Free Estimates • Senior Discounts Licensed Bonded • Insured
78289849
085093109
!!!
Licensed • Insured
360-460-6176
075090631
(360) 477-4374 (360) 461-2788
Done Right Home Repair
Interior/Exterior Painting & Pressure Washing
FALL/WINTER
LIC #LINDQC1023KR
No Job Too Small
From Curb To Roof
035075402
Lic#BOBDADT966K5
Larry Muckley
(360) 683-7655 (360) 670-9274
with
085091454
3360-670-1350 60-670-1350
Grounds Maintenance Specialist • Mowing • Trimming • Pruning • Tractor Work • Landscaping • Sprinkler Installation and Repair
Callahans Landscape Maintenance
Nail it Down
91321005
+ e will We W w i l l meet m e e t or o r beat beat most m o s t estimates estimates
93313234
#LUNDFF*962K7
76289935
452-0755 775-6473
Larry’s Home Maintenance
HOME REPAIR
PAINTING
PRUNING
72289360
TRACTOR
045048457
FENCING
0B5104918
SERVICE DIRECTORY
Classified
PENINSULA DAILY NEWS
51
54
Homes
STRAIT VIEW Main living area, guest area with kitchen and bath. Wood burning fireplace, built-in sound system, bar with sink, and refrigerator, and wraparound deck. $498,800 ML117675/251737 Tom Cantwell 683-6880 WINDERMERE SUNLAND SUNLAND VIEW CONDO 3 Br., 1.75 bath condo. Heat pump and wood burning fireplace, unobstructed water view and wraparound deck. Enjoy SunLand amenities. $175,000. ML252064/165857 Team Topper 683-6880 WINDERMERE SUNLAND THE PRICE IS RIGHT This clean and neat 2 Br. single wide manufactured home on .57 acres is a sweet deal. Appliances are included and the lot is landscaped with tall evergreens and easy access to town. $98,000. ML252309. Kathy Brown 417-2785 COLDWELL BANKER UPTOWN REALTY WANT TO BUY home in Monterra community. 681-8536. Well maintained duplex 2 Br., 2 baths each, carport and great storage space. Units have been well maintained and have had good rental history. $214,900. ML251403 Jennifer Holcomb 457-0456 WINDERMERE P.A. Well maintained Manufactured home on .45 acres. Fully fenced yard, sunroom off back porch, 2 car detached garage close to stored and bus line. New roof on both garage and home. $150,000. ML250465/34906 Jennifer Felton 457-0456 WINDERMERE P.A.
PENINSULA DAILY NEWS Commercial Printing Services 417-3520 DESIRABLE MERRILL ESTATES 2 ready to build, 1+ acre parcels with beautiful mountain views. Established, upscale neighborhood with homes on acreage and green belt areas. $129,000 each. Alan Barnard 461-2153 IN YOUR FACE MTN VIEW Gently rolling 5-acre parcel in settled neighborhood of nicer homes. Electric and phone at road; needs septic and well. Fantastic, inyour-face mountain view and possibly some “peek-a-boo” views of the Strait from southmost part of property. Fully fenced for larger animals (trails nearby). Possible owner financing with substantial down and good credit. $125,000. ML251287. Carolyn and Robert Dodds 683-4844 Windermere Real Estate Sequim East
Lots/ Acreage
‘G’ IS FOR GOBBLE GOBBLE Now that I have your attention, let me introduce you to this private, beautifully treed 2.45 acres in a very, very quiet area just minutes from downtown. Drive right into the middle of the parcel! Phone and power in at the road. Work off your holiday feast on the walking trail surrounding property. $64,500. ML251010. Jace Schmitz 360-452-1210 JACE The Real Estate Company INDUSTRIAL ZONING Level 22+ acre parcel with mountain view located on the west side of Port Angeles. Close proximity to the airport, Hwy 101 and the truck route. Sellers will consider owner financing or a lease option. 2 Phase power to the property. For more photo’s and information, please visit $650,000. ML241915. Kelly Johnson 457-0456 WINDERMERE P.A. PRIVATE SETTING High bluff waterfront. Great privacy and unobstructed views of the Strait. 330’ of frontage of high bank. Water share available through Crescent Water Assoc. ML251816. $172,000. Paul Beck 457-0456 WINDERMERE P.A. RARE FIND Beautiful acreage in Agnew, with breath taking views. Bring your house plans. In Sequim School District, wonderful community. $199,000. ML56475/250847 Kim Bower 683-6880 WINDERMERE SUNLAND SELLER TERMS Nice private parcel between Port Angeles and Sequim. 1.46 acres with PUD water and power in at the road. Manufactured homes OK. $55,000. ML250880. Harriet Reyenga 457-0456 WINDERMERE P.A.
54
62
Lots/ Acreage
Lake Sutherland 3+ acres with beach rights with dock, Hwy 101 frontage. electrical close by. Subdividable, zoned R1. 360-460-4589. SEQUIM LAND WANTED Must support 2 horses. 505-281-1591. TRULY UNIQUE This 35 acres property was approved for almost 40 lots at one time. With gentle topography, stunning water views, city utilities on two sides, and zoning for several lots per acre, this could represent the single best investment/development property on the market in Sequim at this time! $79,950. ML252353 Brody Broker 360-477-9665 JACE The Real Estate Company. Chuck Murphy and Lori Tracey 683-4844 Windermere Real Estate Sequim East
Apartments Unfurnished
CENTRAL P.A. Clean, quiet, 2 Br. in well managed complex. Excellent ref req. $700. 452-3540. P.A.: 1 Br apt, no pets/ smoking. $600 incl. basic utilities, W/D. 565-8039 P.A.: 2 Br., W/D, no pets/smoke. $675, 1st, last, dep. Available Dec. 417-5137. P.A.: Lg. 3 Br., 2 ba, 1,800 sf luxury apt. $900, dep. Section 8 qualified. 452-1010. P.A.: Quiet and clean. Water view. 1 Br. $575. 206-200-7244 P.A.: Really large 2 Br., 1 ba., $625, 1st, last. No pets. 452-1234.
63
Duplexes
P.A.: Clean 2 Br., garage. $725 month, deposit. 452-1016. SEQUIM: 2 Br., 1 ba. $725, dep and credit check 360-385-5857
64
Houses
62
Apartments Unfurnished
2 Br., 2 bath. Clean, great kitchen w/mtn view in P.A. W/D. No smoking/pets. Ref req. $800. 457-1392.
JAMES & ASSOCIATES INC. Property Mgmt.
360-417-2810
More Properties at
WHY PAY SHIPPING ON INTERNET PURCHASES? SHOP LOCAL
BIG, apts. $625-650, Near WM, new carpet. 417-6638.
66
Houses
CASH NOW $ Need to rent pvt, RV site w/all hook-ups. New RV. 670-6265.
Clean, furnished 1 Br. trailer with tip out, near beach, util. incl. $650. 928-3006.
RV SPACES: $375 mo., incl. W/S/G, WiFi, Cable. 461-6672.
EAST P.A.: 3 Br., 2 bath, 5 acres, mtn./ water view. Horses ? $1,200. 477-0747. EAST P.A.: Small 2 Br. mobile. $500. 457-9844/460-4968
68
Commercial Space
PROPERTIES BY LANDMARK 452-1326
P.A.: 3 Br., 2 bath, garage, nice area, $950. 452-1395. P.A.: 4 Br., 1 bath. Remodeled. $895, 1st, last. 452-1234. P.A.: By college, view, 3 Br., 2 ba. $1,150, lease. 457-4966. P.A.: Cute 1 Br. nice area, recently remodeled, no smoke, small pet ok w/dep. $675. 452-4933.
P.A.: Lovely historic home, fully remodeled, immaculate, 3 Br., 2 ba. $1,100 mo. 417-9776 P.A.: Newer 3 bd., 3 bath. Neighborhood, location, garage, yard, low utilities. No smoking/pets. $950 mo. 452-9458. P.A.: Water view 3 Br., 2 bath, 2 car garage. $1150/mo. 452-1016 Properties by Landmark. portangeleslandmark.com WEST P.A.: 4 Br, 2 ba, no smoking. $1,000, $1,000 sec. 417-0153
65
Share Rentals/ Rooms
CARLSBORG: 1 room male. $300, internet, W/D. 206-227-9738. SEQ: 2 Br., 1 bath, living room, kitchen. $500. 683-2017. 110 Green Briar Ln, off Priest Ln.
72
Furniture
COFFEE TABLES: 2 matching, 1 large, $50/obo and 1 small, $40/obo. 681-4429 or 417-7685. DINING TABLE: With 4 chairs, blonde finish nice set. $150/ obo. 681-4429 or 417-7685. ENTERTAINMENT CENTER Pine armoire style. Priced reduced. $75. 808-1767. MISC: Twin electric bed, $200. 2 piece armoire, $100. 360-683-4401.
P.A.: 3 Br. + office, views, 1.5 ba, wood fireplace, new carpet, deck, garage, great views. $995. 360-775-7129 360-452-2758
SEQUIM: Lg. unfurnished room. $350 incl. util. 457-6779.
peninsula dailynews.com
Spaces RV/ Mobile
CENTRAL P.A.: 2 Br., 1 ba, 606 S. Laurel, references required. $700. 457-6600.
P.A.: Furnished 2 or 3 Br. Weekly or monthly. 360-417-1277.
HOUSES IN P.A. 1 br 1 ba......$500 1 br 1 ba......$525 2 br 1 ba......$650 2 br 2 ba......$800 3 br 2 ba......$950 3 br 1.5 ba..$1100 HOUSES IN SEQUIM 2 br 2 ba......$925 2+ br 2 ba....$950 3 br 2 ba....$1100 3 br 2 ba....$1250 61 Apartments Furnished 62 Apartments Unfurnished 63 Duplexes 64 Houses 65 Share Rental/Rooms 66 Spaces RV/Mobile 67 Vacation 68 Commercial Space
64
MONDAY, NOVEMBER 29, 2010
Rocker/Recliners Almost new, 2 matching, gray-blue. $300 ea. 681-2282. 71 72 73 74 75 76 77 78 79
Appliances Furniture General Merchandise Home Electronics Musical Sporting Goods Bargain Box Garage Sales Wanted to Buy
72
Furniture
BED: Adj electric extra long twin bed w/memory foam mattress and wireless remote (programmable preset positions and vibramassage). Great cond/steel mechanism by Motion Bedding. Owner manuals. $600. 681-8967. BEDROOM SET Solid oak. Large chest, $200. Dresser with mirror, $200. King headboard, $100. 2 pier cabinets with mirror, $300. Take all, $700. Must see to appreciate. 360-565-6038 BEDROOM: Black lacquer dresser, armoire, king headboard, mirror. $200/ obo. 797-7311 ENTERTAINMENT CENTER Large, very sturdy, light colored oak. Plenty of room for a large television with two big storage drawers underneath, plus a side cabinet with three shelves and glass-front door. $175/obo. 360-775-8746
SOFA: Micro fiber suede sectional with chaise lounge and ottoman, 68x100x 132, 5 matching pillows, sage green color, stain guard, bought new $2,600, sell for $800. Must see to appreciate. 461-4622 SOFA: Mini sectional, red, less than a year old. $300/obo. 417-2047
73
73
C7
General Merchandise
CUSTOM SHED Beautiful 8x8 custom built shed. Asking for only materials no time or labor. $800 firm, you haul. Call to explain why. 457-2780 DRESSES: 3 nice prom dresses size small, like new worn once, call for description. $30 each. 452-9693 or 360-417-3504 LEONARD COHEN CONCERT TICKET Tues., Nov. 30 Save On Center Victoria. $98. Call Diane 460-2546 MISC: Singer featherweight 221 sewing machine with case, excellent condition, $400. Exercise system, Weider Flex CTX, $125. Bike, Turner, recumbent, $500. 683-0146. MOVING BOXES Used, cardboard, different sizes, incl. wardrobe, good condition. Blue Mountain Road. $200 all. 360-928-3467 SEASONED FIREWOOD $185 cord. 360-670-1163
General Merchandise
BATH CHAIR: Goes down into water, lifts up out of water. $650. 360-681-0942.
Sunvision tanning bed model K-24SH, excellent shape. $500. 461-0721.
BBQ GRILL: Large propane, with side burner, works good. $20. 681-4429 eves or 417-7685 weekdays.
TABLE SAW. JET JWTS-10, 2 fences, router wing w/Bosch insert, blade guard, dust containment box, 2 inserts. $375.00. 681-2524
CASH FOR: Antiques and collectibles. 360-928-9563
Christmas quilts for sale. Christmas and everyday quilts, queen/king size. $300 each. Homemade, hand quilted, machine washable. Phone 683-6901. COMFORTER SET Barney twin, with sheets, good shape. $15. 452-9693, eves. CREDIT CARD MACHINE Like new. Paid $600. Asking $400. 681-3838
VACUUM: Rainbow SE plus accessories and rug shampooer. $450. 670-6230.
WANTED! Your Consignments!!! Artisan Creative Consignment is wanting your handcrafted Art, household and clothing!!! Reasonable consignment! Call for details! Michele at 360-461-4799, Heather at 360-775-4283, or business line at 360-681-7655
PENINSULA DAILY NEWS
REMODELING
WINDOW/CARPET CLEANING Let the Sunshine in! LET US CLEAN YOUR... WINDOWS • CARPETS • GUTTERS plus DEBRIS HAULING RS SCHMIDT ENTERPRISES Insured - GUTTEA*95ONS - Bonded
Call NOW To Advertise
8C313094
452-3480
Call Bryan or Mindy
461-4609
360 Lic#buenavs90818
#JKDIRKD942NG
Quality Home Renovation & Repair Free Estimates and Consultation Kitchens • Bathrooms • Decks • Cedar Fencing Interior Remodel • Interior & Exterior Painting Framing to Finish Woodwork • Small Jobs Welcome
360-440-2856 Licensed • Bonded - Cont#SUTTEC99401
Asbestos Call NOW To Advertise 360-452-8435 or 1-800-826-7714
Specializing in Trees
• View Trimming • Storm Damage • Total Cleanup including small tree & brush cleanup • Bluff Work • Ornamental Pruning
24 HR Emergency Hazardous Tree Removal Don’t Wait Until it’s Too Late
Window Washing
(360) 460-0518
3Licensed 6 0and. Bonded 452 .7938 Contr. #ESPAI*122BJ
Established 1997 Licensed • Bonded • Insured Cont #ANTHOS*938K5
One Call Does It All!
452-9995
TILE INSTALLATION DAVE PETERSON TILE & STONEsince 1984 360-681-2133 New & Remodel Kitchens, Baths, Fireplaces, Shower Pan Expert, Ext. Walkways Granite, Ceramic Tile, Slate & Travertine
Call NOW To Advertise
FREE ESTIMATES Local References
Lic# DavePPT943DW
TREE SERVICE
0B5103483
360-452-8435 SE EMM P PER ER F I T R E EE E SE ER RV VIC IC E or Licensed – Bonded – Insured Free Quotes! 1-800-826-7714 (3 60)461 -1 89 9 – OR –
river1966@msn.com Lic# DELUNE*933QT
0A5100336
O r a n g e Pe e l - K n o c k Dow n - Ha n d Tr ow e l
360
Anthony’s Services • Selected Tree Removal • Topping • High Climbers • Hazard Tree Removal • Free Estimates • Brush Chipping
Inspections - Testing Surveys
0B5103485
Dry Wall Repair
0B5103448
015068170
Call NOW To Advertise 360-452-8435 or 1-800-826-7714
jkdirworks@wavecable.com
0A5100969
Peninsula Since 1988
Interior Painting 360 385-6663
JOHN KIMMEL-OWNER LIC
C o m m ercial & R esid en tial QualityLandscapes@cablespeed.com Bonded and Insured CONTR#QUALIL*123DG
Painting The
• Small Excavating • Brush Mower on Small Rubber Track Excavator • Utility Install & Lot Clearing • Spring & Storm Clean-up •Post Holes & Field Mowing • John Deere Services
ASBESTOS
TREE SERVICE GUTTERS CLEANED
Lawn Care • Pruning • Chipping Fertilizing & Spray Services Hydroseeding Irrigation - Install & Repair
Licensed
Window Washing
360/460•9824
Sutter Craft
PAINTING
RENOVATION & MAINTENANCE
457-6582 (360) 808-0439 (360)
JK DIRTWORKS INC.
945036615
Pruning Artistry Oriental Style A r b o r i s t R i c h a rd 360-683-8328
LANDSCAPING
Moss Prevention
095096373
(360) 683-8332 Locally Operated for 24 years Contractor # GEORGED098NR
Any House Any Size
DIRT WORK
RENOVATION/REPAIR
035075404
9C5066307
Family operated and serving the entire Olympic Peninsula since 1956
Roof & Gutter Cleaning
360.477.1191
PRUNING
Septic Systems • Underground Utilities Roads • Driveways • Rock Retaining Walls Land Clearing • Building Site Prep Building Demolitions
Gutter Cleaning & Services
Jason Tickner
Lic# LOVESHR940CB
Residential and Commercial Excavating and General Contracting
Pressure Washing
CLEARVS9010W
Licensed • Bonded • Insured
CONSTRUCTION, INC.
FOX
0B5104177
360-683-7198 360-461-1148
Clearview Services 40’ Bucket Truck
0A5101705
GEORGE E. DICKINSON
Holiday Special 10% off all labor thru 12/31/10 FREE ESTIMATES
RESTORATION
085092331
EXCAVATING/SEPTIC
GUTTER
-Painting -Limbing/Pruning -Free Estimates -Yard/Debris Removal -View Enhancement -Gutter Cleaning -Moss Removal -Windfall Cleanup -Light Replacement
Tile Work • Kitchens Bathrooms Drywall & Framing Decks • Fences Windows • Ramps
0B5102768
360-452-8435 or 1-800-826-7714
HOME SERVICES
0B5104920
MONDAY, NOVEMBER 29, 2010
ACROSS 1 Toad feature 5 Cravings 10 W.W. Jacobs short story “The Monkey’s __” 13 Etonic competitor 14 Hollandaise and barbecue 16 Genetic molecule: Abbr. 17 Music genre that evolved in the ’50s 19 “__ complicated” 20 Evil smile 21 Pac-10 hoops powerhouse 22 Cambridge sch. 23 Letter before kappa 26 Tranquil 28 How the wheels on the bus go 32 Possess 33 Italian “a” 34 Tide creations 37 Formally relinquish 39 Time off, briefly, and this puzzle’s theme 42 Winter fall 43 Hägar the Horrible’s dog 45 Zippy start? 46 Well-armed org. 47 “Old” nickname for Zachary Taylor 52 Nonsense 54 The ten in “hang ten” 55 Batter’s stat 56 Power co. product 58 Freeze, as a plane’s wings 62 + molecule, e.g. 63 Complain hysterically 66 Work unit 67 Like the night in a classic Van Gogh work 68 All done 69 Knox and McHenry: Abbr. 70 “Do the Right Thing” actor Davis 71 Wimpy DOWN
By DAVID OUELLET HOW TO PLAY: All the words listed below appear in the puzzle –– horizontally, vertically, diagonally, even backward. Find them and CIRCLE THEIR LETTERS ONLY. DO NOT CIRCLE THE WORD. The leftover letters spell the Wonderword. ‘BOARDWALK EMPIRE’ (TV SERIES)
H C O N E C N E R E T H E M E By Jeff Chen
11/29/10
1 Serious conflicts 2 Cosmetic caller 3 Paddy grain 4 Adopt, as a puppy 5 “Top Gun” org. 6 “Groovy!” 7 Hindu religious instructor 8 Chevy Volt or Ford Fusion 9 Do business with 10 Temperamental diva, e.g. 11 Shenanigan 12 Trash 15 First-rate, in Rugby 18 Yankee with 613 career homers 24 Bull: Pref. 25 Oscar winner Paquin 27 Nephew of Cain 28 Big birds of lore 29 Wilson of “Marley & Me” 30 Subordinates 31 “Who’s the Boss?” star Tony 35 Manor master 36 Oscillate 38 Sock ending 40 Car scar 41 Overhaul, as a
E E F R E Eand Tuesdays A D SS R F Monday
H E S E C R O C S L K E O I O
O N W O H S I H I G H L O G R
M A I N E T H A I T E A R G R
P D W G N R S E S B Y E U E U
S A W A H L B E R G I D L L P
O P L E L T A U E I S T E T T
N T K C I C C V S G F S I O I
A N J O O G A L I C E F O O O
I L E T O H H P U S E T S B N
C R E T S B O M O B H M O V E
Join us on Facebook
U E L A G E L L I N S H I R E
L U C K Y K C U N N E T T A P
11/29
Adapt, Al Capone, Alcohol, Atlantic, Backrooms, Book, Bootlegging, Boss, Buscemi, City, Corruption, Dealer, Elias, Enoch, Gangsters, High, Hire, Hotel, Illegal, Lavish, Luciano, Lucky, Main, Mark, Mobster, Move, Nightclubs, Nucky, Patten, Piers, Poor, Prohibition, Protegee, Rule, Scorcese, Sheriffs, Show, Terence, Theme, Thompson, Wahlberg, Weigh Yesterday’s Answer: Party by Mike Argirion and Jeff Knurek
Unscramble these four Jumbles, one letter to each square, to form four ordinary words.
KLANE (c)2010 Tribune Media Services, Inc.
Web site 44 Workers with an ear for music? 48 Italian ice cream 49 “Laughing” critters 50 Longtime Nevada senator Harry 51 Money for taxes and insurance may be held in it 52 Lawyer’s filing 53 NASA “Stop!” 57 NBA’s Shaq and
JACKET: Columbia, girls 6/6X, good condition. $15. 457-5299 JACKET: North Face, insulated gortex, women’s large, like new. $75. 683-5284. “LaFuma” Folding deck chair/reciner. New $150. Sell $50. 683-2743 MATTRESS: Twin, framed, very new. 10”x 39”73”. $135. 928-0167 MIRRORS: RV extension, fits ‘99 F250. $30. 452-7909. MISC: Bar stool, $25/obo. Desk chair, $15/obo. 928-3464. MISC: Camp Chef, 3 burner range, $50. Tent, large, used once, $50. 683-2743 MISC: Crib, $60. Table with 6 chairs, $70. 417-3825. MISC: Overstuffed love seat and chair, blue/white. $15ea./ $25 both. 477-3603. PANTS: New Solstice ski pant, size L, paid $129, sell for $60. 457-5002 PORTA-POTTY: New unused, for boat or camping. $25. 504-2401 Queen mattress, box spring, frame & bedding. $100. 360-681-4471 RECEIVER: Denon AV surround receiver. $100/obo. 452-7179. RECLINE: Brown fabric La-z-Boy, well used. $25. 477-3603. RIMS: (4) 16” stock 8 lug w/caps, taken off when new. $125. 683-7841 SEWING MACHINE Antique, domestic rotary and table. $50. 477-3603 SKIIS: Fischer SC4, w/Tyrolia 290 bindings, Lange boots. $100. 683-9882. SKIS: Rossignol cros country with poles and boots. $65. 683-0146 SNOW CHAINS: H/D sizes 245/75-17-5, 165/75-16, and others. $35. 460-4488.
Mail to: Peninsula Daily News PO Box 1330 Port Angeles,WA 98362
STAR TREK: VHS. 10 TV shows, 3 movies, $10. 683-0146. STEREO RECEIVER Powerful, “technic”. $50. 452-9685. SUMP PUMP: .25 hp, electric w/20’ hose. $35. 582-1280. TABLE SAW: Dado adjustable blade w/Craftsman saw. $45. 457-4971. TELEPHONE RADIO 1956 Country Belle $30. 928-9005. TIRES: (2) 7x35 R14 studded on wheels. $70. 360-379-4134. TIRES: (2) 7x35 R15 studded on wheels. $70. 360-379-4134. TIRES: (2) Snow, 175SR14. $30. 417-1593 TIRES: (4) Snow on 6m 5 hole rims. P205/75R15. $80/obo. 457-5935. TIRES: (4) Snow, F7814. $40. 417-1593 TIRES: (4) Studded 215/60R16. $100. 477-4195 TIRES: Studded P 175/70R13, on 5-lug rims. $100. 775-6865 TRUNK: 100 Years old, original leather straps, hardware. $100. 683-7841. TV: Sharp, 26”. $30. 460-6213 TV: Sony 13” CRT, very good cond. $35. 681-8592 URINAL: Men’s white vitreous china. $75. 683-8032 Vintage Typewriter. 1936/37 Underwood manual typewriter $20. 928-9005. WALKER/LEG REST 4-wheel and handle. $20/obo. 928-3464. WASH STAND: Reprodution. Oak, mirror, pitcher and bowl. $150/obo. 681-4244 WHEELS: (4) Alum, for 15” tires, five hole fit 80’s Chev S10. $25 ea. 457-5092. WOOD HOOP. 3’ 2” Diameter, wrought iron. $40. 477-3603. WOOD STOVE: Minnesota barrel for shop. $25. 457-4971
Bring your ads to: Peninsula Daily News 305 West 1st St., PA 510 S. 5th Ave. #2, Sequim 1939 E. Sims Way, PT
11/27/10
Yao, e.g. 59 A gutter is often under it 60 Eye part containing the iris 61 Exec’s extra 64 “Taking Heat” memoirist Fleischer 65 PBS science guy Bill Musical
or FAX to: (360)417-3507 Email: classified@peninsuladailynews.com
NO PHONE CALLS
79
CUNBOE
GITSAM Now arrange the circled letters to form the surprise answer, as suggested by the above cartoon.
Ans: Yesterday’s
Wanted To Buy
WANTED: 22 cal. rifle. Call 683-1413
A (Answers tomorrow) EVENT FINISH BEDECK Jumbles: LADLE Answer: What barbed wire is usually used for — DE-FENCE
84
Horses/ Tack
CELLO: 3/4 size Kohr, bow, soft case, stand good condition. $350. 457-3666.
MARE: 6 yr old quarter horse mare. Been there, done that! Performance, rodeo, equestrian team, been hauled everywhere. Flashy. Very sweet, no vices. $6,000 negotiable to good home. 360-477-1536 msg.
Give the gift of music. Guitar instruction by Brian Douglas. 360-531-3468
85
VIOLIN: 3/4, nice shape. $150. 452-6439
76
Sporting Goods
GENERATOR: Honda 1,000 watt. $450. 360-385-7728 GUN: Custom Arisaka 300 Savage sporter. $300. 452-2029. GUNS: Colt Python 357 mag., $1,000. Smith & Wesson model 66, 357 mag., $600. Marlin model 39, $450. 683-9899. GUNS: Ruger Red Hawk, 41 mag, stainless, $600. Beretta Cougar 40 S&W, $600. Ruger P95, 9mm, $400. Ask for Marty, 360-670-8918 S&W M&P AR15 M4 .223 flat-top rec. with carry handle site 16” ch barrel, ch gas key, carrier, 6 pos stock, bayo lug, mil spec comp, case, 30 rd mag, fact warr new in box. $970. 683-7716
78A
Garage Sales Central P.A.
VENDORS WANTED: For Dec. 4 Flea Market/Arts & Crafts, Campfire bldg. 928-0213, 8-10 a.m.
78B
Garage Sales Westside P.A.
AUCTION: ANGELES MINI STORAGE, 12 noon on 12/1 at 919 W. Lauridsen, P.A. Unit 19. 452-2400 to verify.
79
Wanted To Buy
1ST AT BUYING FIREARMS Cash for the Holidays. Old or new, rifles, shotguns, and pistols. 1 or whole collection. Please call, I will bring cash today. WA State Firearms Transfer paperwork available. 681-4218. BOOKS WANTED! We love books, we’ll buy yours. 457-9789
5A246724
D A For items E $200 and under S E D R A E F E E R E F FR
• 2 Ads Per Week • No Pets, Livestock, • 3 Lines Garage Sales • Private Party Only or Firewood
T S M O O R K C A B E R P N C
Solution: 9 letters
THAT SCRAMBLED WORD GAME
ACCORDION: 19” keyboard, 120 base, electric. Excellent condition. Buy a $3,000 accordion for $500. 683-7375. CHEST WADERS Hodgeman, boot on type, size 11, never worn. $90. 452-7909 CHRISTMAS DISHES Waechtersbach. $165. 379-0962. CRIB MATTRESS Lightly used, in good shape, bedding set. $30. 461-4846. CROCK POT: 4 qt, removable ceramic, new. $10. 457-9498. DESK: Wood, good shape! Came from Ft. Lewis. $30/obo. 461-4846. DINETTE SET: Maple, oval w/4 chairs. $40. 928-1148 DOLLS: Barbie ‘95, ‘96 Holiday series, mint, in box. $25 ea. 457-5935 DRILL PRESS: Shop Fox, .5” bench top model, like new. $150. 452-7179. ENTERTAINMENT CENTER Pine armoire style. $75. 808-1767. FISH TANK: Saltwater, 80 gal., pump, lights, stand, extras. $100. 477-1264. FREE: 42” Toshiba Theatre view HD TV. 452-7179, 460-2601 FREEZER: 21 cf Hotpoint upright. $75. Owner downsizing. 461-9287 FREEZER: Chest, 3 yr old., 7.5 cf, perfect condition. $60/obo. 360-457-9773 FURNACE: Armstrong, electric, new. $175. 683-8032. GAS CANS: (2) jerry cans. $30 ea. 460-6796 GOLF CLUBS: $5 ea. 360-452-1277 GPS: Garmin (Nuvi 260W) Like new. $75. 360-457-5079 HOT TUB COVER Approx 85” square. $50. 457 3917. HUMIDIFIER: Kenmore, whole house, like new. $35. 452-1277 Internet Adapter Linksys USB. $30. 460-6796 TV: Emerson, 27”. $35. 460-6213.
S R E I P S R E T S G N A G Y
© 2010 Universal Uclick
Friday’s Puzzle Solved
75
AQUARIUM: 20 Gal, w/pump/filter/hood/li ght, no heater. $30. 477-3603 AQUARIUM: 20 gal. w/pump and some accessories. $20. 928-1148 BABY SWING: FisherPrice cradle swing. $30. 461-4846. BAR STOOLS: (4) Oak, with upolst. back/seat. $100. 582-9222 BICYCLE CARRIER For RV ladder, used 1x. $35. 683-9882. BICYCLE RACK Revolver style 2 bike, for 2” receiver hitch. $200. 457-5002. BICYCLE: Girls 20” Malibu Stardom, red with white stripes. $35. 360-224-7800. BICYCLE: Girls 26” mountain, 21 speed, Motiv. $40. 477-3603 BICYCLE: Mens 26 road, Schwinn Varsity 14 sp. Needs seat/ post. $20. 477-3603. BICYCLE: Raliegh Chill Mt Bike, nice shape, 18 speed. $50. 457-5002. BIRD CAGE: 15”x20” x23”, white wire, w/plastic bottom. $10. 477-3603. BOOKS: (7) Harry Potter hardback, full set. $69. 360-224-7800 BOOKS: Current novels, known authors. $3 ea or all for $100. 565-1062 BOOTS: Alpina Xcountry ski womens 9 1/2, mens 9 1/2. $15 ea. 681-7568. BOOTS: New, LL Bean, waterproof leather, men’s 9. $40. 683-5284 BUFFER: Craftsman 9”, 2400 random orbits, new in box. $20. 457-5002. CASSETTE STEREO (5) Quality home units. $20 ea. 452-9685. CHANDELIER: Or entry light, large glass. $50. 582-1280. CHANGING TABLE Lt. brown 2 shelf, no pad. $20. 477-3603. FREE: Hot tub, you haul. (360) 452-6349.
PENINSULA DAILY NEWS
Costco shed parts, recycle for cash. 417-5336 evenings. WANTED: Surveyors staff compass. 457-6236
81 82 83 84 85
Food/Produce Pets Farm Animals Horses/Tack Farm Equipment
82
Pets
Farm Equipment
BOX SCRAPER Rankin 72”, blade and 6 shanks, for 3 point hitch. Model BBG72J. Never used. $600. 360-301-2690
BEAUTIFUL LAB PUPPIES Vet checked, 1st shots. Females, $250. Males, $200. 417-0808 CAGES: (2) large wire cages for birds, rabbits or ? $10 each. You haul or we will haul with gas money included. 681-4429 eves or 417-7685 weekdays. Chihuahua puppies. 3 very cute, happy, friendly, healthy purebred Chihuahua puppies. 2 females 1 male. 7 weeks old. $250-400 360-670-3906 DACHSHUND Mini puppies. 8 weeks old. $300 each. 360-796-3290 FISH TANK: Saltwater, 80 gal., pump, lights, stand everything included. $100. 477-1264 FREE: Chinchilla to loving, approved home. Healthy, not as much time as he deserves. All accessories. 640-0355. FREE: Kittens. (2) 4 mo. old brothers, one long hair, one short, black, very friendly, abandoned by neighbors. Please help! 683-0050. LHASA APSO: Puppies. Ready Dec. 9. Tuxedo and Parties. 3 girls, 3 boys. $450. 477-8349 PUPPY: Chihuahua female, to loving home. $200. 808-1242 TOY POODLES: 8 wk. old black male, 1 6 mo female tri-color phantom. $550 ea. 477-8349
83
NEW BIBLE Jumble Books Go To:
C8
Farm Animals
CALL DUCKS: $25 each pair. 683-3914. HAY: Alf/grass. $5.00 bale. Grass, $4.00. In barn. 683-5817. Weaner pigs, nice Duroc cross, winter price $55. Also young large blue butt boar, $150/obo. 775-6552
91 Aircraft 92 Heavy Equipment/Truck 93 Marine 94 Motorcycles/Snowmobiles 95 Recreational Vehicles 96 Parts/Accessories 97 Four Wheel Drive 98 Trucks/Vans 99 Cars
92
93
Marine
ALUMALITE: Drift boat, very clean, great bottom, oars, trailer included. $3,200, make offer. Must sell due to health. 681-0717. BAYLINER: With 70 hp Evinrude. Fully equipped with EZ Loader trailer, lots of extras. $4,000. 683-4698ASTRON: ‘08 GT 185 Bowrider .
PLACE YOUR AD ONLINE With our new Classified Wizard you can see your ad before it prints! dailynews.com
93
Marine
RARE PANGA 26’ BOAT FISHERMAN’S DREAM Magic Tilt Trailer & essentials for this beautiful ride. New floor & engines overhauled. 2 bimini tops, custom boat cover, gps, radio, etc. In Sequim. $18,500/obo. 707-277-0480 SANGER: ‘76 Super Jet. Built 455 Olds, Hardin in water exhaust, seats 5, upholstery good, dog house fair, turnkey ready. $2,500/obo. 681-3838 1993 Wideglide, custom wheels, lots of extras. $15,000. 477-3670
HARLEY-DAVIDSON ‘07 Softail FLSTF FatBoy, asking $2980, 96ci twin, contact for pictures and details marshak49nk@msn. com, 253-203-6818.
HD: ‘05 Electra Glide Ultra Classic. Black cherry/black pearl, 10,850 miles. One owner, garage kept. Screamin' Eagle and Tall Boy package. never down or in rain. Excellent condition! $15,900. 360-461-4222
Classified
PENINSULA DAILY NEWS
94
Motorcycles
HARLEY: ‘05 Soft Tail Deluxe. Glacier white, vivid black, 2,000 mi. 1450 ST1 EFI, bags, chrome foot boards, sport rack, back rest, lots of chrome, much gear included garaged. $17,500. 460-0895. HD: ‘06 1200 Sportster. 7K miles, mint, extras. $7,900. 452-6677 HONDA: ‘79 CB750K. Complete bike, rusty, for parts or restoration. $400/obo. 360-457-6174 KAWASAKI: ‘09 Ninja EX250. 300 mi., bright green new helmet, visor, can email pics. 1 owner. $4,000. 477-6973.
QAUD: ‘05 POLARIS PHEONIX 200. Red, automatic, approx. 5-10 riding hours, Like new $2,300. 360-460-5982 QUAD: ‘06 Eton 150. Low hrs. good condition. Daughter’s quad. $1,800/obo. 461-7210 QUAD: ‘06 Suzuki Quad Sport Z250. Like new. $2,600 firm. 360-452-3213. RHINO: ‘09 Yamaha 700. Fuel injected. Great condition. Low miles. $9,500/obo. 417-3177
95
Recreational Vehicles
‘80 Prowler Travel Trailor. 20’. $2500. With hitch. Sleeps 5, full kitchen, full bath. Tina 360-809-0836. CAMPER: 8’. $200/ obo. 683-2426. HERE’S THE DEAL Buy my 29’ Pace Arrow with 57K miles on it, general power pack, Monroe shocks, stabilizers, hydraulic levelers, air conditioning, 16’ awning. Price $3,500 then trade on new bus for about $8,000 Ken at 928-9410.
SCOOTER: Aero Honda 80, runs well. $450. Ken at 928-9410 TRIUMPH: ‘05 Bonaville. 1,000 mi., extras. $5,500. 460-6780 URAL: ‘03 Wolfe. 1,000 mi. $3,200. 460-0895
YAMAHA: ‘03 YZ85. Runs great, son outgrown, $800. 360-457-0913 or 360-461-9054
95
Recreational Vehicles
105
Legals General
PUBLIC NOTICE TO WAVE BROADBAND CUSTOMERS In January, Wave's video rates will be adjusted to offset a small portion of the ever-increasing programming fees Wave incurs from the networks carried on our system. We work diligently to minimize these costs on behalf of our customers. Unfortunately, the cable networks have once again dramatically increased their fees. We will absorb much of the increase, and minimize the price adjustments to our video products and services. Some fees and taxes may also be adjusted at this time. Further details, including money-saving bundle options, will be included in your January bill statement. Thank you for choosing Wave Broadband. 1-866-WAVE-123 Pub: Nov. 29, 2010
MOTOR HOME: ‘98 26’ Tioga Class C. Gen., A/C, kept in garage, V10. $15,500. 457-7097. MOTOR HOME: ‘98 30’ class C, Itaska Spirit. Ford V10, 35K miles, 14’ slide, sleeps 6, alum frame, new brakes/tires, mech. perfect, serviced, ready to roll. $20,500. 452-2148. TENT TRAILER: ‘07 8’ Rockwood. Very clean. $5,000. 360-452-5512 TRAILER: ‘06 26’ Jayco. Excellent condition, extras. Reduced price. $13,000. 477-3695. TRAILER: ‘72 Sportsmaster 20’ living space and tongue. Good condition. $3,000/obo. 775-7504 TRAILER: ‘05 Tahoe Transport Toy Hauler. 24’. Good condition. 4K Onan generator. $17,000. 417-3177.
96
Parts/ Accessories
PARTING OUT: ‘89 Toyota Celica automatic. $5-$500. 683-7516
CLASSIFIED can help with all your advertising needs: Buying Selling Hiring Trading Call today! 360-452-8435 1-800-826-7714 dailynews.com
102
Legals City of P.A.
96
Parts/ Accessories
TIRES/WHEELS: (4) Michelin all season (snow/mud) low miles, one season, 225/60/18, Dodge Charger wheels, 18” caps, lug nuts, polished. $1,000 for all, will separate. 683-7789
97
4 Wheel Drive
CHEV: ‘97 1/2 ton extended cab, 3 doors, short bed, 80K mi. $5,000. 406-381-9362 CHEV: ‘02 Club Cab. Long bed. 4WD. Loaded. 44,000 mi., $15,500. 452-8713. CHEV: ‘70 3/4 Ton. $850. 360-434-4056. CHEV: ‘86 Suburban. Good condition. 3rd seat, extra full set wheels. Nice white paint exterior, tan interior. $2,500/ obo. 360-374-6409. CHEV: ‘88 S-10 4x4. As is. $1,000. 457-9292
97
4 Wheel Drive
FORD: ‘88 F250 111K mi., 4x4. $3,000/obo. 808-5605 TOYOTA: ‘96 4-Runner, SR5, loa-ded, gold and wood package, sunroof, Pioneer sound, 12disc changer, 154k miles, $7,000/obo. 360-417-0223
98
Pickups/Vans
CHEV: ‘89 1/2 ton. ‘350’ V8, auto, nice. $2,000. 681-7632. CHEV: ‘38 Pickup. All original, garaged, needs rear end. $15,000. Only serious buyers please. 457-3990, 775-1139 CHEV: ‘47 pickup. 5 window, 80% restored. Illness forces sale. $7,000/obo. 457-7097 CHEV: ‘84 S10 pickup. Excel. rebuilt motor. Good body. Needs paint job. $1,845. 360-6835682, 541-980-5210.
98
Pickups/Vans
FORD: ‘95 Windstar. 7 pass, excellent, 127K. $2,400. 681-7418
DODGE: ‘02 Ram 1500. 85K miles, lifted, canopy, 5.9 V8, new tires. $12,000. 477-5556 FORD: ‘05 F-350 Lariat. 4x4 6.0 diesel, leather, LB, crew cab, fully loaded, great cond. $23,000. Todd 461-9566
FORD: ‘06 Expedition XLT. This expedition is in nearly new condition and has only 60,000 miles with lots of options. $16,500. Please call Sunday through Thursday. 360-460-6213 FORD: ‘92 Aerostar. Loaded, Eddie Bauer model. Excellent in and out. $1,800. 360-683-5871 FORD: ‘97 F150. 5.4, new tires, trans, batt. Clean. $6,500/obo. 360-681-2643 GET READY FOR WINTER All WD, great in snow, ‘99 Oldsmobile Bravada. Leather, loaded, 129K, exc. cond. $6,299. 928-2181, 461-6273. ISUZU: ‘91 Trooper. Runs good, new tires. $1,500/obo. 670-6041 ISUZU: ‘98 Rodeo. 4x4, leather seats, sunroof, new trans., new tires. $4,000. 457-7766 or 452-2602 ext 2. NISSAN: ‘08 Frontier King Cab. V6 4x4, 24K mi., silver ext. matching canopy, bedliner, auto windows-locks, remote ent, cruise, CD, oversize tires, below KBB val of $20,425. Records avail., no accidents. Very clean. $18,600. Call 360-670-1400 TOYOTA ‘01 SEQUOIA SR5 V-8 automatic, 4x4. Third row seating, gray cloth. Nice, nice, nice! The Other Guys Auto and Truck serving the community since 1996! Military discounts! Lowest buy here pay here interest rates! $12,995. The Other Guys Auto and Truck Center 360-417-3788
102
Legals City of P.A.
CITY OF PORT ANGELES NOTICE OF DEVELOPMENT APPLICATION AND PUBLIC HEARING NOTICE IS HEREBY GIVEN that on October 28, 2010, the CITY OF PORT ANGELES received an application to permit a community garden as a conditional use permit in the Commercial Office zone. The application was considered to be complete on October 30, 2010. The CITY OF PORT ANGELES PLANNING COMMISSION will conduct a public hearing on JANUARY 12, 2011, in consideration of the application. Interested parties are encouraged to comment on the request and to attend the public hearing that will begin at 6 p.m., City Hall, 321 East Fifth Street, Port Angeles, Washington. Written comment must be submitted no later than December 13, 2010, to be included in the staff report. Information may be reviewed at the City Department of Community & Economic Development, City Hall, P.O. Box 1150, Port Angeles. City Hall is accessible to persons with disabilities. Interested parties are invited to attend the meeting. STATE ENVIRONMENTAL POLICY ACT: The optional review process identified in WAC 19711-355 is being used. It is anticipated that a determination of non significance will be issued for the project following the required review period that ends on December 13, 2010. APPLICANT: RICHARD BONINE, CITY OF PORT ANGELES LOCATION: Vacant City property - 300 Block of East Fifth Street For further information contact: Sue Roberds, (360) 417-4750 Pub: Nov. 29, 2010. FORD: ‘95 F150 XLE Ext cab, 8’ bed w/lockable lid, 66k, auto w/o/d, full power, 351 Winsor tow pkg, always garaged, very very clean, below book @ $6,000. 683-8133.
FORD: Step Van. One of a Kind, Endless Possibilities, Solid. 40k on a thrifty Cummins diesel; great tires; new battery; no rust. Food truck? Contractor? RV conversion? Only $4,000/obo. 360-820-2157
MAGIC RAINBOW HAPPY BUS 1973 Volkswagon Transporter $1,500/obo Not Camper Style Runs, Some Rust. Call: 360-797-3951
101
Legals Clallam Co.
Cars
CADILLAC: ’92 Sedan Deville. 144K, 4.9L, auto, runs/ looks good. $2,750/ obo. 452-5522.
GM: ’92 Gladiator conversion van. 350, auto, 140K, runs/ looks good! $3,500. 452-5522
CADILLAC: ‘92 SeVille. Exc. shape, good mpg, new tires. $3,000/obo. 452-5406
MAZDA: ‘86 B2000, 5 sp, canopy, bed liner. $700/obo. 460-7974.
CADILLAC: ‘66 Sedan Deville. All original, 63K mi. $3,800. 360-775-5327
MAZDA: ‘88 B2200. Runs good. $1,000/ obo. 582-7486. PLUMBING VAN: ‘02 Ford, job site ready, plus extra plumbing parts, 28K orginial mi. $20,000/obo. 360-385-2773 TOYOTA: ‘03 Tundra, 93,000 miles, V8, 4x4, access cab, leer canopy, great condition, $14,000/obo. Call 360-448-1440 for more details.
99
Cars
CADILLAC: ‘85 Eldorado Commemorative Edition. Excellent condition, spoke wheels, loaded, no rust, always garaged, beautiful blue, 30K miles on new motor; 112K total miles. $2,900. 360-477-4817 CADILLAC: ‘91 Sedan Deville. Good condition, loaded. $900/obo. 457-3425. CHEV: ‘84 Corvette. Silver, 5.7 liter V8. $5,800. 437-7649. CHEV: ‘00 Camaro. V6, red, T-tops. $6,500/obo. 775-1821
FORD: ‘70 heavy duty 3/4 ton. Runs great, new tow pkg. $900/ obo. 417-3959. CHEV: ‘90 Suburban 4 WD 2500. Low miles, auto, good tires, straight body 4WD, V8, clean inter, no rips, tow pkg runs great. Heavy bumper w/winch. $3,500. Forks 360-374-9512.
9996 328i. 180K mi., new tranny, runs great, needs some body work. $2,700/ obo. 206-272-0220. BUICK ‘02 LESABRE Only 46,000 miles and loaded, including 3.8 liter V6, auto, air, tilt wheel, cruise, power windows, locks, mirrors, and seat, AM/FM CD and cassette, front and side airbags, alloy wheels, remote entry, and more! Expires 12-4-10. $6,995 We Finance Dave Barnier Auto Sales 452-6599 davebarnier.com BUICK ‘04 RENDEZVOUS All WD, V6, 3rd row, leather! Loaded! The Other Guys Auto and Truck setting the standards in buy here pay here! Offering 90 days same as cash! Military Discounts! $9,995. The Other Guys Auto and Truck Center 360-417-3788 CHEV: ‘76 Suburban. 454, 143K, runs good. $800/obo. 360-681-2427 CHEV: ‘88 Camaro. Project car, running, licensed, with ‘90 Camaro parts car. $1,200/obo. 928-3863
Classic Olds. 78' Olds Cutlass Supreme Brougham. 86,000 miles, V8, sunroof, garage kept. few minor parking lot dings. Excellent condition. Runs well. 1 owner. interior in excellent condition. $11,000/obo. 360-683-9770
BUICK: ‘97 LaSabre. Excellent codntion, 1 owner. $4,700. 683-6051 after 4 p.m.
DODGE: 93 Stealth RT. Great condition, only 2 owners, no accidents, 129K mi., AWD, 5 sp., all power, awesome stereo, CD changer and battery. $3,000. Chris 360-732-4514
BUICK: ‘99 Regal. Leather interior, moon roof, good condition. $2,800. 457-9038
DODGE: ‘95 Intrepid. 4 door, white, less than 36K mi., like new, original owner. $4,000. 452-3591.
101
101
Legals Clallam Co.
Legals Clallam Co.
NOTICE OF TRUSTEE'S SALE Pursuant to R.C.W. Chapter 61.24, et seq. and 62A.9A-604(a)(2) et seq. Trustee's Sale No: 01-FEE-98435 I NOTICE IS HEREBY GIVEN that the undersigned Trustee, REGIONAL TRUSTEE SERVICES CORPORATION, will on December 10, 2010, at the hour of 10:00 AM, at THE MAIN ENTRANCE TO THE CLALLAM COUNTY COURTHOUSE, 223 EAST FOURTH STREET, PORT ANGELES, WA, sell at public auction to the highest and best bidder, payable at the time of sale, the following described real and personal property (hereafter referred to collectively as the "Property"), situated in the County of CLALLAM, State of Washington: LOT 14, KIRNER ADDITION TO TOWN OF SEQUIM, AS PER PLAT RECORDED IN VOLUME 5 OF PLATS, PAGE 70, RECORDS OF CLALLAM COUNTY, WASHINGTON. SITUATE IN CLALLAM COUNTY, STATE OF WASHINGTON. Tax Parcel No: 03-3019-640139, commonly known as 468 WEST HEMLOCK STREET SEQUIM, WA. The Property is subject to that certain Deed of Trust dated 12/22/2005, recorded 12/28/2005 , under Auditor's/Recorder's No. 2005 1172182, records of CLALLAM County, Washington, from WILLIAM D. SMITH & CLAUDIA M. SMITH, HUSBAND & WIFE, as Grantor, to FIRST AMERICAN TITLE INSURANCE COMPANY, as Trustee, in favor of MORTGAGE ELECTRONIC REGISTRATION SYSTEMS, INC. AS NOMINEE FOR FIRST HORIZON HOME LOAN CORPORATION, as Beneficiary, the beneficial interest in which is presently held by EVERHOME MORTGAGE COMPANY./are made are as follows: FAILURE TO PAY THE MONTHLY PAYMENT WHICH BECAME DUE ON 5/1/2010, AND ALL SUBSEQUENT MONTHLY PAYMENTS, PLUS LATE CHARGES AND OTHER COSTS AND FEES AS SET FORTH. Failure to pay when due the following amounts which are now in arrears: .mount due as of September 10, 2010 Delinquent Payments from May 01, 2010 2 payments at $ 1,024.05 each $ 2,048.10 1 payments at $ 1,104.11 each $ 1,104.11 2 payments at $ 1,028.22 each $ 2,056.44 (05-01-10 through 09-10-10) Late Charges: $ 170.52 Beneficiary Advances: $ 0. 00 Suspense Credit: $ 0.00 TOTAL: $ 5,379.17 IV The sum owing on the obligation secured by the Deed of Trust is: Principal $174,137.00, December 10, 2010. The default(s) referred to in paragraph Ill must be cured by November 29, 2010 (11 days before the sale date) to cause a discontinuance of the sale. The sale will be discontinued and terminated if at any time on or before November 29, 2010, (11 days before the sale date) the default(s) as set forth in paragraph Ill is/are cured and the Trustee's fees and costs are paid. The sale may be terminated at any time after November 29,: CLAUDIA M. SMITH, 468 WEST HEMLOCK STREET, SEQUIM, WA, 98382 WILLIAM D. SMITH, 468 WEST HEMLOCK STREET, SEQUIM, WA, 98382 by both first class and certified mail on 8/3/2010, proof of which is in the possession of the Trustee; and on 8/3/201 0,: September 7, 2010. Effective Date: REGIONAL TRUSTEE SERVICE CORPORATION Trustee By ANNA EGDORF, AUTHORIZED AGENT Address: 616 1st Avenue, Suite 500 Seattle, WA 98104 Phone: (206) 340-2550 Sale Information: ASAP# FNMA3726251 11/08/2010, 11/29/2010 Pub.: Nov. 8, 29, 2010
MONDAY, NOVEMBER 29, 2010
99
Cars
99
Cars
CHEV: ‘90 Cavalier. Auto, 2 door coupe. $900. 683-8249. FORD: 1929 Model “A”. Roadster, 10 footer. $17,500 firm. 681-5403
FORD: ‘90 Tempo. Runs great. 129K miles. 20-25 mpg. $900. 360-775-4854. FORD: ‘92 Crown Victoria. Runs and looks great, 83K. $2,800/ obo. 683-2542.
FORD: ‘92 Mustang Convertible. Awesome care for sale! White with white top, 85,000 original miles. $3,800/obo. Call Joe at: 360-683-3408 or 360-461-1619. HONDA: ‘06 Civic. 67,000 mi., 2 door coupe, clean, white with black/ gray interior. $10,000/obo 460-0845 HONDA: ‘88 Accord. 2 door, auto, $1,800/ obo. 452-8663.
HYUNDAI: ‘86 Excel. 4 door hatchback Only 55,000 miles, new exhaust, excellent gas mileage, runs great, in good shape. Only 2 owners (in family). $2,500/obo. 457-4866 LINCOLN: ‘63 Continental. Partially restored, suicide doors, runs. $2,750. 457-0272 LINCOLN: ‘87 Towncar Signature Series. Leather interior, power doors, windows, sunroof, low miles, grandpa car, excellent condition. $3,300. 452-9693 eves.
Cars
SAAB: ‘94 900si. Must see. $900/obo. 452-590900 Sable LS Wagon. 3rd seat, leather interior, sunroof, alloy wheels, new tires. $4,400.
MINI COOPER: ‘05. White, 103,000 miles, Runs/drives great, no accidents, has had all scheduled tune-ups & oil changes, very clean interior, 2 new tires, highway miles, GREAT MPG. $9,995. Call Angela. 360-460-4802 NASH: ‘50 Statesman. Needs work, runs great, extra engine and tranny. Must sell. $4,995 or make offer. 681-0717 OLDS: ‘90. Runs great. Looks great. $1,200. 460-1183. PONTIAC: ‘’04 Grand Prix. Low mi., 52K, very clean, must see. $8,000/obo. 457-9332
MAZDA: ‘07 3. 5 sp., low hwy mi., charcoal/black interior, Thule roof rack, GPS, call for questions/test drive. $11,000/obo. 206-375-5204
PORSCHE: ‘02 Boxter S. 56K miles, 6 spd, black on black. $21,500. 461-9635.
MERCEDES BENZ ‘97 C230. 122K, executive use only, very clean. $4,500/ obo. 582-1292.
SUBARU: ‘07 Forester. 25,000 mi., perfect condition, under warranty. $16,750. 452-6014
101
101
Legals Clallam Co.
99
C9
PORSCHE: ‘72 914. Good condition, engine rebuilt. $5,800. 683-7965.
Legals Clallam Co.
SUBARU: ‘08 Legacy $15,750. SUZUKI: ‘00 Grand Vitara. Exc. cond., 87K mi., very clean. $3,950. 775-1132. TOYOTA ‘03 AVALON XLS 4 DOOR The flagship of the Toyota line, V6, auto, air, tilt wheel, cruise, power windows, locks, mirrors, and dual power seats, leather interior, power sunroof, front and side airbags, 4 wheel ABS and electronic traction control, alloy wheels, AM/FM CD and cassette, remote entry, and more! Extra clean. Expires 12-410. $10,995 We Finance Dave Barnier Auto Sales 452-6599 davebarnier.com TOYOTA: ‘05 Prius Hybrid. Black, new tires, under, 67K mi. $11,085. 928-9527. TOYOTA: ‘10 Prius. As new, save $4,000. $20,000. 452-7273.
TOYOTA: ‘03 Camry LE One owner, no accidents, well maintained, 4 cyl, auto trans, 95,000 mi. $7,250. 477-2183. TOYOTA: ‘89 Camry. $1,200. 928-9774. TOYOTA: ‘91 Corolla. 4 dr, 5 speed, good shape, runs good, 30+ mpg. $1,650/obo. 360-452-8788 VW: ‘75 Super Beetle. Fuel injected, runs good, 30+ mpg, nice paint, good tires, new floor pan, Pioneer stereo, CD player. Price reduced! $2,995/obo. 775-9648
101
Legals Clallam Co.
NOTICE OF TRUSTEE'S SALE PURSUANT TO THE REVISED CODE OF WASHINGTON CHAPTER 61.24 ET. SEQ. Loan No: 0474856747 APN: 06-30-10-500950 TS No: WA-220945-C I. NOTICE IS HEREBY GIVEN that LSI Title Agency, Inc., the undersigned Trustee will on 1/3/2011, at 10:00 AM at The main entrance to the Clallam County Courthouse, 223 East 4th St., Port Angeles, Washington: THE SOUTH HALF OF LOTS 11 AND 12, IN BLOCK 9, OF PUGET SOUND CO-OPERATIVE COLONY'S SECOND ADDITION TO PORT ANGELES, AS PER PLAT THEREOF RECORDED IN VOLUME 4 OF PLATS, PAGE 16 1/2, RECORDS OF CLALLAM COUNTY, WASHINGTON. SITUATE IN CLALLAM COUNTY, STATE OF WASHINGTON. Commonly known as: 207 VASHON AVENUE PORT ANGELES, Washington 98362 which is subject to that certain Deed of Trust dated 7/25/2007, recorded 7/31/2007, under Auditor's File No. 2007-1206332, in Book , Page records of Clallam County, Washington, from WILLIAM R. PENNINGTON AND KARLA J. PENNINGTON, HUSBAND AND WIFE, as Grantor(s), to ESCROW AND TITLE SERVICES, as Trustee, to secure an obligation in favor of "MERS" MORTGAGE ELECTRONIC REGISTRATION SYSTEMS, INC., SOLELY AS NOMINEE FOR HOMECOMINGS FINANCIAL, LLC (F/K/A HOMECOMINGS FINANCIAL NETWORK, INC.) A LIMITED LIABILITY COMPANY, as Beneficiary, the beneficial interest in which was assigned by "MERS" MORTGAGE ELECTRONIC REGISTRATION SYSTEMS, INC., SOLELY AS NOMINEE FOR HOMECOMINGS FINANCIAL, LLC (F/K/A HOMECOMINGS FINANCIAL NETWORK, INC.) A LIMITED LIABILITY COMPANY to GMAC MORTGAGE, LLC FKA GMAC MORTGAGE CORPORATION.: PAYMENT INFORMATION FROM 5/1/2010 THRU 9/26/2010 NO.PMT 5 AMOUNT $1,399.54 TOTAL $6,997.70 LATE CHARGE INFORMATION FROM 5/1/2010 THRU 9/26/2010 NO. LATE CHARGES 5 TOTAL $283.25 PROMISSORY NOTE INFORMATION Note Dated: 7/25/2007 Note Amount: $170,000.00 Interest Paid To: 4/1/2010 Next Due Date: 5/1/2010 IV. The amount to cure defaulted payments as of the date of this notice is $13,551.93. Payments and late charges may continue to accrue and additional advances to your loan may be made, it is necessary to contact the beneficiary prior to the time you tender the reinstatement amount so that you may be advised of the exact amount you would be required to pay. As of the dated date of this document the required amount to payoff the obligation secured by the Deed of Trust is: $194,346.08 (note: due to interest, late charges and other charges that may vary after the date of this notice, the amount due for actual loan payoff may be greater). The principal sum of $182,453.22, together with interest as provided in the Note from the 1/3/2011. The defaults referred to in Paragraph III must be cured by 12/23/2010, (11 days before the sale date) to cause a discontinuance of the sale. The sale will be discontinued and terminated if at any time before 12/23/2010 (11 days before the sale) the default as set forth in Paragraph III is cured and the Trustee's fees and costs are paid. Payment must be in cash or with cashier's or certified checks from a State or federally chartered bank. The sale may be terminated any time after the 12/23/2010 ): WILLIAM R. PENNINGTON AND KARLA J. PENNINGTON, HUSBAND AND WIFE 207 VASHON AVENUE PORT ANGELES, Washington 98362 KARLA J PENNINGTON 207 VASHON AVENUE PORT ANGELES, WA 98362 by both first class and certified mail on 8/23. days or more before the end of the monthly rental period. THIS IS AN ATTEMPT TO COLLECT A DEBT AND ANY INFORMATION OBTAINED WILL BE USED FOR THAT PURPOSE. DATED: 9/26/2010 LSI Title Agency, Inc. 1111 Main St., #200 Vancouver, WA 98660 Sale Line:: 714-730-2727 Marina Marin Authorized Signatory ASAP# FNMA3753460 11/29/2010, 12/21/2010 Pub.: Nov. 29, Dec. 21, 2010
C10
WeatherNorthwest
Monday, November 29, 2010
Peninsula Five-Day Forecast Today
TonighT
Tuesday
Wednesday
Yesterday
Thursday
Friday
High 41
Low 35
45/33
42/32
42/31
42/32
Rain developing; fog this morning.
Rain.
Rain.
Mostly cloudy with a passing shower.
Cloudy, chance of a little rain; chilly.
Mostly cloudy, showers possible; chilly.
The Peninsula As high pressure slides off to the east today, a storm system will approach British Columbia and the Pacific Northwest. After areas of freezing fog in the morning, expect a mostly cloudy and chilly day across the Peninsula with rain arriving. Snow levels Neah Bay Port across the Olympics will be around 2,500 feet. The storm 45/40 Townsend system will bring additional rain and mountain snow Port Angeles 44/38 tonight and Tuesday, some of which will be heavy at 41/35 times. Snow levels will rise to 5,000 feet tonight, then Sequim drop down to 3,000 feet Tuesday.
Victoria 43/37
44/37
Forks 45/38
Olympia 43/36
Everett 43/38
Seattle 42/39
Spokane 26/17
Forecasts and graphics provided by AccuWeather, Inc. © 2010
Marine Forecast
Areas of fog in the morning; considerable clouds, chilly and becoming rainy today. Wind east 10-20 knots. Waves 1-3 feet. Visibility under a mile. Rain tonight. Wind east 12-25 knots. Waves 1-3 feet. Visibility under 3 miles. Rain tomorrow. Wind east 7-14 knots becoming west. Waves 1-3 feet. Visibility under 3 miles. Wednesday: Mainly cloudy with a passing shower. Wind southeast 6-12 knots. Waves 1-2 feet.
LaPush
6:18 a.m. 6:21 p.m. Port Angeles 8:51 a.m. 9:07 p.m. Port Townsend 10:36 a.m. 10:52 p.m. Sequim Bay* 9:57 a.m. 10:13 p.m.
Tomorrow
wednesday
Ht
Low Tide
Ht
High Tide Ht
Low Tide Ht
High Tide Ht
7.8’ 6.6’ 7.6’ 4.4’ 9.2’ 5.3’ 8.6’ 5.0’
12:31 p.m. ----1:41 a.m. 4:08 p.m. 2:55 a.m. 5:22 p.m. 2:48 a.m. 5:15 p.m.
2.2’ --1.2’ 2.4’ 1.5’ 3.1’ 1.4’ 2.9’
7:11 a.m. 7:39 p.m. 9:25 a.m. 11:13 p.m. 11:10 a.m. ----10:31 a.m. -----
12:40 a.m. 1:39 p.m. 2:41 a.m. 4:52 p.m. 3:55 a.m. 6:06 p.m. 3:48 a.m. 5:59 p.m.
8:02 a.m. 8:53 p.m. 9:59 a.m. ----12:58 a.m. 11:44 a.m. 12:19 a.m. 11:05 a.m.
8.2’ 6.6’ 7.6’ 4.9’ 9.2’ --8.6’ ---
*To correct for Dungeness Bay subtract 15 minutes for high tide, 21 minutes for low tide.
First
Full
1.3’ 1.4’ 2.3’ 1.2’ 3.0’ 1.6’ 2.8’ 1.5’
8.6’ 6.7’ 7.7’ --5.9’ 9.3’ 5.5’ 8.7’
Low Tide Ht 1:39 a.m. 2:41 p.m. 3:46 a.m. 5:33 p.m. 5:00 a.m. 6:47 p.m. 4:53 a.m. 6:40 p.m.
Dec 13
Dec 21
1.7’ 0.6��� 3.3’ 0.2’ 4.3’ 0.2’ 4.0’ 0.2’
City Hi Lo W Athens 74 60 pc Baghdad 78 54 s Beijing 52 31 s Brussels 34 18 c Cairo 85 67 s Calgary 19 6 s Edmonton 14 -3 s Hong Kong 77 65 s Jerusalem 77 51 s Johannesburg 86 54 s Kabul 63 27 s London 36 30 pc Mexico City 77 45 s Montreal 41 32 s Moscow 11 0 pc New Delhi 81 45 s Paris 36 27 c Rio de Janeiro 93 78 pc Rome 55 46 pc Stockholm 23 12 sn Sydney 72 66 sh Tokyo 61 45 s Toronto 43 36 pc Vancouver 42 37 r Weather (W): prcp-precipitation, s-sunny, pc-partly cloudy, c-cloudy, sh-showers, r-rain, t-thunderstorms, sf-snow flurries, sn-snow, i-ice.
of Juan de Fuca. Phone 360385-0373 or e-mail artymus@ olypen.com.
Jefferson County Historical Museum and shop — 540 Water St., 11 a.m. to 4 p.m. Admission: $4 for adults; $1 for children 3 to 12; free to historical society members. Exhibits include “Jefferson County’s Maritime Heritage,” “James Puget Sound Coast Artil- Swan and the Native Amerilery Museum — Fort Worden cans” and “The Chinese in State Park, 11 a.m. to 4 p.m. Early Port Townsend.” Phone Admission: $3 for adults; $1 for 360-385-1003 or visit www. children 6 to 12; free for chil- jchsmuseum.org. dren 5 and younger. Exhibits Northwest Maritime Ceninterpret the Harbor Defenses
New York 48/42
Kansas City 51/22
Los Angeles 63/43
Washington 49/39
Atlanta 47/44 El Paso 49/22
Showers T-storms Rain Flurries Snow Ice
Houston 78/48
Fronts Cold Warm
Miami 81/72 Lo W 37 17 c 16 -1 s 48 42 r 47 44 c 52 37 s 50 34 s 35 20 pc 24 7 pc 22 2 sn 21 11 pc 45 35 s 44 37 pc 65 54 c 25 13 sn 47 37 r 53 47 pc 28 18 sf 43 40 c 68 40 c 35 13 sn 47 24 r 46 39 pc 40 38 c -11 -28 pc 17 0 pc 82 70 pc 78 48 t 37 27 sn 51 48 64 63 81 47 39 60 76 48 55 43 81 65 50 54 41 54 34 51 57 27 74 60 53 35 17 49
Lo W 22 r 28 s 38 r 43 s 72 c 36 r 23 r 54 c 62 t 42 s 26 pc 21 r 65 c 39 s 38 s 35 s 38 c 42 pc 19 s 29 s 35 r 12 sf 41 pc 43 s 39 s 11 sn 4 pc 39 s
National Extremes Yesterday (For the 48 contiguous states)
High: 86 at Naples, FL
Low: -5 at Burns, OR
n Deer Park Cinema,
Port Townsend Rock Club headquarters. Meet docent in workshop — Club building, Port Angeles (360-452chandlery, 431 Water St., 2 Jefferson County Fairgrounds, 7176) p.m. Elevators available, chil- 4907 Landes St., 6:30 p.m. to 9 “Burlesque” (PG-13) dren welcome and pets not p.m. “Harry Potter and the allowed inside building. Phone Deathly Hallows: Part 1” (PG360-385-3628, ext. 102, or Medical referral service — 13) e-mail sue@nwmaritime.org. JC MASH, Jefferson County’s “Love & Other Drugs” (R) free medical referral and help “Morning Glory” (PG-13) Kayak program — Help service, American Legion Hall, “Red” (PG-13) build a cedar-strip wooden “Tangled” (PG) kayak. Chandler Building Boat 209 Monroe St., Port Townsend, Shop, Maritime Center, Water 7 p.m. to 8 p.m. For informaand Monroe streets, 6 p.m. to 8 tion, visit or n Lincoln Theater, Port p.m. Free. Offered by the North- phone 360-385-4268. Angeles (360-457-7997) west Maritime Center and RedRhody O’s square dance “Due Date” (R) fish Custom Kayaks. Phone “Megamind” (PG) Joe Greenley at 360-808-5488 lessons — Gardiner Commu“The Next Three Days” (PGor click on. nity Center, 980 Old Gardiner 13) Road, 7:30 p.m. com.
BLACK FRIDAY
“Unstoppable” (PG-13)
n The Rose Theatre,
Port Townsend (360385-1089) “Burlesque” (PG-13) “Tangled” (PG)
n Uptown Theater, Port Townsend (360-3853883) “Harry Potter and the Deathly Hallows: Part 1” (PG13)
peninsuladailynews.com
TOYOTA-THON 2010
VS
CYBER MONDAY
“The Best Can Cost You Less!”
SHOP US ONLINE OR ON DEER PARK ROAD 2010 Honda
Denver 35/13
Detroit 46/39
Now Showing
Continued from C5 of Puget Sound and the Strait ter tour — Free tour of new
East Jefferson County Senior Co-ed Softball — H.J. Carroll Park, 1000 Rhody Drive, Chimacum, 10 a.m. to noon. Open to men 50 and older and women 45 and older. Phone 360-437-5053 or 360-437-2672 or 360-379-5443.
San Francisco 53/39
Dec 27
Minneapolis 39/23 Chicago 47/37
Moon Phases
Things to Do Tuesday
Billings 24/7
Sunset today ................... 4:24 p.m. Sunrise tomorrow ............ 7:42 a.m. Moonrise today .............. 12:25 a.m. Moonset today ............... 12:52 p.m.
World Cities Today
Yakima Kennewick 30/25 33/26
Today
Seattle 42/39
Sun & Moon
Dec 5
Temperatures are today’s highs and tonight’s lows.
Table Location High Tide
Monday, November 29, 2010
-10s -0s
Shown is today’s weather.
Tide
National Forecast
Statistics are for the 24-hour period ending at 4 p.m. yesterday High Low Prcp YTD P. Angeles 44 31 0.00 10.52 Forks 42 29 0.06 111.29 Seattle 42 35 0.03 37.56 Sequim 45 32 0.01 8.82 Hoquiam 42 29 0.03 60.83 Victoria 42 29 0.05 28.14 P. Townsend* 45 36 0.00 14.46 *Data from
New
Port Ludlow 44/38 Bellingham 43/35
Aberdeen 47/42
Peninsula Daily News
Test Drive Today!
FIT
5 Speed automatic
NEW 2010 Priuss
NEW 2010 COrOLLAs
NEW 2010 MATriXs
NEW 2010 YAriss
FeATuReD SpeCIAl leASe
$
139
offer valid from 11/2/2010 through 1/4/2011
per month*
$139.00 per month for 36 months. $1,999.00 total due at signing.
0%
Includes down payment with no security deposit. Excludes taxes, titles and fees. For well-qualified buyers.
*FEATURED SPECIAL LEASE: Closed-end lease for 2010 Fit 5 Speed Automatic (Model GE8H2AEW) for $139.00 per month for 36 months with a $1,860.00 capitalized cost reduction available to customers who qualify for the HFS Super Preferred or Preferred credit tier. Other rates/tiers are available under this offer. $1,999.00 total due at lease signing (includes first month’s payment and capitalized cost reduction with no security deposit; total net capitalized cost and base monthly payment does not include tax, license, title, registration, documentation fees, options, insurance and the like) Not all buyers may qualify.
honDA yeAr enD CLeArAnCe eVent
clearance pricing
on all new hondas CIVIC
INSIGHT
APR UP TO 60 MOS*
NEW 2010 CAMrYs
0.9% APR ACCORD
NEW 2010 CAMrY HYBriDs
**
NEW 2010 TuNDrAs
CR-V
NEW 2010 HiGHLANDErs
NEW 2010 HiGHLANDEr HYBriDs
Low Prices on aLL remaining 2010s
**Up to 60 months on approval of credit. For well qualified buyers. All vehicle sales subject to a negotiable $150 document fee. Photos for illustration purposes only. Offer ends 1/4/2011.
Check us out online at
*TFS Tier 1+ thru Tier 3 Customers On Approval of Credit. Offer expires 11/30/10. Does not include tax, license & documentation fees. All vehicles subject to prior sale. Not responsible for typographical errors. A negotiable dealer documentary fee up to $150 may be added to the sale price. See Dealer for details.
You Can Count on us!
0B5104504
97 Deer Park Road | Port Angeles | 1-800-927-9395 • 360-452-9268
95 Deer Park Road • Port Angeles – 1-800-927-9379 • 360-457-8511
0B5104500
WILDER Honda WILDER
You Can Count On Us! | https://issuu.com/peninsuladailynews/docs/whfoavb20101129j | CC-MAIN-2017-17 | refinedweb | 35,106 | 74.39 |
import "github.com/igm/kubernetes/pkg/watch"
Package watch contains a generic watchable interface, and a fake for testing code that uses the watch interface.
doc.go filter.go iowatcher.go mux.go watch.go Error: *api.Status is recommended; other types may make sense // depending on context. Object runtime.Object }
Event represents a single event to a watched resource.
EventType defines the possible types of events.
const ( Added EventType = "ADDED" Modified EventType = "MODIFIED" Deleted EventType = "DELETED" Error EventType = "ERROR" )
FakeWatcher lets you test anything that consumes a watch.Interface; threadsafe.
func NewFake() ) Modify(obj runtime.Object)
Modify sends a modify event.
func (f *FakeWatcher) ResultChan() <-chan Event
func (f *FakeWatcher) Stop()
Stop implements Interface.Stop().
FilterFunc should take an event, possibly modify it in some way, and return the modified event. If the event should be ignored, then return keep=false.
type Interface interface { // Stops watching. Will close the channel returned by ResultChan(). Releases // any resources used by the watch. Stop() // Returns a chan which will receive all the events. If an error occurs // or Stop() is called, this channel will be closed, in which case the // watch should be completely cleaned up..
Mux distributes event notifications among any number of watchers. Every event is delivered to every watcher.
NewMux creates a new Mux. queueLength is the maximum number of events to queue. When queueLength is 0, Action will block until any prior event has been completely distributed. It is guaranteed that events will be distibuted in the order in which they ocurr, but the order in which a single event is distributed among all of the watchers is unspecified.
Action distributes the given event among all watchers.
Shutdown disconnects all watchers (but any queued events will still be distributed). You must not call Action after calling Shutdown.
Watch adds a new watcher to the list and returns an Interface for it. Note: new watchers will only receive new events. They won't get an entire history of previous events.
StreamWatcher turns any stream for which you can write a Decoder interface into a watch.Interface.
func NewStreamWatcher(d Decoder) *StreamWatcher
NewStreamWatcher creates a StreamWatcher from the given decoder.
func (sw *StreamWatcher) ResultChan() <-chan Event
ResultChan implements Interface.
func (sw *StreamWatcher) Stop()
Stop implements Interface.
Package watch imports 5 packages (graph). Updated 2018-04-17. Refresh now. Tools for package owners. | https://godoc.org/github.com/igm/kubernetes/pkg/watch | CC-MAIN-2019-51 | refinedweb | 392 | 60.41 |
Originally posted on opensource.
Give your password an extra layer of security with GPG and the Python getpass module.
Passwords are particularly problematic for programmers. You’re not supposed to store them without encrypting them, and you’re not supposed to reveal what’s been typed when your user enters one. This became particularly important to me when I decided I wanted to boost security on my laptop. I encrypt my home directory—but once I log in, any password stored as plain text in a configuration file is potentially exposed to prying eyes.
Specifically, I use an application called Mutt as my email client. It lets me read and compose emails in my Linux terminal, but normally it expects a password in its configuration file. I restricted permissions on my Mutt config file so that only I can see it, but I’m the only user of my laptop, so I’m not really concerned about authenticated users inadvertently looking at my configs. Instead, I wanted to protect myself from absent-mindedly posting my config online, either for bragging rights or version control, with my password exposed. In addition, although I have no expectations of unwelcome guests on my system, I did want to ensure that an intruder couldn’t obtain my password just by running
cat on my config.
Python GnuPG
The Python module
python-gnupg is a Python wrapper for the
gpg application. The module’s name is
python-gnupg, which you must not confuse with a module called
gnupg.
GnuPG (GPG) is the default encryption system for Linux, and I’ve been using it since 2009 or so. I feel comfortable with it and have a high level of trust in its security.
I decided that the best way to get my password into Mutt was to store my password inside an encrypted GPG file, create a prompt for my GPG password to unlock the encrypted file, and hand the password over to Mutt (actually to the
offlineimap command, which I use to synchronize my laptop with the email server).
Getting user input with Python is pretty easy. You make a call to
input, and whatever the user types is stored as a variable:
myinput = input()print(“You entered: “, myinput)
My problem was when I typed a password into the terminal in response to my password prompt, everything I typed was visible to anyone looking over my shoulder or scrolling through my terminal history:
Invisible password entry with getpass
As is often the case, there’s a Python module that’s already solved my problem. The module is
getpass4, and from the user’s perspective, it behaves exactly like
input except without displaying what the user is typing.
You can install both modules with pip:
python-gnupg getpass4
Here’s my Python script to create a password prompt:
# by Seth Kenlon
# GPLv3# install deps:
# python3 -m pip install –user python-gnupg getpass4
import gnupg
import getpass
from pathlib import Path
def get_api_pass():
homedir = str(Path.home())
gpg = gnupg.GPG(gnupghome=os.path.join(homedir,“.gnupg”), use_agent=True)
passwd = getpass.getpass(prompt=“Enter your GnuPG password: “, stream=None)
with open(os.path.join(homedir,‘.mutt’,‘pass.gpg’), ‘rb’) as f:
apipass = (gpg.decrypt_file(f, passphrase=passwd))
f.close()
return str(apipass)
if __name__ == “__main__”:
apipass = get_api_pass()
print(apipass)
Save the file as
password_prompt.py if you want to try it out. If you’re using
offlineimap and want to use this solution for your own password entry, then save it to some location you can point
offlineimap to in your
.offlineimaprc file (I use
~/.mutt/password_prompt.py).
Testing the password prompt
To see the script in action, you first must create an encrypted file (I’ll assume that you already have GPG set up):
$ gpg –encrypt pass
$ mv pass.gpg ~/.mutt/pass.gpg
$ rm pass
Now run the Python script:
Enter your GPG password:
hello world
Nothing displays as you type, but as long as you enter your GPG passphrase correctly, you will see the test message.
Integrating the password prompt with offlineimap
I needed to integrate my new prompt with the
offlineimap command. I chose Python for this script because I knew that
offlineimap can make calls to Python applications. If you’re an
offlineimap user, you’ll appreciate that the only “integration” required is changing two lines in your
.offlineimaprc file.
First, add a line referencing the Python file:
pythonfile = ~/.mutt/password_prompt.py
And then replace the
remotepasseval line in
.offlineimaprc with a call to the
get_api_pass() function in
password_prompt.py:
remotepasseval = get_api_pass()
No more passwords in your config file!
Security matters
It sometimes feels almost paranoid to think about security minutiae on your personal computer. Does your SSH config really need to be restricted to 600? Does it really matter that your email password is in an inconsequential config file buried within a hidden folder called, of all things,
.mutt? Probably not.
And yet knowing that I don’t have sensitive data quietly hidden away in my config files makes it a lot easier for me to commit files to public Git repositories, to copy and paste snippets into support forums, and to share my knowledge in the form of actual, known-good configuration files. For that alone, improved security has made my life easier. And with so many great Python modules available to help, it’s easy to implement.
Source: opensource | https://learningactors.com/enter-invisible-passwords-using-this-python-module/ | CC-MAIN-2021-43 | refinedweb | 898 | 60.65 |
As a marketer, you are always looking to do more with less. You may get the sense that technology can help you do better and you’re right. Follow along as I explain exactly how you can harness this force without writing a single line of code.
1. Do A/B Split Tests and Personalization
You’ve probably heard of all the merits of A/B split testing and of being data-driven, but how can you implement these different tests on each of your pages without consulting the tech team?
It’s easy enough with solutions like Visual Website Optimizer and Optimizely that allow you to drag and drop your changes across the website by simply copy and pasting a snippet of code across your website (or getting somebody technical to help you do that). Both tools allow you to customize your website for different types of visitors, and they’ll allow you to run controlled experiments to see which variations of your web pages perform best.
2. Build Landing Pages
Maybe you don’t want to optimize your website – you want to build some new pages. Maybe it’s a new campaign announcing a new product launch, or maybe you’re running an event you want to collect an email waiting list for. Whatever it is, you’ll need a web page that describes what you’re doing, a landing page. Thankfully, you don’t have to build anything in HTML or CSS. You can use drag and drop editors in Unbounce or, if you’re really looking to maximize conversion, marketing-based solutions like Leadpages.
3. Build Entire Websites
Don’t want to stop at just building a web page? Maybe you want to look to build an entire website for a new product. Thankfully, you don’t have to call a web agency to do everything for you at a high price! You can use solutions like Squarespace or Wix to build everything in your website without a line of code. And if you want to get even more customized, grab a theme from Themeforest and learn the basics of WordPress! You’ll soon be building beautiful websites with layers of personalized complexity–without a line of code.
4. Scrape Links, Content and More with Python (but use with caution!)
By downloading Anaconda and using the iPython Notebook contained within, you can use Python scripts and copy + paste the outputs.
The easiest and most powerful use of this is to take links and data from other websites. Be careful though, a lot of websites will have terms of use that prohibit the use of their content. Nevertheless, it might be a good tool to use to get raw data, or to get useful links that point to certain resources. You might, for example, want to get all of the links of your competitors profiled in a certain blog post, or you might want to get all of the links of different services in a directory.
This script above will take all the links from a sample page (in this case the Wikipedia page for the Python language)
Here’s the raw script you can copy + paste in Python 3.5 mode:
from bs4 import BeautifulSoup
import requests
r = requests.get(“”)
soup = BeautifulSoup(r.text,”lxml”)
for link in soup.find_all(‘a’):
print(link.get(‘href’))
5. Send Newsletters and Automate Emails
Email is one of the most effective marketing channels out there, and the best for return on investment. If you can get people coming back by filling their inbox with valuable information, you’ve reached marketing nirvana.
Instead of doing all the messy work coding up HTML-rich emails, you can use the drag & drop and email list capabilities of MailChimp. If you want to automate emails a layer beyond, and take people through an in-depth series of automated emails, you could use a solution like Drip.
6. Get Data
Ever needed to take a quick look at certain data, like the demographic traits of a certain country? Need to source the latest financial data? Look no further than Quandl. You’ll be able to find all sorts of data, from the average age of first marriage for women to life expectancy at birth. Best of all, you can export that data directly in Excel, stepping away from all of the code if you needed.
7. Filter Through Data
Most people think of Google Apps as a great way to collaborate with others, but they don’t know about the full power of this suite of tools. Google built a way for you to add layers of functionality on top of their powerful software, allowing you to do so much more with different types of data. Best of all, you can copy + paste pre-made scripts and benefit from the effects without being technical!
Check to see if your website is online or save all tweets that match a certain hashtag to a spreadsheet. You can do that or a variety of other tasks through scripts that will save you time and money.
Use these scripts for good, not evil.
8. Building Popups and Other Interactive Elements on a Website
Sometimes, you want to add an additional layer of interactivity to a website, whether it’s a popup to highlight a brand new feature, or a walkthrough that will help guide users. Thankfully, with tools like Engage and HelloBar you can add different modals or elements to your website that can help you collect emails, direct traffic elsewhere, or dictate what users should look at in a web page.
9. Dig Deeper into Websites, and See How Your Website Looks in mobile
Most people don’t know about the handy Google Chrome Inspector or its equivalent Firebug on Firefox. While most of the time it is used by developers to spot errors or mock up certain changes in the code, you can use the Inspector to check into the exact URLs of images, and how your website displays on different screen sizes, from iPhones to tablets.
The responsive design tool in these inspector tools will allow you to simulate what your website looks like from device-to-device, a crucial need to see if your website is mobile-friendly. This is a factor that’s critically important for websites with mobile traffic, and one that Google uses to rank webpages.
Conclusion
By harnessing technology, you’ll be at the cutting-edge of digital marketing. You won’t even need to learn how to code to get an awesome array of new powers. Save yourself time and money, and make sure you use your new capabilities for good!
About the Author: Roger is a digital marketer who self-taught himself to code but recognizes when code is useful and when it isn’t. He manages Growth for edtech company Springboard, and will often write about new technologies at his own personal blog code(love). You can find him on Twitter. | http://bloggersmakingmoney.com/9-ways-for-marketers-to-do-amazing-technical-things-without-knowing-code/ | CC-MAIN-2017-26 | refinedweb | 1,165 | 67.38 |
Hide Forgot
Spec URL:
SRPM URL:
Description:.
Just to show the output of rpmlint on this package:
[ansilva@dhcp227-94 noarch]$ rpmlint python-proctor-1.2-2.noarch.rpm
[ansilva@dhcp227-94 noarch]$
This person is in need of a sponsor.
* Package passes rpmlint
[steve@psycho Desktop]$ rpmlint
/home/steve/rpmbuild/RPMS/noarch/python-proctor-1.2-2.fc7.noarch.rpm
[steve@psycho Desktop]$
* Package passes Package Naming Guidelines
* %{name} is the same as spec file
* Meets the Packaging Guidelines
* Licensed under BSD. NOTE: license is not in upsteam source. Please notify the
owner and request it be added.
* The License field in the package spec file matches the actual license.
* spec file is written in American English.
* spec is legible
* Upstream matches whats in srpm
[steve@psycho Desktop]$ md5sum Proctor-1.2.tar.gz*
cee63679980ea25816511bb1b8be0d7f Proctor-1.2.tar.gz
cee63679980ea25816511bb1b8be0d7f Proctor-1.2.tar.gz-orig
[steve@psycho Desktop]$
* Package compiles in noarch
* BuildRequires looks sane.
* Build doesn't have duplicate files listed
* %files look sane
* %clean is sane
* macros used throughout spec
* package is python libraries which is code
* Package does not require docs to run
X Unclear if gui.py should be available or if it is in progress. If it should
work then a %{name}.desktop file is needed and that file must be properly
installed with desktop-file-install in the %install section. Please talk with
the developer.
* Does not own files or directories owned by other packages
* %install has rm -rf $RPM_BUILD_ROOT
* Files are all valid UTF-8
X Package seems to require Pmw ( I believe). Without
Pmw warnings are thrown on running tests and gui does not work.
[steve@psycho rpmbuild]$ python /usr/lib/python2.5/site-packages/proctorlib/gui.py
Traceback (most recent call last):
File "/usr/lib/python2.5/site-packages/proctorlib/gui.py", line 38, in <module>
import Pmw
ImportError: No module named Pmw
[steve@psycho rpmbuild]$
- Note: A later version has been released -- 1.3 Mon Jul 30 07:43:36 2007
()
* Package seems to work as expected with the noted exception of the missing GUI
lib:
[steve@psycho proctorlib]$ proctorbatch --list
WARNING: Could not import icon (No module named PmwContribD)
test: tests.ExampleTestCase.test00
test: tests.ExampleTestCase.test01
test: tests.ExampleTestCase.test02
test: tests.ExampleTestCase.test03Failure
test: tests.ExampleTestCase.test04Error
test: tests.ExampleTestCase.test05
test: tests.ExampleTestCase.test06
test: tests.ExampleTestCase.test07
test: tests.ExampleTestCase.test08Failure
test: tests.ExampleTestCase.test09Error
test: tests.ExampleTestCase.test10
test: tests.ExampleTestCase.test11
test: tests.ExampleTestCase.test12
....
It also is importable as expected ....
[steve@psycho proctorlib]$ python
Python 2.5 (r25:51908, Apr 10 2007, 10:29:13)
[GCC 4.1.2 20070403 (Red Hat 4.1.2-8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import proctorlib
>>> print proctorlib.__doc__
Library for Proctor.
I've resolved to move along to a new package, I will try to get someone else to
pick this package up. | https://bugzilla.redhat.com/show_bug.cgi?id=247268 | CC-MAIN-2018-51 | refinedweb | 488 | 62.64 |
Getting Started with Streaming in Python
Getting Started with Plotly Streaming
If you want to skip ahead to other streaming examples, you can go to any of the following links:
Check which version is installed on your machine and please upgrade if needed.
import plotly plotly.__version__
'1.9.10'
Now let's load the dependencies/packages that we need in order to get a simple stream going.
import numpy as np import plotly.plotly as py import plotly.tools as tls import plotly.graph_objs as go
Before you start streaming, you're going to need some stream tokens. You will need one unique stream token for every
trace object you wish to stream to. Thus if you have two traces that you want to plot and stream, you're going to require two unique stream tokens. Notice that more tokens can be added via the settings section of your Plotly profile:
Now in the same way that you set your credentials, as shown in Getting Started, you can add stream tokens to your credentials file.
stream_ids = tls.get_credentials_file()['stream_ids'] print stream_ids
[u'a3yx8ev3pg', u'2w50b45d0z', u'cew1sbgo4s', u'nhlxf6ig3d', u'n9s75hv9ic', u'96kd717ava', u'v6f5oeb8ut', u'4lm5a0gsr8', u'0xhh453c6m']
You'll see that
stream_ids will contain a list of the stream tokens we added to the credentials file.
Now that you have some stream tokens to play with, we're going to go over how we're going to put these into action. There are two main objects that will be created and used for streaming:
- Stream Id Object
- Stream link Object
We're going to look at these objects sequentially as we work through our first streaming example. For our first example, we're going to be streaming random data to a single scatter trace, and get something that behaves like the following:
The
Stream Id Object comes bundled in the
graph_objs package. We can then call help to see the description of this object:
help(go.Stream)
Help on class Stream in module plotly.graph_objs.graph_objs: class Stream(PlotlyDict) | Valid attributes for 'stream' at path [] under parents (): | | ['token', 'maxpoints'] | | Run `<stream-object>.help('attribute')` on any of the above. | '<stream-object>' is the object at [] | | Method resolution order: | Stream | PlotlyDict | __builtin__.dict | PlotlyBase | __builtin__.object | | Methods inherited from PlotlyDict: | | __copy__(self) | | __deepcopy__(self, memodict={}) | | __dir__(self) | Dynamically return the existing and possible attributes. | | __getattr__(self, key) | Python only calls this when key is missing! | | __getitem__(self, key) | Calls __missing__ when key is not found. May mutate object. | | __init__(self, *args, **kwargs) | | __missing__(self, key) | Mimics defaultdict. This is called from __getitem__ when key DNE. | | __setattr__(self, key, value) | Maps __setattr__ onto __setitem__ | | __setitem__(self, key, value, _raise=True) | Validates/Converts values which should be Graph Objects. | | force_clean(self, **kwargs) | Recursively remove empty/None values. | | get_data(self, flatten=False) | Returns the JSON for the plot with non-data elements stripped. | | get_ordered(self, **kwargs) | Return a predictable, OrderedDict version of self. | | help(self, attribute=None, return_help=False) | Print help string for this object or an attribute of this object. | | :param (str) attribute: A valid attribute string for this object. | :param (bool) return_help: Return help_string instead of printing it? | :return: (None|str) | | strip_style(self) | Recursively strip style from the current representation. | | All PlotlyDicts and PlotlyLists are guaranteed to survive the | stripping process, though they made be left empty. This is allowable. | | Keys that will be stripped in this process are tagged with | `'type': 'style'` in graph_objs_meta.json. Note that a key tagged as | style, but with an array as a value may still be considered data. | | to_string(self, level=0, indent=4, eol='\n', pretty=True, max_chars=80) | Returns a formatted string showing graph_obj constructors. | | :param (int) level: The number of indentations to start with. | :param (int) indent: The indentation amount. | :param (str) eol: The end of line character(s). | :param (bool) pretty: Curtail long list output with a '..' ? | :param (int) max_chars: The max characters per line. | | Example: | | print(obj.to_string()) | | update(self, dict1=None, **dict2) | Update current dict with dict1 and then dict2. | | This recursively updates the structure of the original dictionary-like | object with the new entries in the second and third objects. This | allows users to update with large, nested structures. | | Note, because the dict2 packs up all the keyword arguments, you can | specify the changes as a list of keyword agruments. | | Examples: | # update with dict | obj = Layout(title='my title', xaxis=XAxis(range=[0,1], domain=[0,1])) | update_dict = dict(title='new title', xaxis=dict(domain=[0,.8])) | obj.update(update_dict) | obj | {'title': 'new title', 'xaxis': {'range': [0,1], 'domain': [0,.8]}} | | # update with list of keyword arguments | obj = Layout(title='my title', xaxis=XAxis(range=[0,1], domain=[0,1])) | obj.update(title='new title', xaxis=dict(domain=[0,.8])) | obj | {'title': 'new title', 'xaxis': {'range': [0,1], 'domain': [0,.8]}} | | This 'fully' supports duck-typing in that the call signature is | identical, however this differs slightly from the normal update | method provided by Python's dictionaries. | | ---------------------------------------------------------------------- | Data descriptors inherited from PlotlyDict: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Methods inherited from __builtin__.dict: | | _ | | __gt__(...) | x.__gt__(y) <==> x>y | | __iter__(...) | x.__iter__() <==> iter(x) | | __le__(...) | x.__le__(y) <==> x<=y | | __len__(...) | x.__len__() <==> len(x) | | __lt__(...) | x.__lt__(y) <==> x<y | | __ne__(...) | x.__ne__(y) <==> x!=y | | __repr__(...) | x.__repr__() <==> repr(x) | | _ inherited from __builtin__.dict: | | __hash__ = None | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T | | ---------------------------------------------------------------------- | Methods inherited from PlotlyBase: | | to_graph_objs(self, **kwargs) | Everything is cast into graph_objs. Here for backwards compat. | | validate(self) | Everything is *always* validated now. keep for backwards compat.
As we can see, the
Stream Id Object is a dictionary-like object that takes two parameters, and has all the methods that are assoicated with dictionaries.
We will need one of these objects for each of trace that we wish to stream data to.
We'll now create a single stream token for our streaming example, which will include one scatter trace.
# Get stream id from stream id list stream_id = stream_ids[0] # Make instance of stream id object stream_1 = go.Stream( token=stream_id, # link stream id to 'token' key maxpoints=80 # keep a max of 80 pts on screen )
The
'maxpoints' key sets the maxiumum number of points to keep on the plotting surface at any given time.
More over, if you want to avoid the use of these
Stream Id Objects, you can just create a dictionary with at least the token parameter defined, for example:
stream_1 = dict(token=stream_id, maxpoints=60)
Now that we have our
Stream Id Object ready to go, we can set up our plot. We do this in the same way that we would any other plot, the only thing is that we now have to set the stream parameter in our trace object.
# Initialize trace of streaming plot by embedding the unique stream_id trace1 = go.Scatter( x=[], y=[], mode='lines+markers', stream=stream_1 # (!) embed stream id, 1 per trace ) data = go.Data([trace1])
Then, add a title to the layout object and initialize your Plotly streaming plot:
# Add title to layout object layout = go.Layout(title='Time Series') # Make a figure object fig = go.Figure(data=data, layout=layout) # Send fig to Plotly, initialize streaming plot, open new tab py.iplot(fig, filename='python-streaming')
The Stream Link Object is what will be used to communicate with the Plotly server in order to update the data contained in your trace objects. This object is in the
plotly.plotly object, an can be reference with
py.Stream
help(py.Stream) # run help() of the Stream link object
Help on class Stream in module plotly.plotly.plotly: class Stream | Interface to Plotly's real-time graphing API. | | Initialize a Stream object with a stream_id | found in. | Real-time graphs are initialized with a call to `plot` that embeds | your unique `stream_id`s in each of the graph's traces. The `Stream` | interface plots data to these traces, as identified with the unique | stream_id, in real-time. | Every viewer of the graph sees the same data at the same time. | | View examples and tutorials here: | | | Stream example: | # Initialize a streaming graph | # by embedding stream_id's in the graph's traces | import plotly.plotly as py | from plotly.graph_objs import Data, Scatter, Stream | stream_id = "your_stream_id" # See | py.plot(Data([Scatter(x=[], y=[], | stream=Stream(token=stream_id, maxpoints=100))])) | # Stream data to the import trace | stream = Stream(stream_id) # Initialize a stream object | stream.open() # Open the stream | stream.write(dict(x=1, y=1)) # Plot (1, 1) in your graph | | Methods defined here: | | __init__(self, stream_id) | Initialize a Stream object with your unique stream_id. | Find your stream_id at. | | For more help, see: `help(plotly.plotly.Stream)` | or see examples and tutorials here: | | | close(self) | Close the stream connection to plotly's streaming servers. | | For more help, see: `help(plotly.plotly.Stream)` | or see examples and tutorials here: | | | heartbeat(self, reconnect_on=(200, '', 408)) | Keep stream alive. Streams will close after ~1 min of inactivity. | | If the interval between stream writes is > 30 seconds, you should | consider adding a heartbeat between your stream.write() calls like so: | >>> stream.heartbeat() | | open(self) | Open streaming connection to plotly. | | For more help, see: `help(plotly.plotly.Stream)` | or see examples and tutorials here: | | | write(self, trace, layout=None, validate=True, reconnect_on=(200, '', 408)) | Write to an open stream. | | Once you've instantiated a 'Stream' object with a 'stream_id', | you can 'write' to it in real time. | | positional arguments: | trace - A valid plotly trace object (e.g., Scatter, Heatmap, etc.). | Not all keys in these are `stremable` run help(Obj) on the type | of trace your trying to stream, for each valid key, if the key | is streamable, it will say 'streamable = True'. Trace objects | must be dictionary-like. | | keyword arguments: | layout (default=None) - A valid Layout object | Run help(plotly.graph_objs.Layout) | validate (default = True) - Validate this stream before sending? | This will catch local errors if set to | True. | | Some valid keys for trace dictionaries: | 'x', 'y', 'text', 'z', 'marker', 'line' | | Examples: | >>> write(dict(x=1, y=2)) # assumes 'scatter' type | >>> write(Bar(x=[1, 2, 3], y=[10, 20, 30])) | >>> write(Scatter(x=1, y=2, text='scatter text')) | >>> write(Scatter(x=1, y=3, marker=Marker(color='blue'))) | >>> write(Heatmap(z=[[1, 2, 3], [4, 5, 6]])) | | The connection to plotly's servers is checked before writing | and reconnected if disconnected and if the response status code | is in `reconnect_on`. | | For more help, see: `help(plotly.plotly.Stream)` | or see examples and tutorials here: |
You're going to need to set up one of these stream link objects for each trace you wish to stream data to.
Below we'll set one up for the scatter trace we have in our plot.
# We will provide the stream link object the same token that's associated with the trace we wish to stream to s = py.Stream(stream_id) # We then open a connection s.open()
We can now use the Stream Link object
s in order to
stream data to our plot.
As an example, we will send a time stream and some random numbers:
# (*) Import module keep track and format current time import datetime import time i = 0 # a counter k = 5 # some shape parameter # Delay start of stream by 5 sec (time to switch tabs) time.sleep(5) while True: # Current time on x-axis, random numbers on y-axis x = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') y = (np.cos(k*i/50.)*np.cos(i/50.)+np.random.randn(1))[0] # Send data to your plot s.write(dict(x=x, y=y)) # Write numbers to stream to append current data on plot, # write lists to overwrite existing data on plot time.sleep(1) # plot a point every second # Close the stream when done plotting s.close()
Below you can see an example of the same plot, but streaming indefinitely instead of just 200 points.
Note that the time points correspond to the internal clock on the servers, which is in UTC time.
# Embed never-ending time series streaming plot tls.embed('streaming-demos','12')
Anyone can view your streaming graph in real-time. All viewers will see the same data simultaneously (try it! Open up this notebook up in two different browser windows and observer that the graphs are plotting identical data!).
In summary, these are the steps required in order to start streaming to a trace object:
- Make a
stream id object(
Streamin the
plotly.graph_objsmodule) containing the
streaming token(which is found in the settings of your Plotly account) and the maximum number of points to be keep on screen (which is optional).
- Provide the
stream id objectas the key value for the
streamattribute in your trace object.
- Make a
stream link object(
py.Stream) containing the same stream token as the
stream id objectand open the stream with the
.open()method.
- Write data to the plot/your trace with the
.write()method. When done, close the stream with the
.close()method. | https://plot.ly/python/streaming-tutorial/ | CC-MAIN-2017-43 | refinedweb | 2,196 | 66.23 |
Static code reviews aimed at eating bugs (!) are unbiased and neutral. If you spill coffee on their laps or are applying for the same job as them, the advice given back will remain the same. Static code reviews work via rules; some rules are accurate in their assessment and others are not so relevant--or even false. Before building a thorough infrastructure for large-scale deployment, it is well worth installing the tool's respective plugins. You can have a lot of fun kicking the tires of the rule sets for your own particular environment. Getting your fingers into the reality of the code is the first step in the path to Quality Assurance enlightenment. Note to self, remember to ask boss for pay rise.
Note: this is Part 2. Feel free to read Part 1!
Did I also mention the satisfaction involved when splattering bugs?
Assumptions
The examples in this article have been run both on Ubuntu 7.10 and (sorry to say) Windows Vista. PMD and FindBugs are platform agnostic and require Java 1.5 to run. PMD reads the source code and works with most versions of Java. FindBugs uses BCEL to read the meta information from class files, and can therefore read any versions of compiled code. The relevant links are:
TFTP
One of the easiest places to start learning is through visual feedback from within the Eclipse IDE, The Test Performance Tools Platform (TFTP), a top-level eclipse project, has an inbuilt static code review functionality. At the time of writing TFTP includes 72 helpful definitions. For most Eclipse installations you will need to use the usual update mechanism: Help→software updates.
To analyse the code, right click on any piece of code in the Package explorer window, as described in figure 1, and select the Analysis→Open Analysis dialog. The dialog is obvious. Select the project you want analyzed and the rule sets you wish to activate. Finally, press the Analysis button.
Figure 1, shows the main screen of the default Java perspective after analyzing a deliberately weak piece of code. If you click on the green flag on the left-hand side of the source code dialog, you will find an option (or options) to quick fix the selected issue.
Roll up, roll up, and watch the magic of static code analysis at work. Listing 1 is the original code. With untrained eyes and time constraints, you may well miss the fact that
name.equals() will always throw a runtime exception and that
String constants are hidden in the code rather than concentrated at the top of the class.
public class EvenCleverPeople { public static void main(String[] args) { String name=null; if (name.equals("Admin")){ System.out.println("Hi special user"); } } }
Listing 1: Code gone bad
Analyzing and quick fixing via the TFTP framework transforms the code to a stable (and maintainable) listing 2. I particularly like the
ADMIN.equals(name) as
ADMIN excellently describes the constant and never inconveniently throws a
nullpointer exception: at worst it only returns a Boolean false.
public class EvenCleverPeople { private static final String ADMIN = "Admin"; private static final String CONSTANT = "Hi special user"; //$NON-NLS-1$ public static void main(String[] args) { String name=null; if (ADMIN.equals( name )){ System.out.println(CONSTANT); } } }
Listing 2: More maintainable and less runtime prone code
If you are not sure of a rule, you should run the "quick fix" procedure: it's a brilliant way to learn; plus, the actions in most cases are sensible and help form good habits. (No, I do not have any bad habits!) At the time of writing 72 rules exist; this is a somewhat more limited subset than either PMD or FindBugs.
FindBugs
The quality of the rules are consistent between the three projects. However, if I had to vote I would consider that FindBugs generates fewer false positives than the rest. Better still, FindBugs finds a few of the more painful gotchas, especially at the high priority levels, and in particular for the correctness category. I strongly suspect that all the tools are strong and have real meaning within a well-balanced development ecosphere.
To install Findbugs please use the usual Help→Software updates section; the site for updates is:
To activate FindBugs, again right click on a project in the Package explorer dialog. A Find bugs option will appear. Choose FindBugs→FindBugs. Within a very short period of time the code is analyzed and the issues are marked with an attractive bug-like icon. The bug is ready now to be hit with a large stone. I do like the squelchy noise very much: one less potential phone call. Right clicking on the icon and then selecting Show Bug Descriptions brings up the definition of the issue, as shown in figure 2.
The bug is ready now to be hit with a large stone. I do like the squelchy noise very much
PMD
The PMD plugin is also installable via the Help→Software updates option. The site you will need to add is:
PMD works exactly as expected: after installing it, right click on the package explorer on the relevant project of choice and then select PMD→Check Code with PMD. For our example code, a wide set of bug pattern potential issues are flagged. To generate an HTMLized report, as shown in figure 3, select PMD→Generate Reports.
Another powerful extra included with the PMD installation is its ability to find code that has been copied from elsewhere in the project. Copied code (or "duplicated code"), especially for object orientated languages, is a sign of the need to refactor. Refactoring, for example, by pulling the copied code into a utility or parent class.
Copied code, sorry duplicated code, especially for object orientated languages, is a generic sign of the need to refactor
Conclusion
In summary, each tool is a significant help in the fight for code quality. TFTP has the very handy quick fix option and FindBugs has a very accurate and wide ranging set of rules and workflow. PMD has a wide range of rules, report generation and the ability to spot code duplication. I see the combination of PMD, FindBugs and TFTP much stronger together than as individual Eclipse extensions.
In the next article I will briefly introduce you to the command line use of FindBugs, useful in large scale projects. Better still, I will also interview Professor Bill Pugh, one of the main driving forces behind FindBugs.
Acknowledgments
I would like to thank my wife Hester vander Heijden for at least trying to rewrite some of my known issues, and the Eclipse, FindBugs and PMD teams for building such excellent products.
Typo
The project is actually TPTP and not TFTP(a separate and commonly used acronym). The article is otherwise very useful and timely, thanks much to Alan for his work in this area. | http://www.freesoftwaremagazine.com/comment/76418 | CC-MAIN-2015-32 | refinedweb | 1,146 | 62.88 |
Proving a Forged Signature — The Fail-stop Signature Method
I did a pre-interview with the mighty Torben P Pedersen (famous for the Pedersen Commitment) [here], and will be following up with a full interview, soon. Torben has contributed so much to cryptography of the decades, so let’s take a look at his work on fail-stop signatures:
At the time, Torben was at Aarhus University in Denmark, and Engene at CWI in Amsterdam [here]. With the fail-stop signature, a forgery can be detected, and then the signing mechanism no longer used. We have various properties for this:
- If Alice has signed a message, Bob should be able to accept it.
- Eve cannot forge the signature, without going costly work.
- If Eve manages to create a forgery, Alice can prove with a proof-of-sorgery.
- Alice cannot produce a signature which at a future time will be marked as a forgery.
So, how do you detect a forger? Well, get them to do something that is valid, but to become valid, there’s a few different options that the forger could use to make the fake. If there are lots of options to select from, the forger is unlikely to pick the right one, and we’ll be able to detect a forger a work.
With the van Heijst-Pedersen meethod [1], the generation of the keys is split between the TTP (trusted third partner) and Alice. The TTP generates two prime numbers q and p, and where q divides into p−1. Next the TTP selects a generator value (g) and computes α) such that:
Next select a random value of a from 0 to q−1 and computes:
The TTP sends (p,q,α,β) to Alice. Alice now selects four random values (x1,x2,y1,y2) . She then computes:
Alice creates a signature for message (M) with:
The signatures is then (sig1,sig2). Bob verifiers with:
If v1 is equal to v2 is signature is correct. The signature proof is:
This method is a one time signing scheme.
Detecting the forgery
Now for the elements of the public key (β1,β2), we can have other possible values for x′1,x′2,y′1,y′2. A forger will try to generate the values of β1 and β2 with x′1,x′2,y′1,y′2 . In the following the forger can discover the alternative values:}")
The forger can then publish x′1,x′2,y′1,y′2 and signfake1(s′1) and signfake2(s′2) and it will appear valid. The fake is detected by computing:
The coding is here:
import random
import libnum
import sympyfrom Crypto.Util.number import getPrime
from Crypto.Random import get_random_bytesimport sysprimebits=8if (len(sys.argv)>1):
primebits=int(sys.argv[1])if primebits>128: primebits=128isprime=False# For q, search for a prime q that is a factor of p-1while (isprime==False):
p = getPrime(primebits, randfunc=get_random_bytes)
q = p//2
if (sympy.isprime(q) and sympy.gcd(q,p-1)>1): isprime=Truealpha=1
while (alpha==1):
g=3
alpha = pow(g,(p-1)//q,p)a=random.randint(1,q-1)
beta=pow(alpha,a,p)m=10x1 = random.randint(1,q-1)
x2 = random.randint(1,q-1)
y1 = random.randint(1,q-1)
y2 = random.randint(1,q-1)print("\nAlice's private key:")
print (f"x1={x1}, x2={x2}, y1={y1}, y2={x2} ")beta1 = (pow(alpha,x1,p)*pow(beta,x2,p)) % p
beta2 = (pow(alpha,y1,p)*pow(beta,y2,p)) % pprint("\nAlice's public key:")
print (f"p={p}, q={q}, alpha={alpha}, beta={beta}, beta1={beta1}, beta2={beta2}")sig1 = (x1+ m*y1) % q
sig2 = (x2+m*y2) % qprint (f"\nx1={x1}, x2={x2}")
print (f"y1={y1}, y2={y2}")
print (f"\nSig1={sig1}, Sig2={sig2}")v1=(beta1*pow(beta2,m,p)) % p
v2=(pow(alpha,sig1,p)*pow(beta,sig2,p)) % pprint (f"v1={v1}, v2={v2}")
if (v1==v2): print("Signature checks okay")
else: print("Bad signature")# ===== Fake
if (primebits>8): sys.exit()
print ("\n\nNow let's generate a fake..."}")s1diff= (sig1-sig1fake)%q
s2diff= libnum.invmod(sig2-sig2fake,q)aval=(s1diff * s2diff) % qprint (f"aval={aval}, a={a}")
A sample run is:
Alice's public key:
172416440120879 86208220060439 9 3Alice's private key:
a: 32435590251523
Sigs 57589080246324 79290697369458
v1= 74539090295259 v2= 74539090295259
If we use 8-bit primes, the program searches for a fake value of the private key. Here is a run:
Alice's private key:
x1=47, x2=74, y1=69, y2=74 Alice's public key:
p=179, q=89, alpha=9, beta=147, beta1=173, beta2=146x1=47, x2=74
y1=69, y2=52Sig1=25, Sig2=60
v1=16, v2=16
Signature checks okay
Now let's generate a fake...x1=1, x2=32
y1=1, y2=17Sig1=11, Sig2=24
aval=35, a=54
Here is a demo:
Fail-stop signature
Back] A fail-stop signature allows Alice to prove that a signature that looks like she has signed, has not actually…
asecuritysite.com
and the code:
References
[1] van Heijst, E., Pedersen, T. P., & Pfitzmann, B. (1992, August). New constructions of fail-stop signatures and lower bounds. In Annual International Cryptology Conference (pp. 15–30). Springer, Berlin, Heidelberg [here]. | https://medium.com/asecuritysite-when-bob-met-alice/proving-a-forged-signature-the-fail-stop-signature-method-b6fed24a8d0c?source=collection_home---4------4----------------------- | CC-MAIN-2020-50 | refinedweb | 880 | 63.39 |
Porting Your iOS App to macOS
If you’re developing apps for iOS, you already have a particular set of skills that you can use to write apps for another platform – macOS!
If you’re like most developers, you don’t want to have to write your app twice just to ship your app on a new platform, as this can take too much time and money. But with a little effort, you can learn how to port iOS apps to macOS, reusing a good portion of your existing iOS app, and only rewriting the portions that are platform-specific.
In this tutorial, you’ll learn how to create an Xcode project that is home to both iOS and macOS, how to refactor your code for reuse on both platforms, and when it is appropriate to write platform specific code.
To get the most out of this tutorial you should be familiar with NSTableView. If you need to refresh your knowledge we have an introduction for you.
Getting Started
For this tutorial, you’ll need to download the starter project here.
The sample project is a version of the BeerTracker app used in previous tutorials. It allows you to keep a record of beers you’ve tried, along with notes, ratings, and images of the beers. Build and run the app to get a feel for how it works.
Since the app is only available on iOS, the first step to porting the app for macOS is to create a new target. A target simply is a set of instructions telling Xcode how to build your application. Currently, you only have an iOS target, which contains all the information needed to build your app for an iPhone.
Select the BeerTracker project at the top of the Project Navigator. At the bottom of the Project and Targets list, click the + button.
This will present a window for you to add a new target to your project. At the top of the window, you’ll see tabs representing the different categories of platforms supported. Select macOS, then scroll down to Application and choose Cocoa App. Name the new target BeerTracker-mac.
Adding the Assets
In the starter app you downloaded, you’ll find a folder named BeerTracker Mac Icons. You’ll need to add the App Icons to AppIcon in Assets.xcassets found under the BeerTracker-mac group. Also add beerMug.pdf to Assets.xcassets. Select beerMug, open the Attributes Inspector and change the Scales to Single Scale. This ensures you don’t need to use different scaled images for this asset.
When you’re done, your assets should look like this:
In the top left of the Xcode window, select the BeerTracker-mac scheme in the scheme pop-up. Build and run, and you’ll see an empty window. Before you can start adding the user interface, you’ll need to make sure your code doesn’t have any conflicts between UIKit, the framework used on iOS, and AppKit, the framework used by macOS.
Separation of Powers
The Foundation framework allows your app to share quite a bit of code, as it is universal to both platforms. However, your UI cannot be universal. In fact, Apple recommends that multi-platform applications should not attempt to share UI code, as your secondary platform will begin to take on the appearance of your initial application’s UI.
iOS has some fairly strict Human Interface Guidelines that ensure your users are able to read and select elements on their touchscreen devices. However, macOS has different requirements. Laptops and desktops have a mouse pointer to click and select, allowing elements on the screen to be much smaller than would be possible on a phone.
Having identified the UI as needing to be different on both platforms, it is also important to understand what other components of your code can be reused, and which ones need to be rewritten. Keep in mind that there isn’t necessarily a definitive right or wrong answer in most of these cases, and you will need to decide what works best for your app. Always remember that the more code shared, the less code you need to test and debug.
Generally, you’ll be able to share models and model controllers. Open Beer.swift, and open the Utilities drawer in Xcode, and select the File Inspector. Since both targets will use this model, under Target Membership, check BeerTracker-mac leaving BeerTracker still checked. Do the same thing for BeerManager.swift, and SharedAssets.xcassets under the Utilities group.
If you try to build and run, you will get a build error. This is because Beer.swift is importing UIKit. The model is using some platform specific logic to load and save images of beers.
Replace the import line at the top of the file with the following:
import Foundation
If you try to build and run, you’ll see the app no longer compiles due to UIImage being part of the now removed UIKit. While the model portion of this file is shareable between both targets, the platform specific logic will need to be separated out. In Beer.swift, delete the entire extension marked Image Saving. After the
import statement, add the following protocol:
protocol BeerImage { associatedtype Image func beerImage() -> Image? func saveImage(_ image: Image) }
Since each target will still need access to the beer’s image, and to be able to save images, this protocol provides a contract that can be used across the two targets to accomplish this.
Models
Create a new file by going to File/New/File…, select Swift File, and name it Beer_iOS.swift. Ensure that only the BeerTracker target is checked. After that, create another new file named Beer_mac.swift, this time selecting BeerTracker-mac as the target.
Open Beer_iOS.swift, delete the file’s contents, and add the following:
import UIKit // MARK: - Image Saving extension Beer: BeerImage { // 1. typealias Image = UIImage // 2. func beerImage() -> Image? { guard let imagePath = imagePath, let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first else { return #imageLiteral(resourceName: "beerMugPlaceholder") } // 3. let pathName = (path as NSString).appendingPathComponent("BeerTracker/\(imagePath)") guard let image = Image(contentsOfFile: pathName) else { return #imageLiteral(resourceName: "beerMugPlaceholder") } return image } // 4. func saveImage(_ image: Image) { guard let imgData = UIImageJPEGRepresentation(image, 0.5), let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first else { return } let appPath = (path as NSString).appendingPathComponent("/BeerTracker") let fileName = "\(UUID().uuidString).jpg" let pathName = (appPath as NSString).appendingPathComponent(fileName) var isDirectory: ObjCBool = false if !FileManager.default.fileExists(atPath: appPath, isDirectory: &isDirectory) { do { try FileManager.default.createDirectory(atPath: pathName, withIntermediateDirectories: true, attributes: nil) } catch { print("Failed to create directory: \(error)") } } if (try? imgData.write(to: URL(fileURLWithPath: pathName), options: [.atomic])) != nil { imagePath = fileName } } }
Here’s what’s happening:
- The BeerImage protocol requires the implementing class to define an associated type. Think of this as a placeholder name for the type of object you really want to use, based on your object’s needs. Since this file is for iOS, you’re using UIImage.
- Implement the first protocol method. Here, the Image type represents UIImage.
- Another example of how the type alias can be used when initializing an image.
- Implement the second protocol method to save an image.
Switch your scheme to BeerTracker, then build and run. The application should behave as before.
Now that your iOS target is working, you’re ready to add macOS-specific code. Open Beer_mac.swift, delete all the contents, and add the following code:
import AppKit // MARK: - Image Saving extension Beer: BeerImage { // 1. typealias Image = NSImage func beerImage() -> Image? { // 2. guard let imagePath = imagePath, let path = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first else { return #imageLiteral(resourceName: "beerMugPlaceholder") } let pathName = (path as NSString).appendingPathComponent(imagePath) guard let image = Image(contentsOfFile: pathName) else { return #imageLiteral(resourceName: "beerMugPlaceholder") } return image } func saveImage(_ image: Image) { // 3. guard let imgData = image.tiffRepresentation, let path = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first else { return } let fileName = "/BeerTracker/\(UUID().uuidString).jpg" let pathName = (path as NSString).appendingPathComponent(fileName) if (try? imgData.write(to: URL(fileURLWithPath: pathName), options: [.atomic])) != nil { imagePath = fileName } } }
The above code is nearly identical to the previous code, with just a few changes:
- Here, instead of using UIImage, you’re using the AppKit specific class NSImage.
- On iOS, it’s common to save files in the Documents directory. You usually don’t have to worry about cluttering up this directory, since it is specific to the app and hidden from the user. On macOS, however, you won’t want to not mess up the user’s Documents, so you save the app’s files to the Application Support directory.
- Since NSImage doesn’t have the same method for getting image data as UIImage, you’re using the supported
tiffRepresentation.
Switch your target to BeerTracker_mac, then build and run. Your app now compiles for both platforms, while maintaining a standard set of functionality from your model.
Creating the User Interface
Your empty view Mac app isn’t very useful, so it’s time to build the UI. From the BeerTracker-mac group, open Main.storyboard. Start by dragging a Table View into your empty view. Now select the Table View in the Document Outline.
macOS storyboards sometimes require you to dig down a bit deeper into the view hierarchy. This is a change from iOS, where you’re used to seeing all template views at the top level.
Configuring the Table View
With the Table View selected, make the following changes in the Attributes Inspector:
- Set Columns to 1
- Uncheck Reordering
- Uncheck Resizing
Select the Table Column in the Document Outline and set its Title to Beer Name.
In the Document Outline, select the Bordered Scroll View (which houses the Table View), and in the Size Inspector find the View section and set the View dimensions to the following:
- x: 0
- y: 17
- width: 185
- height: 253
Setting the coordinates is going to be slightly different here, as well. In macOS, the origin of the UI is not in the top left, but the lower left. Here, you’ve set the y coordinate to 17, which means 17 points up from the bottom.
Adding a Delegate and Data Source
Next you’ll need to connect your delegate, data source and properties for the Table View. Again, you’ll need to select the Table View from the Document Outline to do this. With it selected, you can Control-drag to the View Controller item in the Document Outline and click delegate. Repeat this for the dataSource.
Open ViewController.swift in the Assistant Editor, Control-drag from the Table View and create a new outlet named
tableView.
Before you finish with the Table View, there’s one last thing you need to set. Back in the Document Outline, find the item named Table Cell View. With that selected, open the Identity Inspector, and set the Identifier to NameCell.
Images and Text
With the Table View setup, next comes the “form” section of the UI.
First, you’ll add an Image Well to the right of the table. Set the frame to the following:
- x: 190
- y: 188
- width: 75
- height: 75
An Image Well is a convenient object that displays an image, but also allows a user to drag and drop a picture onto it. To accomplish this, the Image Well has the ability to connect an action to your code!
Open the BeerTracker-mac ViewController.swift in the Assistant Editor and create an outlet for the Image Well named
imageView. Also create an action for the Image View, and name it
imageChanged. Ensure that you change Type to NSImageView, as shown:
While drag and drop is great, sometimes users want to be able to view an Open Dialog and search for the file themselves. Set this up by dropping a Click Gesture Recognizer on the Image Well. In the Document Outline, connect an action from the Click Gesture Recognizer to ViewController.swift named
selectImage.
Add a Text Field to the right of the Image Well. In the Attributes Inspector, change the Placeholder to Enter Name. Set the frame to the following:
- x: 270
- y: 223
- width: 190
- height: 22
Create an outlet in ViewController.swift for the Text Field named
nameField.
Rating a Beer
Next, add a Level Indicator below the name field. This will control setting the rating of your beers. In the Attributes Inspector, set the following:
- Style: Rating
- State: Editable
- Minimum: 0
- Maximum: 5
- Warning: 0
- Critical: 0
- Current: 5
- Image: beerMug
Set the frame to the following:
- x: 270
- y: 176
- width: 115
Create an outlet for the Level Indicator named
ratingIndicator.
Add a Text View below the rating indicator. Set the frame to:
- x: 193
- y: 37
- width: 267
- height: 134
To create an outlet for the Text View, you’ll need to make sure you select Text View inside the Document Outline, like you did with the Table View. Name the outlet
noteView. You’ll also need to set the Text View‘s delegate to the ViewController.
Below the note view, drop in a Push Button. Change the title to Update, and set the frame to:
- x: 284
- y: 3
- width: 85
Connect an action from the button to ViewController named
updateBeer.
Adding and Removing Beers
With that, you have all the necessary controls to edit and view your beer information. However, there’s no way to add or remove beers. This will make the app difficult to use, even if your users haven’t had anything to drink. :]
Add a Gradient Button to the bottom left of the screen. In the Attributes Inspector, change Image to NSAddTemplate if it is not already set.
In the Size Inspector, set the frame to:
- x: 0
- y: -1
- width: 24
- height: 20
Add an action from the new button named
addBeer.
One great thing about macOS is that you get access to template images like the + sign. This can make your life a lot simpler when you have any standard action buttons, but don’t have the time or ability to create your own artwork.
Next, you’ll need to add the remove button. Add another Gradient Button directly to the right of the previous button, and change the Image to NSRemoveTemplate. Set the frame to:
- x: 23
- y: -1
- width: 24
- height: 20
And finally, add an action from this button named
removeBeer.
Finishing The UI
You’re almost finished building the UI! You just need to add a few labels to help polish it off.
Add the following labels:
- Above the name field, titled Name.
- Above the rating indicator titled Rating.
- Above the notes view titled Notes.
- Beneath the table view titled Beer Count:.
- To the right of the beer count label, titled 0.
For each of these labels, in the Attributes Inspector, set the font to Other – Label, and the size to 10.
For the last label, connect an outlet to ViewController.swift named
beerCountField.
Make sure your labels all line like so:
Click the Resolve Auto Layout Issues button and in the All Views in View Controller section click Reset to Suggested Constraints.
Adding the Code
Whew! Now you’re ready to code. Open ViewController.swift and delete the property named
representedObject. Add the following methods below
viewDidLoad():
private func setFieldsEnabled(enabled: Bool) { imageView.isEditable = enabled nameField.isEnabled = enabled ratingIndicator.isEnabled = enabled noteView.isEditable = enabled } private func updateBeerCountLabel() { beerCountField.stringValue = "\(BeerManager.sharedInstance.beers.count)" }
There are two methods that will help you control your UI:
setFieldsEnabled(_:)will allow you to easily turn off and on the ability to use the form controls.
updateBeerCountLabel()simply sets the count of beers in the
beerCountField.
Beneath all of your outlets, add the following property:
var selectedBeer: Beer? { didSet { guard let selectedBeer = selectedBeer else { setFieldsEnabled(enabled: false) imageView.image = nil nameField.stringValue = "" ratingIndicator.integerValue = 0 noteView.string = "" return } setFieldsEnabled(enabled: true) imageView.image = selectedBeer.beerImage() nameField.stringValue = selectedBeer.name ratingIndicator.integerValue = selectedBeer.rating noteView.string = selectedBeer.note! } }
This property will keep track of the beer selected from the table view. If no beer is currently selected, the setter takes care of clearing the values from all the fields, and disabling the UI components that shouldn’t be used.
Replace
viewDidLoad() with the following code:
override func viewDidLoad() { super.viewDidLoad() if BeerManager.sharedInstance.beers.count == 0 { setFieldsEnabled(enabled: false) } else { tableView.selectRowIndexes(IndexSet(integer: 0), byExtendingSelection: false) } updateBeerCountLabel() }
Just like in iOS, you want our app to do something the moment it starts up. In the macOS version, however, you’ll need to immediately fill out the form for the user to see their data.
Adding Data to the Table View
Right now, the table view isn’t actually able to display any data, but
selectRowIndexes(_:byExtendingSelection:) will select the first beer in the list. The delegate code will handle the rest for you.
In order to get the table view showing you your list of beers, add the following code to the end of ViewController.swift, outside of the
ViewController class:
extension ViewController: NSTableViewDataSource { func numberOfRows(in tableView: NSTableView) -> Int { return BeerManager.sharedInstance.beers.count } } extension ViewController: NSTableViewDelegate { // MARK: - CellIdentifiers fileprivate enum CellIdentifier { static let NameCell = "NameCell" } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let beer = BeerManager.sharedInstance.beers[row] if let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: CellIdentifier.NameCell), owner: nil) as? NSTableCellView { cell.textField?.stringValue = beer.name if beer.name.characters.count == 0 { cell.textField?.stringValue = "New Beer" } return cell } return nil } func tableViewSelectionDidChange(_ notification: Notification) { if tableView.selectedRow >= 0 { selectedBeer = BeerManager.sharedInstance.beers[tableView.selectedRow] } } }
This code takes care of populating the table view’s rows from the data source.
Look at it closely, and you’ll see it’s not too different from the iOS counterpart found in BeersTableViewController.swift. One notable difference is that when the table view selection changes, it sends a Notification to the NSTableViewDelegate.
Remember that your new macOS app has multiple input sources — not just a finger. Using a mouse or keyboard can change the selection of the table view, and that makes handling the change just a little different to iOS.
Now to add a beer. Change
addBeer() to:
@IBAction func addBeer(_ sender: Any) { // 1. let beer = Beer() beer.name = "" beer.rating = 1 beer.note = "" selectedBeer = beer // 2. BeerManager.sharedInstance.beers.insert(beer, at: 0) BeerManager.sharedInstance.saveBeers() // 3. let indexSet = IndexSet(integer: 0) tableView.beginUpdates() tableView.insertRows(at: indexSet, withAnimation: .slideDown) tableView.endUpdates() updateBeerCountLabel() // 4. tableView.selectRowIndexes(IndexSet(integer: 0), byExtendingSelection: false) }
Nothing too crazy here. You’re simply doing the following:
- Creating a new beer.
- Inserting the beer into the model.
- Inserting a new row into the table.
- Selecting the row of the new beer.
You might have even noticed that, like in iOS, you need to call
beginUpdates() and
endUpdates() before inserting the new row. See, you really do know a lot about macOS already!
Removing Entries
To remove a beer, add the below code for
removeBeer(_:):
@IBAction func removeBeer(_ sender: Any) { guard let beer = selectedBeer, let index = BeerManager.sharedInstance.beers.index(of: beer) else { return } // 1. BeerManager.sharedInstance.beers.remove(at: index) BeerManager.sharedInstance.saveBeers() // 2 tableView.reloadData() updateBeerCountLabel() tableView.selectRowIndexes(IndexSet(integer: 0), byExtendingSelection: false) if BeerManager.sharedInstance.beers.count == 0 { selectedBeer = nil } }
Once again, very straightforward code:
- If a beer is selected, you remove it from the model.
- Reload the table view, and select the first available beer.
Handling Images
Remember how Image Wells have the ability to accept an image dropped on them? Change
imageChanged(_:) to:
@IBAction func imageChanged(_ sender: NSImageView) { guard let image = sender.image else { return } selectedBeer?.saveImage(image) }
And you thought it was going to be hard! Apple has taken care of all the heavy lifting for you, and provides you with the image dropped.
On the flip side to that, you’ll need to do a bit more work to handle user’s picking the image from within your app. Replace
selectImage() with:
@IBAction func selectImage(_ sender: Any) { guard let window = view.window else { return } // 1. let openPanel = NSOpenPanel() openPanel.allowsMultipleSelection = false openPanel.canChooseDirectories = false openPanel.canCreateDirectories = false openPanel.canChooseFiles = true // 2. openPanel.allowedFileTypes = ["jpg", "png", "tiff"] // 3. openPanel.beginSheetModal(for: window) { (result) in if result == NSApplication.ModalResponse.OK { // 4. if let panelURL = openPanel.url, let beerImage = NSImage(contentsOf: panelURL) { self.selectedBeer?.saveImage(beerImage) self.imageView.image = beerImage } } } }
The above code is how you use
NSOpenPanel to select a file. Here’s what’s happening:
- You create an
NSOpenPanel, and configure its settings.
- In order to allow the user to choose only pictures, you set the allowed file types to your preferred image formats.
- Present the sheet to the user.
- Save the image if the user selected one.
Finally, add the code that will save the data model in
updateBeer(_:):
@IBAction func updateBeer(_ sender: Any) { // 1. guard let beer = selectedBeer, let index = BeerManager.sharedInstance.beers.index(of: beer) else { return } beer.name = nameField.stringValue beer.rating = ratingIndicator.integerValue beer.note = noteView.string // 2. let indexSet = IndexSet(integer: index) tableView.beginUpdates() tableView.reloadData(forRowIndexes: indexSet, columnIndexes: IndexSet(integer: 0)) tableView.endUpdates() // 3. BeerManager.sharedInstance.saveBeers() }
Here’s what you added:
- You ensure the beer exists, and update its properties.
- Update the table view to reflect any names changes in the table.
- Save the data to the disk.
You’re all set! Build and run the app, and start adding beers. Remember, you’ll need to select Update to save your data.
Final Touches
You’ve learned a lot about the similarities and differences between iOS and macOS development. There’s another concept that you should familiarize yourself with: Settings/Preferences. In iOS, you should be comfortable with the concept of going into Settings, finding your desired app, and changing any settings available to you. In macOS, this can be accomplished inside your app through Preferences.
Build and run the BeerTracker target, and in the simulator, navigate to the BeerTracker settings in the Settings app. There you’ll find a setting allowing your users to limit the length of their notes, just in case they get a little chatty after having a few.
In order to get the same feature in your mac app, you’ll create a Preferences window for the user. In BeerTracker-mac, open Main.storyboard, and drop in a new Window Controller. Select the Window, open the Size Inspector, and change the following:
- Set Content Size width to 380, and height to 55.
- Check Minimum Content Size, and set width to 380, and height to 55.
- Check Maximum Content Size, and set width to 380, and height to 55.
- Check Full Screen Minimum Content Size, and set width to 380, and height to 55.
- Check Full Screen Maximum Content Size, and set width to 380, and height to 55.
- Under Initial Position, select Center Horizontally and Center Vertically.
Next, select the View of the empty View Controller, and change the size to match the above settings, 380 x 55.
Doing these things will ensure your Preferences window is always the same size, and opens in a logical place to the user. When you’re finished, your new window should look like this in the storyboard:
At this point, there is no way for a user to open your new window. Since it should be tied to the Preferences menu item, find the menu bar scene in storyboard. It will be easier if you drag it close to the Preferences window for this next part. Once it is close enough, do the following:
- In the menu bar in storyboard, click BeerTracker-mac to open the menu.
- Control-drag from the Preferences menu item to the new Window Controller
- Select Show from the dialog
Find a Check Box Button, and add it to the empty View Controller. Change the text to be Restrict Note Length to 1,024 Characters.
With the Checkbox Button selected, open the Bindings Inspector, and do the following:
- Expand Value, and check Bind to.
- Select Shared User Defaults Controller from the drop down.
- In Model Key Path, put BT_Restrict_Note_Length.
Create a new Swift file in the Utilities group named StringValidator.swift. Make sure to check both targets for this file.
Open StringValidator.swift, and replace the contents with the following code:
import Foundation extension String { private static let noteLimit = 1024 func isValidLength() -> Bool { let limitLength = UserDefaults.standard.bool(forKey: "BT_Restrict_Note_Length") if limitLength { return self.characters.count <= String.noteLimit } return true } }
This class will provide both targets with the ability to check if a string is a valid length, but only if the user default BT_Restrict_Note_Length is true.
In ViewController.swift add the following code at the bottom:
extension ViewController: NSTextViewDelegate { func textView(_ textView: NSTextView, shouldChangeTextIn affectedCharRange: NSRange, replacementString: String?) -> Bool { guard let replacementString = replacementString else { return true } let currentText = textView.string let proposed = (currentText as NSString).replacingCharacters(in: affectedCharRange, with: replacementString) return proposed.isValidLength() } }
Finally, change the names of each Window in Main.storyboard to match their purpose, and give the user more clarity. Select the initial Window Controller, and in the Attributes Inspector change the title to BeerTracker. Select the Window Controller for the Preferences window, and change the title to Preferences.
Build and run your app. If you select the Preferences menu item, you should now see your new Preferences window with your preferences item. Select the checkbox, and find some large amount of text to paste in. If this would make the note more 1024 characters, the Text View will not accept it, just like the iOS app.
Where to Go From Here?
You can download the finished project here.
In this tutorial you learned:
- How to utilize a current iOS project to host a macOS app.
- When to separate code based on your platform's needs.
- How to reuse existing code between both projects.
- The differences between some of Xcode's behaviors between the two platforms.
For more information about porting your apps to macOS, check out Apple's Migrating from Cocoa Touch Overview.
If you have any questions or comments, please join in the forum discussion below!
Team
Each tutorial at is created by a team of dedicated developers so that it meets our high quality standards. The team members who worked on this tutorial are:
- Author
Andy Pereira
- Tech Editor
Sarah Reichelt
- Editor
Chris Belanger
- Final Pass Editor
Jean-Pierre Distler
- Team Lead
Michael Briscoe | https://www.raywenderlich.com/161968/porting-your-ios-app-to-macos | CC-MAIN-2017-43 | refinedweb | 4,384 | 58.38 |
Aahz wrote in message ... >In article <55688f89.0311180211.7ab1bc30 at posting.google.com>, >Francis Avila <francisgavila at yahoo.com> wrote: >> >>A little annoyed one day that I couldn't use the statefulness of >>generators as "resumable functions", [...] > ><raised eyebrow> But generators *are* resumable functions; they just >don't permit injection of new values into their state. I see then that I don't need to convince you. :) But it is because you can't inject new values into their state that they are not resumable functions. They're pure state, not functions-with-persisting-state. If they were resumable functions, we could call them like functions and be returned values based upon passed parameters, except that the algorithm used would depend upon the generator's internal state. Now, the above sounds like a class, doesn't it? But yet we think of generators as functions. My post was an attempt to explain why this is so, and argue for a set of semantics based on that perception (because the PEP seems to want to regard them as classes). Generators are funny because they share properties of classes and functions, but I think they're more function-like than class-like, and that's why class-like interfaces (i.e. generator attributes) are a strange fit. >As Michele >pointed out, it's easy enough to wrap a generator in a class if you want >to monitor the changing state of an attribute. True--you simply have to use 'self' to access public values, as the PEP suggests. The only advantage the PEP has is that we don't need to wrap generators in a function to gain access to public attributes--the only reason for the wrapper class anyway is to give a namespace between global and local. Anyone can do that, so why do we need a magic __self__ attribute? So I agree, I don't like the PEP's specific proposal, but I still like the functionality it's attempting to provide. >The problem with injecting values is that there's no way to pick them >up; it's a "push" solution rather than a "pull" solution. You mean "pull" rather than "push"? Well, I just suggested a way to pick them up which is no different than how a function picks up parameters--they're pushed in rather than pulled in, by overwriting the local namespace before advancing the generator's state. Would you care to comment on my suggestion? -- Francis Avila | https://mail.python.org/pipermail/python-list/2003-November/190108.html | CC-MAIN-2016-40 | refinedweb | 414 | 63.8 |
The 10 Most Annoying Things Coming Back to Java After Some Days of Scala
The 10 Most Annoying Things Coming Back to Java After Some Days of Scala
Join the DZone community and get the full member experience.Join For Free
Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!
So, I’m experimenting with Scala because I want to write a parser, and theScala Parsers API seems like a really good fit. After all, I can implement the parser in Scala and wrap it behind a Java interface, so apart from an additional runtime dependency, there shouldn’t be any interoperability issues.
After a few days of getting really really used to the awesomeness of Scala syntax, here are the top 10 things I’m missing the most when going back to writing Java:
1. Multiline strings
That is my personal favourite, and a really awesome feature that should be in any language. Even PHP has it: Multiline strings. As easy as writing:
println ("""Dear reader, If we had this feature in Java, wouldn't that be great? Yours Sincerely, Lukas""")
Where is this useful? With SQL, of course! Here’s how you can run a plain SQL statement with jOOQ and Scala:
println( DSL.using(configuration) .fetch(""" SELECT a.first_name, a.last_name, b.title FROM author a JOIN book b ON a.id = b.author_id ORDER BY a.id, b.id """) )
And this isn’t only good for static strings. With string interpolation, you can easily inject variables into such strings:
val predicate = if (someCondition) "AND a.id = 1" else "" println( DSL.using(configuration) // Observe this little "s" .fetch(s""" SELECT a.first_name, a.last_name, b.title FROM author a JOIN book b ON a.id = b.author_id -- This predicate is the referencing the -- above Scala local variable. Neat! WHERE 1 = 1 $predicate ORDER BY a.id, b.id """) )
That’s pretty awesome, isn’t it? For SQL, there is a lot of potential in Scala.
2. Semicolons
I sincerely haven’t missed them one bit. The way I structure code (and probably the way most people structure code), Scala seems not to need semicolons at all. In JavaScript, I wouldn’t say the same thing. The interpreted and non-typesafe nature of JavaScript seems to indicate that leaving away optional syntax elements is a guarantee to shoot yourself in the foot. But not with Scala.
val a = thisIs.soMuchBetter() val b = no.semiColons() val c = at.theEndOfALine()
This is probably due to Scala’s type safety, which would make the compiler complain in one of those rare ambiguous situations, but that’s just an educated guess.
3. Parentheses
This is a minefield and leaving away parentheses seems dangerous in many cases. In fact, you can also leave away the dots when calling a method:
myObject method myArgument
Because of the amount of ambiguities this can generate, especially when chaining more method calls, I think that this technique should be best avoided. But in some situations, it’s just convenient to “forget” about the parens. E.g.
val s = myObject.toString
4. Type inference
This one is really annoying in Java, and it seems that many other languages have gotten it right, in the meantime. Java only has limited type inference capabilities, and things aren’t as bright as they could be.
In Scala, I could simply write
val s = myObject.toString
… and not care about the fact that
s is of type String. Sometimes, but onlysometimes I like to explicitly specify the type of my reference. In that case, I can still do it:
val s : String = myObject.toString
5. Case classes
I think I’d fancy writing another POJO with 40 attributes, constructors, getters, setters, equals, hashCode, and toString
— Said no one. Ever
Scala has case classes. Simple immutable pojos written in one-liners. Take the Person case class for instance:
case class Person(firstName: String, lastName: String)
I do have to write down the attributes once, agreed. But everything else should be automatic.
And how do you create an instance of such a case class? Easily, you don’t even need the
new operator (in fact, it completely escapes my imagination why
new is really needed in the first place):
Person("George", "Orwell")
That’s it. What else do you want to write to be Enterprise-compliant?
Side-note
OK, some people will now argue to use project lombok. Annotation-based code generation is nonsense and should be best avoided. In fact, many annotations in the Java ecosystem are simple proof of the fact that the Java language is – and will forever be – very limited in its evolution capabilities. Take
@Override for instance. This should be a keyword, not an annotation. You may think it’s a cosmetic difference, but I say that Scala has proven that annotations are pretty much always the wrong tool. Or have you seenheavily annotated Scala code, recently?
6. Methods (functions!) everywhere
This one is really one of the most useful features in any language, in my opinion. Why do we always have to link a method to a specific class? Why can’t we simply have methods in any scope level? Because we can, with Scala:
// "Top-level", i.e. associated with the package def m1(i : Int) = i + 1 object Test { // "Static" method in the Test instance def m2(i : Int) = i + 2 def main(args: Array[String]): Unit = { // Local method in the main method def m3(i : Int) = i + 3 println(m1(1)) println(m2(1)) println(m3(1)) } }
Right? Why shouldn’t I be able to define a local method in another method? I can do that with classes in Java:
public void method() { class LocalClass {} System.out.println(new LocalClass()); }
A local class is an inner class that is local to a method. This is hardly ever useful, but what would be really useful is are local methods.
These are also supported in JavaScript or Ceylon, by the way.
7. The REPL
Because of various language features (such as 6. Methods everywhere), Scala is a language that can easily run in a REPL. This is awesome for testing out a small algorithm or concept outside of the scope of your application.
In Java, we usually tend to do this:
public class SomeRandomClass { // [...] public static void main(String[] args) { System.out.println(SomeOtherClass.testMethod()); } // [...] }
In Scala, I would’ve just written this in the REPL:
println(SomeOtherClass.testMethod)
Notice also the always available
println method. Pure gold in terms of efficient debugging.
8. Arrays are NOT (that much of) a special case
In Java, apart from primitive types, there are also those weird things we call arrays. Arrays originate from an entirely separate universe, where we have to remember quirky rules originating from the ages of Capt Kirk (or so)
Yes, rules like:
// Compiles but fails at runtime Object[] arrrrr = new String[1]; arrrrr[0] = new Object(); // This works Object[] arrrr2 = new Integer[1]; arrrr2[0] = 1; // Autoboxing // This doesn't work Object[] arrrr3 = new int[]; // This works Object[] arr4[] = new Object[1][]; // So does this (initialisation): Object[][] arr5 = { { } }; // Or this (puzzle: Why does it work?): Object[][] arr6 = { { new int[1] } }; // But this doesn't work (assignment) arr5 = { { } };
Yes, the list could go on. With Scala, arrays are less of a special case, syntactically speaking:
val a = new Array[String](3); a(0) = "A" a(1) = "B" a(2) = "C" a.map(v => v + ":") // output Array(A:, B:, C:)
As you can see, arrays behave much like other collections including all the useful methods that can be used on them.
9. Symbolic method names
Now, this topic is one that is more controversial, as it reminds us of theperils of operator overloading. But every once in a while, we’d wish to have something similar. Something that allows us to write
val x = BigDecimal(3); val y = BigDecimal(4); val z = x * y
Very intuitively, the value of z should be
BigDecimal(12). That cannot be too hard, can it? I don’t care if the implementation of
* is really a method called
multiply() or whatever. When writing down the method, I’d like to use what looks like a very common operator for multiplication.
By the way, I’d also like to do that with SQL. Here’s an example:
select ( AUTHOR.FIRST_NAME || " " || AUTHOR.LAST_NAME, AUTHOR.AGE - 10 ) from AUTHOR where AUTHOR.ID > 10 fetch
Doesn’t that make sense? We know that
|| means concat (in some databases). We know what the meaning of
- (minus) and
> (greater than) is. Why not just write it?
The above is a compiling example of jOOQ in Scala, btw.
Attention: Caveat
There’s always a flip side to allowing something like operator overloading or symbolic method names. It can (and will be) abused. By libraries as much as by the Scala language itself.
10. Tuples
Being a SQL person, this is again one of the features I miss most in other languages. In SQL, everything is either a TABLE or a ROW. few people actually know that, and few databases actually support this way of thinking.
Scala doesn’t have ROW types (which are really records), but at least, there are anonymous tuple types. Think of rows as tuples with named attributes, whereas case classes would be named rows:
- Tuple: Anonymous type with typed and indexed elements
- Row: Anonymous type with typed, named, and indexed elements
- case class: Named type with typed and named elements
In Scala, I can just write:
// A tuple with two values val t1 = (1, "A") // A nested tuple val t2 = (1, "A", (2, "B"))
In Java, a similar thing can be done, but you’ll have to write the library yourself, and you have no language support:
class Tuple2<T1, T2> { // Lots of bloat, see missing case classes } class Tuple3<T1, T2, T3> { // Bloat bloat bloat }
And then:
// Yikes, no type inference... Tuple2<Integer, String> t1 = new Tuple2<>(1, "A"); // OK, this will certainly not look nice Tuple3<Integer, String, Tuple2<Integer, String>> t2 = new Tuple3<>(1, "A", new Tuple2<>(2, "B"));
jOOQ makes extensive use of the above technique to bring you SQL’s row value expressions to Java, and surprisingly, in most cases, you can do without the missing type inference as jOOQ is a fluent API where you never really assign values to local variables… An example:
DSL.using(configuration) .select(T1.SOME_VALUE) .from(T1) .where( // This ROW constructor is completely type safe row(T1.COL1, T1.COL2) .in(select(T2.A, T2.B).from(T2)) ) .fetch();
Conclusion
This was certainly a pro-Scala and slightly contra-Java article. Don’t get me wrong. By no means, I’d like to migrate entirely to Scala. I think that the Scala language goes way beyond what is reasonable in any useful software. There are lots of little features and gimmicks that seem nice to have, but will inevitably blow up in your face, such as:
implicitconversion. This is not only very hard to manage, it also slows down compilation horribly. Besides, it’s probably utterly impossible to implement semantic versioning reasonably using
implicit, as it is probably not possible to foresee all possible client code breakage through accidental backwards-incompatibility.
- local imports seem great at first, but their power quickly makes code unintelligible when people start partially importing or renaming types for a local scope.
- symbolic method names are most often abused. Take the parser API for instance, which features method names like
^^,
^^^,
^?, or
~!
Nonetheless, I think that the advantages of Scala over Java listed in this article could all be implemented in Java as well:
- with little risk of breaking backwards-compatibility
- with (probably) not too big of an effort, JLS-wise
- with a huge impact on developer productivity
- with a huge impact on Java’s competitiveness
In any case, Java 9 will be another promising release, with hot topics likevalue types, declaration-site variance, specialisation (very interesting!) orClassDynamic
With these huge changes, let’s hope there’s also some room for any of the above little improvements, that would add more immediate value to every day work. Lukas Eder , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/10-most-annoying-things-coming | CC-MAIN-2018-30 | refinedweb | 2,061 | 63.8 |
Feedback
Getting Started
Discussions
Site operation discussions
Recent Posts
(new topic)
Departments
Courses
Research Papers
Design Docs
Quotations
Genealogical Diagrams
Archives
I'm pleased to announce the Eastwest programming language and structure editor. This is a research project aimed at exploring how structure editors can help with functional programming. Eastwest introduces the concept of "token type", which is a useful way of handling bindings in structure editors. For beginners, the most interesting feature of Eastwest is that the type of an expression is always displayed at the top of the screen. Eastwest takes into account the type of an expression when displaying suggestions. Arguments can be placed anywhere inside function names which can be written in any character set thus opening the possibility of making source code resemble human language. The structure editor can handle thousands of nodes. Since it is impossible to copy/paste source code, I've created a series of videos showing how to use the structure editor and the language.
the project can be found at
the video tutorials can be found at
You can download and try it out at-
Eastwest is based on the O'caml Structure Editor Toolkit (OSET), which can be found at
If anyone knows of any similar projects, please let me know.
...literally 'east-west' but actually meaning 'thing'?
I actually came up with the concept in china. I originally wanted to call it East, since it's where the idea was born. It's also a combination of EAsy and faST (FASY being another option.) not to mention an acronym: "Editor for Abstract Syntax Trees". Unfortunately, google code claimed that the name "east" was already taken, so I changed it to its current form.
In Chinese, dongxi is also used as an euphemism as could be imagined. Or perhaps I hang out with the wrong people.
I'm not big on structure editors. You could get most of the benefits in an unstructured editor using clever incremental parsing/type checking techniques that are well understood by now.
It is true that clever incremental parsing/type checking gives many of the advantages usually associated with structure editors while keeping the text based interface which we all know and love. There are, however, some things which cannot be achieved in text:
- arguments can appear anywhere in function names and function names can include spaces and characters from other languages, allowing the source code to appear like human language (something similar to inform 7). It is possible to write programs in Japanese (using kana).
- the user is forced to only add from a finite list of options, a kind of exact completion, thus a user cannot make a type unsafe choice.
- smart code formatting automatically expands/retracts the source tree, graphically showing the user the local structure while keeping the source code compact.
- the user does not need to learn a syntax. Instead, the user can conceptualize based on the name of the action such as "add a function" or "include a module"
- the user can then use the structure editor when asking for input (see )
- "token types" allow the users to exactly represent languages with bindings, such as the language of closed lambda terms.
- Since incremental parsing is not needed, this is way is potentially faster.
I don't really agree with any of these bullets except maybe the last which is true but almost not worth discussing. Some of this requires IDE support over what Notepad provides, but isn't incompatible with incremental parse. Not supporting whitespace in identifiers is a trade-off that allows whitespace to be the separator between tokens - it could be something else.
I'd like to hear why you disagree with each point. However, I may not have made my points as clearly as I should have.
for function names:
the following are legal function names:
the average of (float) and (float)
(float) is greater than (float)
if (bool) then (a) else (a)
so that you can write code like:
if the average of x and y is greater than 2 then ... else ...
for the exact completion argument:
it is simply not possible to write something like this:
"hello" - "world"
Another point I forgot to make: all function calls are implicitly qualified with its module but these qualifications are not shown to the user. The user chooses the module when calling it, but this is painless thanks to the completion mechanism.
If anyone wants a clearer idea of what I mean I suggest they try it out or that they look at some of the videos I posted in the tutorial.
Right, there's nothing preventing english-like function names (or at least the functional equivalence) with a more conventional parser/IDE.
In fact, Algol 60 allowed calls that looked like
The_average_of (float) and: (float);
The idea was that commas in argument lists could be replaced by )identifier:(.
(Uhh, maybe I have the colon and the identifier swapped. And maybe it allowed spaces instead of underscores; there's no good reason why not -- it was legal in FORTRAN. Algol 60's lexical behavior was always a gray area. It's been a long time...) And of course Smalltalk 80 calls look fairly similar.
so: the average of (float) and: (float);. The BNF defined this alternative to comma as ')', label, '('.
the average of (float) and: (float);
')', label, '('
Of course, in order to do that you had to strop your reserved words, writing either 'if' or IF, depending on the compiler, or (for publication) if. Simple if was an identifier.
'if'
IF
if
the following are legal function names:
the average of (float) and (float)
(float) is greater than (float)
if (bool) then (a) else (a)
Something like mixfix parsing allows this, but I don't really think it's such a good idea. I don't understand your point about "hello"-"world".
If anyone wants a clearer idea of what I mean I suggest they try it out or that they look at some of the videos I posted in the tutorial.
I've looked at a few of the videos. It's a mouse based interface, which I wouldn't want to use for the majority of programming tasks. You can add a mouse based insertion mechanism on top of text based format (see eclipse), but it looks generally more difficult to me to start with a structural approach and retrofit parsability from text. Removing parsing ambiguity from the grammar should be done up front.
- the user is forced to only add from a finite list of options, a kind of exact completion, thus a user cannot make a type unsafe choice.
This is just IDE support.
Again, this is just IDE support.
The nice thing about a mouse driven visual interface is that it's easier to explore all the possible options. The bad thing is it's generally going to be slower and the user has to figure out where things are in the interface. Once you know you want "if X then Y" to show up on the screen, it's trivial to get it there using text editing. If you have to find it in some drop down or memorize a shortcut stroke for it, that's annoying. So we probably ought to have both, and again, text is the one you need to get right up front.
- the user can then use the structure editor when asking for input (see )
This is just saying that you can expose the IDE UI to the language through a library. That's not unique to the structural approach.
Text based languages need to have the concept of a parse error state. This is the price you pay for letting users edit code as text. But modulo this parse error state, closed lambda terms can be modeled exactly.
- Since incremental parsing is not needed, this is way is potentially faster.
Note that you could speed up text based parsing if you were willing to have more than just a plain text data structure representing the text.
the mouse based interface is optional and is presented only so that user's can see what's going on. In fact, the mouse based interface was added after the keyboard interface. You can view a video of me using the keyboard interface here:
To input an "if (bool) then (a) else (a)", the user need only write "if" and Eastwest will list it as an option (most probably the first). This is fast because the user doesn't need to write "then" or "else". In my experience, it can be faster than editing text.
A description of the keyboard bindings can be found here:
"hello" - "world" will never get accepted by the structure editor. Once you select that you want to call the " (float) - (float) " function, the structure editor will know that the first argument is a float, thus it will never accept "hello" as a valid option. In a standard IDE, the user can input anything he wants and he can make unparseable or untypeable additions. This is not the case in Eastwest.
Using the structure to get input from the user is a unique way to get input. It saves the programmer from having to write a GUI or a parser. Granted, the machanism of using the IDE through a library is not new but I've never seen it done to systematically get a value of any type. This is especially useful since the programmer will always get a well formed value; consequently, he does not need to have error messages.
Eastwest supports automatic expansion/retraction/formatting of the source code based on code size and cursor position which, in my experience, does away with manual formatting. If you know of any IDEs that do this, please let me know.
(a) you just have to define your tokens differently so that they can include whitespace. I've implemented incremental tokenizers that are flow sensitive that can basically do this (which you need to deal with comments in C-like languages). Your argument might have to do more with the fact that there is no good grammar for having whitespace in identifier names, but this can be solved with more syntax.
(b) Incremental type checking lets the user know when a type unsafe choice is made immediately, and can also prioritize choices based on type information (though if you are typing in an expression path, this isn't what you want anyways!). I've also done this.
(c) How is that different from automatic code formatting?
(d) This works fine with absolute beginners (see Alice) but doesn't even begin to scale to beginner programmers. Syntax is an important aspect of a language...and the user still has to learn the language!
(e) Don't get it (sorry, youtube is blocked by the greatfirewall of China, perhaps too many dongxi's there).
(f) you can do a lot with a tokenizer these days, much more than most languages do...
(g) Not an issue. Incremental parsing is fast enough, I've always been able to incrementally parse in the UI thread without noticeable slow down, even for huge files. The slow part that needs attention is always going to be type checking. Besides, you slow down the user significantly by having them think in discrete "good edits" and then use the UI to express those edits.
I'm not trying to slam your work, but your premise is hard for me to swallow, and it seems like we've been on this path before and the drawbacks of structured editing are already known to be game-enders. You either have to focus on defeating this criticism (not easy) or focus on unique features that you can only get with a structured editor (e.g., see Alice or even Subtext).
(a) Eastwest not only allows whitespaces and chinese/japanese/arabic/... characters, it also allows placing arguments anywhere. Some people have responded that they've seen this in Algol-60, but I don't know of any currently used programming language which supports it.
(b) The big winners for exact completion are beginners. I have to admit that experienced programmers would be happy with having an error message as soon as an unsound choice is made. However, I see no reason for letting the user make an unsound choice in the first place.
(c) It is different because the formatting which change depending on the cursor position. So that the expression " 2 + 3 " will be displayed as one line unless the 2 or the 3 is selected. You will need to watch the videos to really understand it.
(d) This is what is special about Eastwest: the user does not need to know the syntactic details about the language. Instead, he simply needs to get familiar with the concepts (which usually correspond to some kind of text on the screen.) In this manner, I can completely change the syntactic details and the user will still be able to easily adapt. Again, You'll need to watch the videos or try it out yourself.
(e) -
(f) I'd like to see a language which uses a tokenizer in this way. Furthermore, token types (mostly) do away with error messages.
(g) I consistently find IDEs which incrementally parse less responsive. I admit that this is a purely subjective and personal opinion.
I can understand your reservations with respect to using a structure editor to interact with a programming language. What is different here is that I also want to show that structure editors are ideal for domain specific languages especially those which are not often used and easily forgotten. Eastwest is a programming language made for creating user interfaces for domain specific language and specifying their interpretation. In this manner it serves two purposes: show that a structure editor can be used for a full fledged programming language and, for those who are skeptical about this first point, to show that it can be used for domain specific languages.
It's too bad you can't view the videos. Is there any way I can make them available to you?
Sean,
I think your critique is a bit fast. We have no evidence that the structure editing approach can't in principle be made to work, only that it can be tricky to match some of the ergonomic qualities of free text editing. (Intentional Software are betting their business on it.) Moreover, a similar claim could be made for incremental parsing/semantic analysis. We've been trying that for several decades (think Ensemble/Harmonia, etc), and the state of the art is still extremely primitive: just witness Eclipse or Visual Studio.
Indeed, the kind of fancy incremental parsers, type checkers and code formatters you allude to are really just structure editors made a little more user-friendly. A structure editor that works well can present the "illusion" of freely editable text. Conversely, a fancy syntactically- and semantically-aware text editor can present the "illusion" of directly manipulable semantic structure. Sufficiently well implemented, they collapse functionally into the same thing.
I'm going to stand by my critique. The ergonomics of structured editing is a show stopper for anyone but novices. Anything that puts you into a rigid mode where you have to fix something before continuing is bad in most cases; e.g., consider evil modal dialog boxes. Imagine a word processor that forced you to fix spelling mistakes before typing the next word!
The difference between a structure editor and a smart editor are mostly of ideology and technique. In the former case, ideology dictates that edits must be made in correct chunks where feedback and assistance are in the foreground, while in the latter case, ideology allows for free form editing with background feedback and assistance.
By technique, the former is an exercise in forward engineering (tree building) while the latter is an exercise in backward engineering (via compilation), which is definitely trickier than forward engineering. Smart editors are much more viable for real developers, even in the sorry state they are in today (e.g., Eclipse or Visual Studio). Can they converge? Could a structure editor be made to look like a smart editor? Sure, but then...its ideology has changed to that of a smart editor (in that it is allowing for free form editing). Not sure if Intentional Software is going to be able to climb over these obstacles (how much impact have they had???).
I actually know things can be better Java/C# support from my Scala plugin experience. Incremental parsing is an easy problem, you just memoize your parse trees from your regular batch parser and increase error recovery by tracking brace pairs (in a C-like language). Error recovery is very important in the incremental world: a parse error shouldn't destroy good parse information that were already computed. Incremental type checking involves more memoization and error recovery, but you can reuse your existing compiler if it is based on functional programming principles (i.e., well-modularized state). It is definitely tricky, and my biggest regret is not having enough time (one or two more years) to finish the work up to some level of robustness.
I think I was inviting you to drop the ideological distinction in favour of a functional characterisation, because ultimately it's how systems behave that matters, not the ideologies of their designers, and an ideological definition of what counts as a "structure editor" only ends up begging the question.
Perhaps. But I guess my point was that once your structure editor feels like a free form editor, is it still a structure editor? If we go purely by functional characterization, then the difference is in the tree building/processing approach (compilation vs. explicit construction).
Somebody needs to do usability study research to measure what the differences are.
People who use IDEs put up with a lot of b.s. and have high pain tolerances, though. Resharper...
But the usability of structure editors has been studied somewhat. They are great for beginners and horrible for everyone else because they stick you into a mode and force you to follow a certain order in program definition. IDEs surely are bad, but we use them and we miss them when we have to go back to something like Emacs (or at least many of us do).
I don't think there will be a comparison between a compilation-based smart editor and construction-based structure editor until there is a viable structure editor with which we can compare against. Few people go in that direction so....
Do you any references to studies examining the usability of structure editors?
No. As far as I know, no one has done a study that has scientifically measured the usability of structure editors for non-novice programmers. There is a study at CMU on structure editor viability for refactoring tasks, but I remember it wasn't related to writing new code.
As far as I can tell, the modal editing problem of structure editors was simply termed "the usability problem" when structured editing research was popular in the early 80s, I don't know whether anyone did any tests to validate the use of this term.
Here's some very relevant research. From the abstract:
A detailed study of Java programmers' text editing found that the full flexibility of unstructured text was not utilized for the vast majority of programmers' character-level edits. Rather, programmers used a small set of editing patterns to achieve their modifications, which accounted for all of the edits observed in the study. About two-thirds of the edits were of name and list structures and most edits preserved structure except for temporary omissions of delimiters. These findings inform the design of a new class of more flexible structured program editors that may avoid well-known usability problems of traditional structured editors, while providing more sophisticated support such as more universal code completion and smarter copy and paste.
Thanks for the heads up.
Design Requirements for More Flexible Structured Editors from a Study of Programmers’ Text Editing[PDF]
To what extent would you attributed the sluggishness of recent releases of IntelliJ IDEA to trying to make the unstructured approach work?
It just seems like these unstructured text IDEs are getting slower and slower as they do more ad-hoc things to text, both in analysis and synthesis.
Awhile back I bought some books on advanced pattern matching concepts to look into doing a sort of hybrid structured/unstructured editor. I never really got anywhere with it, because I realized it was a rabbit hole requiring a labor of love to get any results out of.
The problem with most smart editors is that they are not truly incremental: they work by silently reprocessing entire text buffers as fast as possible, which sometimes isn't fast enough. The Scala plugin was unique in the way that it was actually incremental at the tree level (both parsing and type checking, not every AST tree, but certain large-grained trees like classes and methods). Sadly, this was also its downfall, as it made certain assumptions about the compiler (no magical maps that record dependencies in order-sensitive ways) that maybe shouldn't have been made. But at least I know its possible...
The easy problem is incremental parsing, which is also the least important (re-parsing large buffers can be made fast) but is important if you want to do decent error recovery (so transient parse errors don't destroy good existing parse trees). Type checking also isn't that hard, there are some tricks with managing the symbol table (re-typing a tree, remove entries already entered the last time that tree was processed). Once you have incremental parsing and type checking, most of your important IDE features are easily implemented (intellisense, real time error and type feedback). Any feature beyond that...say advanced bug checking or what not requires the appropriate incremental algorithms. If no incremental algorithm exists (say for global refactoring), then we should use structured-editor like modal methods.
I spent a couple of years down the rabbit hole and even though the problems aren't easy, its definitely doable by a team of smart programmers within a reasonable amount of time (say 3 programmers @ 2 years could put out a kick-ass Scala plugin). I have no idea why Eclipse JDT and Visual Studio C# support are so lacking given the size of the teams involved. Perhaps the techniques used are just outmoded, they are re-using too much legacy code, and so on...I have no experience with IntelliJ, but my discussion with the developers suggests that they focus on tackling other problems.
Most smart editors actually use what's known by some text buffer editing afficionados as "the reduced document model" or "reduced model". It sounds like you are describing this approach. [Edit: This model can usually be optimized using Ropes data structures.]
Developing plug-ins for Visual Studio up until 2010 was very painful. 2010 is supposedly making it better but I've not given it a try. The secret sauce is MEF, which to me is no secret sauce at all, dumbing down what it is about it's basically an emacs style plug-in model with better engineering constructs (app domains, assemblies, then namespaces as opposed to "RMS-style") and crappier syntax. But the average guy can code VB.NET extensions and not use elisp.
Edit; And yes, I am pretty sure that if Visual Studio and Eclipse have crappy models for documents, then legacy code (i.e., third-party plug-ins) required for backwards compatibility will drag it down. At this point, many would refuse to upgrade to VSTS2010 if Resharper just died. In 2005, the SLOC figure for VS was 6 million plus. Hate to wonder what it is now. I know from reading the code and studying the models for NetBeans Schliemann and GSF projects that most people don't come up with good enough data structures, and thus code-dig themselves into mantle of the earth's crust.
[Edit: Ah, just found MobWrite via this Hacker News link. This is similar to what I had in mind, except my purpose wasn't collaborative editing.]
Go ahead and change the home page to explain that it's a literal translation of æ±è¥¿.
Or 东西 for those of us from the simplified world.
I was going to try this out, but I'm not familiar with OCaml and had some difficulty getting Eastwest to compile (some pcre error, will try again later).
I'm also working a project that will require a structure editor. I've been grappling with internal format and bootstrapping though, and haven't gotten to that phase yet. But I'll definitely keep this in mind!
you'll have to install libpcre-ocaml-dev (if you're using debian)
First off, a very interesting project!
There are a few things that you will need to consider, though. I have gone down this conceptual path before (though not far in implementation), and in my opinion you definitely do not want to limit the user to constructs which already exist. This forces an implementation order - you always have to declare/build up your toolkit first, and then build on that. Using earth as a metaphor (where support is dependency), you can never build any overhangs, to be filled under later.
You could say that this is for the best, and that you should always have working code. However, on many occasions it is valuable to bash out a function, referencing other nonexistent, hypothetical functions.
As for the interface, while I haven't checked if you are actually using the F-keys, I actually think they should be closer in on the computer. They aren't exactly fast and reachable. Something like alt + letter would be good.
What do you mean by "you definitely do not want to limit the user to constructs which already exist"?
If you're talking about an FFI, one exists, though currently undocumented. You can call functions written in O'Caml. The implementation was done using the Lazy module so that the function "if _ then _ else _" is defined as an external function.
As for the F-keys, I agree that they are a little far for the user. I originally had it set to alt-X (as you proposed). Unfortunately this didn't work on some keymaps. In the future I'll simply make it so that both work.
I think radial menus are more useful than dropdown lists, as an FYI
I think this is a step in the right direction. I think that it would be nice if Microsoft Visual Studio or eclipse had a strong-syntax tree editor, where deleting a bracket was tantamount to deleting the expression block... I elaborate my opinion here . (I'm linking externally because it includes images, is a bit of a derail, and talks a bit about implementation, sorry if it's spammy!)
I have tried Eastwest (see below for instalation tips).
I have also read your blog entry.
I must say it's wrong that non-mouse support is lacking.
See the calculator demo, it's pretty apparent that the mouse keeps still.
Actually the keyboard support is excellent and you don't need mouse at all.
(that doesn't mean the usability is astounding, to judge it you have to test the real thing)
About the videos :
* no more syntax errors, no more type errors
* user input validated without a parser
* thanks to GADT user input typed without a typer
* it feels like the ultimate beginner-friendly programming environment
* my blog entry (french)
About the installation:
* type-conv package is a (never mentionned) requirement
* sexplib package is also a (never mentionned) requirement
* i have encountered the xml-light install Bug#345792
(workaround:)
* i have also encountered the omake install Bug#522008
(workaround:)
My review :
* at first encounter the ergonomics doesn't feel so good
- once edited code blocks feel quite rigid, there's not much you can do except copy/move/delete
- pattern branches can't even be copied/moved/deleted
- you always edit the operands, you can't edit an operator
* when loading lambda_calculus.east i have a Conv.Of_sexp_error exception
* the language is really crude
- there is an integer type but no integer operations
- there is a boolean type but no boolean operations
- true and false are defined but do not appear in the menu when needed
- the float type misses negation, equality, sin/cos/tan/exp/log
* eastwest uses camomile thus i tried to paste some unicode math symbols but didn't succeed
* would be nice if the editor includes a unicode math symbols panel
* the literate programming approach really delivers, it smells like natural language
Conclusion :
* i really like the language and the experimental tool
* yet the editor is nowhere near real-world usage, once entered the code just feels like frozen
My deriv example could be a nice demo, unfortunately Eastwest doesn't accept immediate floats in patterns.
I hope Eastwest will improve to the point where at least some serious toy interpreters can be done.
I've introduced literal patterns into Eastwest version 0.1.3. Any token type (int, float, string, etc...) can have literal patterns. You might need to install the latest OSET.
I've encoded typed lambda calculus with type inference; thought you might be interested:
Lambda calculus with gadt is a fanstatic demo.
I expected an example like that.
GADT are a really cool thing from the Haskell world that fit Eastwest like a glove because your environment is so much language-oriented.
About literal patterns, one problem is they rely on branches ordering, so one wants to be able to (re-)order branches.
Thanks for the feedback!
Eastwest is based on SDL. This is definitely not because I have a preference for SDL; rather, it was a last resort that finally made Eastwest work. This is why copy/paste is not possible at the moment and why inputting unicode is only possible if the character is on your keyboard. If someone writes an ocaml library to fetch the copy buffer then getting copy/paste would become trivial. Getting unicode input (through an IME), however, will require much more work.
I don't see how I can fix this bullet:
"once edited code blocks feel quite rigid, there's not much you can do except copy/move/delete"
seems like the nature of the beast
Everything else you mentioned is spot on and easily fixable. I'll post on this thread when it is done (shouldn't take too long). I don't know if Eastwest will ever be ready for "real world usage"; I just hope it can inspire someone to write something that will be.
The "insert unicode" menu option lets you display any of the unicode characters you mentioned
grab the oset source here:
svn checkout oset-read-only
then do a make reinstall. You'll then have to get the eastwest sources here:
svn checkout eastwest-read-only
both these commands are on the google code pages. It's largely untested, so feel free to send me an email if you find anything that's not right.
I have actually tested Eastwest r106 and emailed you a report.
Seems you did not received it.
I guess the skeptic audience is gone now so i can make it public.
The r106 update starts to realize the full Eastwest potential.
Unicode is a great addition that gives more cachet to your already syntax rich language.
I also discovered how much freedom when naming thing and how it challenges my usual naming conventions.
However, the more i test it the more i find things to be improved :
My output syntax test exemple is to input 3cos² (x²+1) that is derived as (it can't be unfolded) :
(-12) * x * sin x power 2 + (1) * cos x power 2 + (1)
sin x power 2 + (1) that sounds much like (sin x)² + 1 but actually is sin (x² + 1).
Thus your innovative syntax comes with a cost in the readibility department: it doesn't scale up, especially as one can't destructure it.
Anyway, it's still one of the most impressive technological demo i have seen. Thanks for your great work.
The smart editor idiosyncrasy is something i can accept for toying with a pioneering tool.
I can live with it (provided branches are no more castrated).
You already have something really impressive, please concentrate on the language first, having a more expressive language allows more and better code examples. Reengineering the editor is probably much more work and wouldn't even gain you more attention.
Unicode math is actually a killer feature.
Even a fixed set would be a giant step, may be selectable from a LablGtk menu or some other folding panel, most people would probably be well served by a limited set along these lines :
∀∃âˆâˆ‘∆∈∉∋∌℘λαβηγεζθπσωφΩΓℕℤℚâ„â„‚
≜â‰â‰¡âˆ¥âˆ¦â—¦ × √ xº x¹ x² x³ xâ¿ xˉ ¼ ½ ¾ ≠≡ ≈ ÷ ≤ ≥
⊢⊥∩∪∧∨⊂⊃⊄⊅⇒⇔â†â†’↦↤↔↑⊓⊔⊕⊖⊗⊘⊙⊚⊠…
Maximize the Eastwest added value that is language-oriented paradigm.
Then it can become a tool of choice for learning functionnal programming, DSL prototyping and language/formal semantics research.
I love the call to replace >=, with ≥ 's.
Maybe someday someone will make a math or programmer's keyboard to mesh with it!
Most rich math programming environments like Maple and Mathematica allow you to enter key chords to generate math symbols, e.g. "replace >=, with ≥".
Fortress is the first general purpose programming language, though, to allow this.
Maple's implementation sucks, by the way, and has be fraught with bugs. | http://lambda-the-ultimate.org/node/3567 | CC-MAIN-2021-39 | refinedweb | 5,693 | 60.85 |
Re: [soaplite] Perl server -> .Net client. Can't parse response due to namespace?
Expand Messages
- Thanks for your reply Brad,
I have used the SOAP data object to override the prefix and now get a soap response of:
<SOAP-ENV:Body>
<namesp1:createSessionResponse xmlns:
<createSessionResponse xmlns="">
<status xsi:06</status>
<sessionID xsi:
<redirectURL xsi:
</createSessionResponse>
</namesp1:createSessionResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
The code to do this is:
my $myRes = SOAP::Data->name("createSessionResponse" => \SOAP::Data->value( SOAP::Data->name("status" => $result_hash{'status'}), SOAP::Data->name("sessionID" => $result_hash{'sessionID'}), SOAP::Data->name("redirectURL" => $result_hash{'redirectURL'}) ) )->attr({ xmlns => '' }); $myRes->prefix(''); return($myRes);
Anyone got any ideas on how to get rid of the outer <namesp1:createSessionResponse> elements that are now being duplicated?
Thanks,
Robin
On Wed, 2005-12-21 at 08:20 -0500, Brad Miele wrote:
Robin,
I believe that there is something in the SOAP::Lite man page to this effect, or at least for working with .Net in general. for my web service, which was written solely for working with .Net clients, i dicovered that .Net didn't like the prefix stuff tha SOAP::Lite includes, an example of one of my responses is:
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:
<soap:Body>
<LogoutResponse xmlns="">
<LogoutResult>0</LogoutResult>
<errorMessage>SUCCESS</errorMessage>
</LogoutResponse>
</soap:Body></soap:Envelope>
I had to remove the gensym and namesp tags.
There *should* be a way to do this when you initialize SOAP::Lite, but i could never get it quite right, so i always end up hacking the .pm to correct it, if someone can show me an example of setting up the prefixes for .Net without hacking the module, that would be cool.
In any case robin, i hope this helps.
On 12/21/05, robin_keech1 <robin@...> wrote:
Hi all,
I have written a SOAP server using SOAP::Lite. It has a wsdl file at
I have tested the service with both perl and php clients. We have a new customer that is coding in .Net and having trouble integrating the method calls. The server logs show a method request and a result being sent back, but the client can't seem to get at the results. Initially they only received a string with "status", so I changed the wsdl to include a complex type as the return parameter. The actual perl server code just returns a hash.
The client has said that "the .Net framework cannot parse the XML being returned from the createSession SOAP call as one of the namespaces is declared within the node using the namespace. .NET needs it to be declared before it is used or it throws an error."
Firstly, is this conclusion correct? Has anyone experienced a problem like this with .Net? And if it is, can anyone help with suggestions on suppressing/removing the namespace part.
So the SOAP body looks like:
<SOAP-ENV:Body>
<namesp35:createSessionResponse xmlns:
<s-gensym283 xsi:status</s-gensym283>
<s-gensym285 xsi:00</s-gensym285>
<s-gensym287 xsi:sessionID</s-gensym287>
<s-gensym289 xsi:42053C6A714211DA909B8DCE9602641D</s-gensym289>
<s-gensym291 xsi:redirectURL</s-gensym291>
<s-gensym293 xsi:</s-gensym293>
</namesp35:createSessionResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
But this won't work unless the namesp35 namespace is declared before it is used. Taking out the section in bold should work, according to the customer.
The other thing I though it might be was not encoding the result hash as a correct SOAPata type object that matches the wsdl description. Or maybe I should be looking at overriding the serialiser.
As you can probably tell, I have no idea what to do to get this working. I don't have access to any .Net technology to play with. Any suggestions would be greatly appreciated.
Robin
YAHOO! GROUPS LINKS
- Visit your group "soaplite" on the web.
- To unsubscribe from this group, send an email to:
soaplite-unsubscribe@yahoogroups.com
- Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.
--
Brad Miele
Technology Director
IPNStock
(866) 476-7862 x902
bmiele@...
- Hi , i m new to soap lite..i have to create perl client that consume .net web service... from wsdl filei succefully install soap lite..and its woking..but problem is occur when i use complex type....im sending you my perl script file..plz have a look..give me suggestion..this is right way.. i also use stubmaker.pl for making .pm file,but doesmt work..
here is code of mine...# perl client
# GetName method is complex type
# problem: when client request to serevr ,serevr cant get any value from client
# In addTwo method its simply take two parameters and return addtion of them..but when on server site its show o,o as input
# as well as in GetName method i pass city name as "jaipur " but on server its show null$NS = ""; #name space
$HOST = "";use SOAP::Lite +trace => 'debug';
my $_debug_=1;;my $localservice = SOAP::Lite -> uri($NS)
-> on_action( sub { join "/", @_ } )
-> proxy($HOST);
#$localservice->proxy->timeout(100);
$localservice ->xmlschema('2001');
my $method2 = SOAP::Data->name('addTwo') ->attr({xmlns=>$NS});
my @params = (
SOAP::Data->name(a => 4),
SOAP::Data->name(b => 4));my $result = $localservice->call($method2 => @params)->result;print $result;my $method = SOAP::Data->name('GetName') -> attr({xmlns => $NS});my @params = (
SOAP::Data->name('oPerson'=> \SOAP::Data->value(SOAP::Data->name('add'=>
\SOAP::Data->value(SOAP::Data->name('City' =>"jaipur"))))));
my $result = $localservice->call($method => @params)->result;
print $result;thanksregardsSudhakar Sharma
Send instant messages to your online friends
Your message has been successfully submitted and would be delivered to recipients shortly. | https://groups.yahoo.com/neo/groups/soaplite/conversations/topics/5062?o=1&xm=1&l=1 | CC-MAIN-2017-34 | refinedweb | 929 | 57.67 |
Wavepot Milestone #1
Wavepot, by George Stagas, is reaching it's first milestone. It's a crowfunded dsp sandbox. A bit like glsl sandbox. In wavepot you can listen at the works of the others and try your own modifications on them, or create your own audio processing programs.
Whereas the glsl sandbox has been bounded to simple fragment shaders, the wavepot's module system means it'll be easier to create large scripts and build on top of others work. I'm already using some of the modules from opendsp, not needing to rewrite the filters for every dsp function.
Biggest thing introduced in the first milestone is the github interface. The code you write into the screen is stored into github. It ends up to anonymous account if you're not logged in. The scripts can also read
.wav -samples from any repository: Here's a sample.
You can use this tool to create your own sound effects, or small sound tracks. Without a track editor and midi input you have to notate that all into your code or use a separate tracker. The functions can be embedded into javascript programs or recorded into samples.
Stagas is planning to open source, and he's perhaps running second crowdsourcing funding for the milestone #2. I'd be already quite satisfied if the tool would get a decent track editor and midi input, perhaps some knobs. When wavepot was down for few days, I already thought about doing it myself.
How to use Wavepot
To use wavepot, you need to know how to code javascript. Perhaps need to know little bit about the upcoming ecmascript 6 -standard. The DSP scripts are plain javascript. If you know a little bit about digital audio synthesis, that's good too. The script must produce a dsp -function, like this:
export function dsp(t) {
return Math.cos(t*Math.PI*2*440) * 0.5;
}
The above dsp is a 440Hz sine oscillator. The
Math.PI*2 is
π*2, also known as
tau. It's multiplied with 0.5 to reduce the amplitude. What you write there depends on what you're doing, and how loud sound you want to produce. The
t is time in seconds from the start of the track.
Wavepot's driver calls the
dsp(t) to fill an audio frame. The driver roughly looks like this:
for (var i = 0; i < frame_length; i++) {
var out = dsp(i / sampleRate + time);
if (out instanceof Array) {
left[i] = clamp(out[0], -1, +1);
right[i] = clamp(out[1], -1, +1);
} else {
left[i] = clamp(out, -1, +1);
right[i] = clamp(out, -1, +1);
}
}
time += frame_length / sampleRate;
Here's a longer example, that you can try out yourself:
var pi = Math.PI;
var tau = 2*Math.PI;
import Biquad from 'opendsp/biquad';
var bq = new Biquad('lowpass');
export function dsp(t) {
bq.cut(100 + 10000*(1+Math.cos(t*tau*0.1))).res(5.0).gain(1.0).update();
var l = noise() * 0.1;
var r = bq.run(l);
return [r, r];
}
function noise() {
return Math.random()*2 - 1;
}
The above program is driving noise through a biquad filter with oscillating cutoff frequency. The filter is instantiated outside the function because it encloses a bit of state. The
.run() -method advances the filter, and stops working as intended if called more than once in the dsp -function.
Here's some other wavepot scripts I've written last week: | http://boxbase.org/entries/2014/nov/17/wavepot/ | CC-MAIN-2018-34 | refinedweb | 575 | 75.2 |
UpFront
UpFront
- LJ Index, July 2009
- They Said It
- bc—When Integers Aren't Enough
- diff -u: What's New in Kernel Development
- Non-Linux FOSS
- Netbooks—Dying or Evolving?
- EFI-X: When Dual Boot Isn't Enough
- Stop Burning CDs; Burn USB Drives Instead
- Mobile LinuxJournal.com
LJ Index, July 2009
1. Percent of US homes that don't have Internet access: 29
2. Percent of US homes that think the Internet is useless: 12.7
3. Highest average number of spams per user in a single day in 2008 (April 23) at Google: 194
4. Approximate number of spams per second that can be attributed to the McColo ISP (recently shut down): 33
5. Approximate number of spammers responsible for 80% of Internet spam: 200
6. Rank of US in list of “10 Worst Spam Origin Countries”: 1
7. Rank of China in list of “10 Worst Spam Origin Countries”: 2
8. Rank of Russian Federation in list of “10 Worst Spam Origin Countries”: 3
9. Rank of United Kingdom in list of “10 Worst Spam Origin Countries”: 4
10. Rank of South Korea in list of “10 Worst Spam Origin Countries”: 5
11. Approximate cost per megabyte of RAM in 1957: $411,041,792
12. Approximate cost per megabyte of RAM in 2008: $0.021
13. Billions of dollars of legal music downloads in 2008: 3.7
14. Percent increase in legal music downloads from 2007 to 2008: 25
15. Downloaded music sales as a percent of total music sales: 20
16. Percent of total music downloads that were not “legal”: 95
17. Average “step-on-it” factor used during software estimation phase: 2.5
18. Average number of weeks left to complete a software project: 2
19. US National Debt as of 04/05/09, 1:29:32pm CDT: $11,135,460,534,223.90
20. Change in the debt since last month's column: $185,190,792,300
1, 2: Park Associates
3: Google Message Security Data Centers
4: Spamcorp
5–10: Spamhaus
11, 12:
13–16: IFPI
17, 18: Common knowledge
19:
20: Math
They Said It
Don't you wish there was a knob on the TV to turn up the intelligence? There's one marked “Brightness”, but it doesn't work.
—Gallagher
Nobody in the game of football should be called a genius. A genius is somebody like Norman Einstein.
—Joe Theismann
Downgrade rights are hugely important for Windows 7. Will Microsoft offer downgrades [from Windows 7] to XP? They've not answered that question yet. But it's really important.
—Michael Silver, Garter analyst
One day soon the Gillette company will announce the development of a razor that, thanks to a computer microchip, can actually travel ahead in time and shave beard hairs that don't even exist yet.
—Dave Barry
Once a new technology rolls over you, if you're not part of the steamroller, you're part of the road.
—Stewart Brand
The Internet today is an open platform where the demand for Web sites.
—President Barack Obama
bc—When Integers Aren't Enough
Most people have the need to do some kind of math when they are using a computer. In shell scripts, you can make integer calculations by using functionality in the shell itself. But what if that's not enough? Luckily, the POSIX standard includes a very useful command-line utility called bc. With this, you can do arbitrary precision arithmetic. Actually, it is a complete, C-like language that can do some pretty sophisticated programming, supporting variables and functions.
In bc, numbers are all represented internally as a decimal number. They have a length, which is the total number of digits, and a scale, which is the number of decimal spaces. You can find these values by using the built-in functions length() and scale(). For example, the number 10.23 would have a length of 4 and a scale of 2. The variable scale holds the number of decimal places to keep when internal functions are executed. The default value is 0. bc supports all number bases from 2–16, with base-10 being the default. The input and output base of numbers can be set by using the variables ibase and obase. All of the basic mathematical operations are supported in bc. You can multiply, divide, add, subtract, do mod and exponentiation. There are all of the standard comparison operations too. Less than, less than or equal to, greater than, greater than or equal to, equal to and not equal to all give results of 0 for false and 1 for true. This is very useful in the conditional statements available in bc.
bc can be used in shell scripts or on the command line as a very effective calculator. It will read from a list of files given on the command line or read from standard input. On the command line, expressions simply can be echoed through a pipe to bc:
echo "1+1" | bc
The above will give the answer of 2. As a more complex example, the sine of 5 can be assigned to a shell variable with the following:
RESULT=`echo s(5) | bc -l`
The -l command-line option tells bc to load the math library, giving access to the trigonometric functions.
As a bit of a contrived example, say there are two values and you need to find out which one has a larger sine. With the math library and the built-in comparison operations, you can do this with the following:
echo "s(5) < s(10)" | bc -l
The result 1 is printed out on standard output, verifying that the sine of 5 is less than the sine of 10. bc can print out a text string telling the user whether the result is true or false with the following:
echo 'if (s(5) < s(10)) print "true\n" else print "false\n"' | bc -l
This prints out the word true. If this string is to be stored in a variable, the newline characters would be removed from the executable line. This value then can be used later in a shell script by saving it to a shell variable.
What if you have a data file of input values and you want to apply some function to them? Say you need to calculate the logarithm base-10 of each value and dump it into another file. The following example takes a list of the first ten numbers, calculates the logarithm base-10 of each number and writes the value into the file output.lst:
LIST="0 1 2 3 4 5 6 7 8 9" for INPUT in $LIST do echo "l($INPUT)/l(10)" | bc -l >>output.lst done
These examples already have done some useful work, but what if the requirements are more robust? Does this necessitate a move to a heavyweight math program, like Mathematica or Maple? Not necessarily. With bc, you can create and use functions to make more complicated calculations. Even recursive functions can be written, like in this example to calculate a factorial:
define f (x) { if (x <= 1) return (1); return (f(x-1) * x); } print "Factorial:"; factorial = read(); print f(factorial); print "\n"; quit
This can be dumped into a file called fact.bc and run through bc to get the factorial of some number by executing:
bc fact.bc
This script asks the user for a number and then finds the factorial. It can be used without interaction simply by feeding the number in to standard input with a pipe:
echo 10 | bc fact.bc
This prints out the factorial of 10 (3628800) to standard output. But, how fast can such a program be? For a variety of values run on a generic laptop, the following times were measured:
10 0.004s 100 0.004s 1000 0.028s 10000 3.099s
These times were averaged over three runs to account for varying system load. It seems more than fast enough to be useful for a lot of heavy work.
For a more scientific example, the following bc script finds how long it takes for an object to fall from a series of heights:
define t(h) { g = 9.81; return (sqrt(2 * h / g)); }
Now there is no excuse for abandoning a shell script simply because it can't handle some mathematical problem. With bc, you can do a lot of really useful work straight from the command line. Go forth and enumerate.
diff -u: What's New in Kernel Development
Geert Uytterhoeven has replaced the old, dead CVS repository for the m68k Linux port with a shiny new git repository, and added a make install build target, as well as various other code fixes.
Steven Rostedt has updated ftrace to let users turn kernel tracepoints on and off simply by setting values in files in the /debug directory.
Jaswinder Singh Rajput has added some performance-counting features to AMD K7 and later processors. A range of data can be tracked, including processor cycles, number of executed instructions, page faults and context switches. The patches seem likely to go into the kernel soon. Ingo Molnar has given his endorsement and offered some bug reports to which Jaswinder responded quickly.
Matthew Wilcox has done a major rewrite of the MSI HOWTO. The Message Signaled Interrupts (MSI) HOWTO had not been updated significantly since 2004. It provides a mechanism for triggering interrupts on PCI devices, entirely in software. Previously, PCI devices needed to have a physical pin corresponding to the desired interrupt. MSI is much more flexible, and proper documentation will be quite useful. Grant Gundler and Michael Ellerman offered their own technical feedback to the HOWTO, and Randy Dunlap and Sitsofe Wheeler helped polish up the language.
Cheng Renquan has enhanced the KBuild system, so that when viewing help for any given compilation option, the currently selected build choice is visible at the same time. He also made various less user-visible changes, and Randy Dunlap has signed off.
Alex Chiang has submitted a bunch of PCI patches, including code to create /sys/bus/pci/rescan, a user-controlled file that can force a rescan of all PCI buses on the system. He added several other files to the /sys/ directory to give greater and greater PCI control to the user.
It's nice to remove features that no one uses. For one thing, it can simplify kernel code greatly. H. Peter Anvin wanted to remove the zImage build target recently and asked if anyone was still using it. As it turns out, Woody Suwalkski noted that ARM still used zImage. H. Peter probably will remove it from the x86 tree and leave ARM alone.
Bartlomiej Zolnierkiewicz has expunged the IDE floppy and tape drivers from the kernel and the MAINTAINERS file and listed them in the CREDITS file instead. He thanked Gadi Oxman and Paul Bristow for all the work they did in the early days on those drivers.
Michael Kerrisk has removed his name as the official maintainer of the kernel man pages. The Linux Foundation funding has run out, and a supplemental round of Google funding also has run out, so now he'll have to focus on other things. He still plans to support the project as best he can, but he cautions that the man pages likely will be orphaned soon, if no further funding or willing maintainer steps forward.
Non-Linux FOSS
Iron.
IronPython Studio (from ironpythonstudio.codeplex.com
Netbooks—Dying or Evolving?
I'm just as guilty as everyone else that jumped on the Netbook bandwagon when it started with the 7" Eee PC. After a few weeks, the limitations of such tiny notebooks become fairly clear. The Netbook market has evolved to the point that it's almost laughable. What are the latest features of that market? Bigger screens! Ten- to twelve-inch screens are becoming the new rage in the “Netbook” world.
Um, we had 12" screens before. We called them notebooks. I'm not sure if the Netbook fascination is wearing off or if low-power laptops are just going to become the norm. Because “low power” is becoming a misnomer as the CPU speeds creep up on ultra-portables, I think the term Netbook might just die away.
Another option is that something like Android, Moblin or Ubuntu Netbook Remix will standardize the tiny-screen laptop market, and it will become more like a souped-up cell phone as opposed to a stripped-down notebook. One thing seems clear, the days of a 7–9" screen running a customized and minimal Linux distribution are fading away into history. Is the Netbook a dying fad or still an infant going through growing pains? Sadly, I think that depends on how hardware manufacturers choose to push their upcoming models.
I certainly don't have the ability to see the future, but I hope the future of Netbooks doesn't continue along the path of adopting Microsoft Windows. Low-powered hardware just begs to have the Linux kernel running on it. If the interface could be something standard that ran familiar applications, we might have a chance to retake the entire Netbook market. Only time will tell, and only hardware manufacturers can pick the standard.
EFI-X: When Dual Boot Isn't Enough
I recently was contacted by the folks selling the EFI-X. It's a small USB device that allows EFI-booting operating systems to boot on traditional BIOS-based machines. The big selling point for such a device is that it allows native booting of Apple OS X on off-the-shelf PC hardware. I couldn't get any specifics as to why a Linux user would benefit from such hardware, but at the same time, I guess it's useful to know Linux is fully compatible with EFI-booting technology.
So although the $240 it takes to buy an EFI-X module won't really benefit your Linux install very much, if you want to install OS X on your trusty Linux machine, you now can do so. It most likely violates EULA terms with Apple to install on non-Apple hardware, but it doesn't require a hacked and pirated version of OS X to install. I bought an EFI-X, and OS X installed from the retail DVD right next to my Linux install. It takes a separate drive for each operating system, but I now have a triple-booting quad-core computer that cost less than $800. If you don't want to buy Apple hardware, but would like to dual- (or triple-) boot your system, check it out:.
Stop Burning CDs; Burn USB Drives Instead
It seems that every week there's a new version of some Linux distribution available. I don't know about you, but I have enough burned “last version” CDs to build a very reflective fort in the backyard. I'm also really bad about labeling CDs when I burn them, so I end up burning the same CD over and over. Thankfully, there is help for people like me—Unetbootin.
I did a video tutorial on this a while back, but the gist of Unetbootin is that you create a bootable USB drive instead of burning an installer CD. The application automatically will download the latest CD image, or you can create a bootable USB drive from an already-downloaded ISO file. Unetbootin even works in Windows, so if you're stuck with only a Windows machine, you can create a bootable USB drive to install our favorite operating system.
The great thing is that USB drives are easily rewritable. Most modern systems will boot from them without issue. The only downside is that it's harder to build forts out of USB drives. So, unless you really want to build that highly reflective fort, I'd suggest checking out Unetbootin.
Unetbootin video tutorial:.
Mobile LinuxJournal.com
After reading all about mobile Linux this month, I'm guessing you might be in the mood to take your Linux Journal mobile too. If you haven't visited our mobile version at m.linuxjournal.com, you missed the chance to catch all the content you find on LinuxJournal.com formatted to fit your mobile device. Even if you have visited us on your mobile device, you may have missed the link to our mobile videos. Scroll down to the bottom of the screen, and you'll see a link to our videos on YouTube mobile, which provides our videos in 3gp format for your mobile device. Just think, now you can whip out Shawn Powers' tech tips any time and almost anywhere! Happy | http://www.linuxjournal.com/magazine/upfront-16?quicktabs_1=2 | CC-MAIN-2015-32 | refinedweb | 2,784 | 71.55 |
#include <qcamera.h>
#include <qcamera.h>
Collaboration diagram for QCamera:
QCamera class is a visualization widget for camera devices. This calss can be used for the following purposes:
0
A constructor.
A destructor.
[inline]
Return the current camera device.
[protected, virtual]
[inline, slot]
Reset the camera.
[signal]
Emitted when the size of a camera image has been changed.
Connect a camera device.
[virtual, slot]
Resize a camera image.
Capture a single image from a camera and show it.
[slot]
display an image on the screen.
Capture images from a camera and show them periodically.
Stop capturing images from a camera.
[protected]
Camera device.
Camera property dialog.
Painter for drawing.
Internal pixmap for double-buffering.
Memory buffer to store a PNM image.
Size of a PNM image.
The height of camera images.
The width of camera images. | http://robotics.usc.edu/~boyoon/bjlib/dc/d74/classQCamera.html | CC-MAIN-2016-36 | refinedweb | 136 | 56.21 |
keyctl_setperm - Man Page
change the permissions mask on a key
Synopsis
#include <keyutils.h> long keyctl_setperm(key_serial_t key, key_perm_t perm);
Description
keyctl_setperm() changes the permissions mask on a key.
A process that does not have the SysAdmin capability may not change the permissions mask on a key that doesn't have the same UID as the caller.
The caller must have setattr permission on a key to be able change its permissions mask.
The permissions mask is a bitwise-OR of the following flags:
- KEY_xxx_VIEW
Grant permission to view the attributes of a key.
- KEY_xxx_READ
Grant permission to read the payload of a key or to list a keyring.
- KEY_xxx_WRITE
Grant permission to modify the payload of a key or to add or remove links to/from a keyring.
- KEY_xxx_SEARCH
Grant permission to find a key or to search a keyring.
- KEY_xxx_LINK
Grant permission to make links to a key.
- KEY_xxx_SETATTR
Grant permission to change the ownership and permissions attributes of a key.
- KEY_xxx_ALL
Grant all the above.
The 'xxx' in the above should be replaced by one of:
- POS
Grant the permission to a process that possesses the key (has it attached searchably to one of the process's keyrings).
- USR
Grant the permission to a process with the same UID as the key.
- GRP
Grant the permission to a process with the same GID as the key, or with a match for the key's GID amongst that process's Groups list.
- OTH
Grant the permission to any other process.
Examples include: KEY_POS_VIEW, KEY_USR_READ, KEY_GRP_SEARCH and KEY_OTH_ALL.
User, group and other grants are exclusive: if a process qualifies in the 'user' category, it will not qualify in the 'groups' category; and if a process qualifies in either 'user' or 'groups' then it will not qualify in the 'other' category.
Possessor grants are cumulative with the grants from the 'user', 'groups' and 'other' categories.
Return Value
On success keyctl_setperm()). | https://www.mankier.com/3/keyctl_setperm | CC-MAIN-2021-17 | refinedweb | 320 | 71.75 |
Opened 13 years ago
Closed 13 years ago
Last modified 12 years ago
#856 closed Bug (Completed)
_StringAddThousandsSep() prefixes some #'s with ,
Description
During testing, this UDF sometimes puts a ',' at the beginning of a number which isn't correct. For example, the below results in -,123,456,789,012,345.67890:
#include <String.au3> MsgBox(16,"_StringAddThousandsSep() faulty reult", _ "Result of _StringAddThousandsSep('-123456789012345.67890'): "& _ _StringAddThousandsSep('-123456789012345.67890'))
_DebugBugReportEnv() Result:
Environment = 3.3.0.0 under WIN_XP/Service Pack 3 X86
Attachments (0)
Change History (3)
comment:1 Changed 13 years ago by Gary
- Resolution set to Completed
- Status changed from new to closed
comment:2 Changed 13 years ago by TicketCleanup
- Milestone set to Future Release
Automatic ticket cleanup.
comment:3 Changed 12 years ago by Spiff59
This version, incorporates the fix required above, and also strips off leading zeros, as returning a string such as "00,000,015,746" seems improper. This version is also more than twice as fast as the exisitng one. It retains all functionality, but will return @error = 1 if an invalid string is passed to the function. Presently, the first non-numeric character passed is replaced by a decimal point, and the passed string is truncated at the second non-numeric character. Rather than that "unpredictable" or undocumented behavior, I would think an @error code would be preferable.
{{{Func StringAddThousandsSep($sText, $Sep = ',', $Dec = '.')
If Not StringIsInt($sText) And Not StringIsFloat($sText) Then Return SetError(1)
Local $aSplit = StringSplit($sText, "-" & $Dec )
Local $iInt = 1
Local $iMod
If Not $aSplit[1] Then
$aSplit[1] = "-"
$iInt = 2
EndIf
If $aSplit[0] > $iInt Then
$aSplit[$aSplit[0]] = "." & $aSplit[$aSplit[0]]
EndIf
$iMod = Mod(StringLen($aSplit[$iInt]), 3)
If Not $iMod Then $iMod = 3
$aSplit[$iInt] = StringRegExpReplace($aSplit[$iInt], '(?<=\d{' & $iMod & '})(\d{3})', $Sep & '\1')
For $i = 2 to $aSplit[0]
$aSplit[1] &= $aSplit[$i]
EndFunc
}}}
Guidelines for posting comments:
- You cannot re-open a ticket but you may still leave a comment if you have additional information to add.
- In-depth discussions should take place on the forum.
For more information see the full version of the ticket guidelines here.
This was fixed after the release version. Should be in next beta. | https://www.autoitscript.com/trac/autoit/ticket/856 | CC-MAIN-2021-43 | refinedweb | 367 | 55.34 |
How to publish a topic on NAO (c++)?
Hello,
It's my first time programming with ROS and NAO and I am trying to create a topic speech for NAO.
When I write this command in the console
rosrun proyects nao_test
the program run, but the NAO doesn't recieve the message that I send. This is my code and I think that something is missing
#include "ros/ros.h" #include "std_msgs/String.h" int main(int argc, char **argv) { ros::init(argc, argv, "nao_test"); ros::NodeHandle n; ros::Publisher speech_pub = n.advertise<std_msgs::String>("speech", 100); std_msgs::String str; str.data = "hello world"; speech_pub.publish(str); return 0; }
Thanks
can you try removing the return 0; and putting ros::spin(); instead?
Do not remove the return statement. Just add
ros::spin()or
ros::spinOnce()directly before it. | https://answers.ros.org/question/194982/how-to-publish-a-topic-on-nao-c/ | CC-MAIN-2021-31 | refinedweb | 138 | 69.38 |
How to build a REAL chat system for your startup
Every other day I see a blog post on how to create a chat system using WebSockets or how to use the magic of Firebase to build a majestic one, although let’s be honest: Building a REAL customizable chat system is a whole different story.
Now, let’s consider a complicated use case:
we have a product consisting of two parts: 1) mobile app that our end users install and 2) a web dashboard. The dashboard is used by administrators to target a certain group of audience and send them messages. The selected audience will receive the messages on their mobile apps.
Consider that we need to provide solutions for the following use-cases:
- 1–1 chat between two users
- Group chats among users
- Sending bulk messages (we refer to them as `campaigns`) from dashboard to users
- Sending individual messages to a specific user from the dashboard
campaign messages break down into following categories:
- Dashboard’s admin needs to create a group chat and add an audience group.
- Dashboard’s admin creates individual channels between the dashboard and each user and drops a message in that channel. The users as members, will receive the messages in their mobile apps.
- Dashboard’s admin sends a uni-directional message to the users. The user will recieve the message either by SMS or chat format.
Now the question is how to implement this?
Solutions
One solution is to reinvent the wheel. We all have heard of Firebase and its greatness. We can use Firebase’s Real-time database to build our own chat infrastructure.
Let’s see how the implementation looks like:
At the end you will end up with following Firebase tree:
- campaignMessageQueue
- campaignQueue
- campaignStatus
- chatMessages
- chatReadReceipts
- chats
- chatTypingIndicators
- messageQueue
- userChats
- userPushTokens
- nonChatSMSQueue
- campaignMessageQueue
Scary! Isn’t it?
Does it work? Yes.
Does it scale? Kind of.
Is it easy to deal with? Hell, no!
To support this beast, you need to dedicate a lot of time and energy.
This solution reinvents every aspect of a chat system including: Read receipts, Typing indicators, notifications, and case status for chats.
You need to have different Node workers set up which read from different queues in Firebase Tree.
Here’s a description of each worker:
campaignWorker
The worker operates on campaignQueue.
The worker receives jobs from web dashboard UI, fetches distribution list, creates new chats with users, and then places the campaign message in them. It also has the responsibility of creating jobs in campaignMessageQueue.
messageWorker
The worker operates on messageQueue.
It handles all notification tasks for normal/non-campaign messages.
campaignMessageWorker
The worker operates on campaignMessageQueue. The functionality is exactly like messageWorker, it just operates on a different queue.
nonChatSMSWorker
The worker operates on nonChatSMSQueue.
It handles sending SMS-only messages that do not create a message within a real chat.
campaignMessageWorker
The worker operates on campaignMessageQueue .
It handles sending mass non-campaign messages for a dashboard.
Sounds like a lot of work, no? Implement and maintaining all this code is not the only problem, sometimes the Node workers clog up and other times they crash and need to be restarted.
The cost of maintenance is so high that soon you are going to be looking for an alternative. Your target goal will be to eliminate reliance on Firebase as your Chat database, the question is how is that possible?
That’s when Twilio comes to play. They are mostly known for their SMS API but they also provide a chat API.
Twilio’s Programmable Chat API
Programmable Chat is a cloud-based chat product which provides a number of client SDKs and a REST API for use in integrating Chat capabilities into applications and websites. It is modeled after Extensible Messaging and Presence Protocol (XMPP) and revolves around the concept of Service Instances. Chat Services are where all the Channels, Messages, Users and other resources within a Chat deployment live.
- Each service instance could have many channels.
- Each channel could have many members.
- Each channel could have many messages.
Service instances are isolated silos and there is no way for two different service instances to communicate with one another. To send a message between two entities; first, there should be an existing channel between them. Then the entities must be added as members to the channel. Every message dropped in the channel will be published to the members. Using client SDKs (available for web, iOS and Android), we can retrieve the list of Subscribed Channels that a User is a Member of (or has been invited to) once that user logs into the client.
This model is super flexible.
Now let’s go back to the original problem we solved previously via Firebase. We will try to implement it in Twilio:
First, we create a default service instance. This service instance is used by the dashboard to send messages to the mobile users. Also, our users will be able to send private messages to the dashboard’s admin. All these channels are resided in this service instance.
Using Programmable Chat API, we can totally eliminate the reliance on Firebase. We will proceed to remove the aforementioned node workers and we will simplify the structure of our project.
Now let’s talk about Twilio’s Chat REST API. We can use it to implement all the use-cases discussed earlier. The API is used by our backend and is intended for system usage. The API can be used to orchestrate the usage of Programmable Chat, you can add members, send arbitrary messages, change users’ role and etc. Basically, it’s a god-mode for our chat system.
Here is a brief detail on how each scenario was implemented:
- User to User chat (mobile): Whenever a user needs to initiate chat with another user, the mobile client sends a request to the provided endpoint on the backend. Our backend will try to find a channel with the unique name of [user1.uuid, user2.uuid].sort.join(‘:’) in default service instance. If no channel with that unique is found, our REST Client will create a new channel with that name and adds both users as members to it. The endpoint will return the appropriate Channel ID to the mobile client in the return payload. From there, mobile client is able to send messages on that channel. Using Twilio’s REST API, we make sure that we are not creating duplicate channels between two users and we preserve the history of conversations. Next time, a user wants to send a message to a fellow user, the same channel will be used.
def create_1_to_1_chat(u1, u2)
unique_name = [u1.uuid, u2.uuid].sort.join(‘:’)
name = User.where(uuid: [u1.uuid, u2.uuid].sort).map(&:name).join(‘ — ‘)
c = add_channel(unique_name, name, channel_type: :public)
c = update_attribute(c, ‘topic’, name)
add_member(c, u1)
add_member(c, u2)
c.sid
end
2. User to dashboard chat (mobile): The process is very similar to the former use-case. The biggest difference is that, the backend will try to find or initialize the channel in dashboard’s service instance (and not the default service instance):
def create_user_to_dashboard_chat(u)
c = add_channel(u.uuid, “#{@dashboard.name”>@dashboard.name”>@dashboard.name">u.name}-#{@dashboard.name} #{u.uuid}”)
c = update_attribute(c, ‘topic’, @dashboard.name)
c = update_attribute(c, ‘dashboard_uuid’, @dashboard.uuid)
add_member(c, u)
add_member(c, @dashboard, role_sid: :channel_admin)
res = TwilioChannel.load_channel(@dashboard, c)
res
end
3. dashboard to user chat (web): Sometimes we would like to send a message to an individual user. The logic used here is the exact same one we used for “user-to-dashboard” chat.
4. dashboard-to-users (aka. Campaigns): As mentioned before, we needed to support two different types of dashboard-to-users communication.
First use-case is when the dashboard needs to create a group chat with some users in it. The request will be sent from dashboard to the backend along with the list of search params that needs to be used to define the audience. Backend will receive the request and asynchronously creates a new channel and adds the chosen audience as members to the channel.
The second use-case is when the dashboard needs to open individual channels between itself and the mobile users. Normally an admin uses this communication type to require a response from the audience. The request will be sent from dashboard to the backend along with the list of search params that needs to be used to define the audience identities. Backend receives the request and creates a different channel for each user and adds that user as a member to it. We use Sidekiq for efficient background processing.
Webhooks Events
Programmable Chat event callbacks allow you to monitor and intercept specific events in your backend service. The two categories of events are “Pre-Event” (synchronous) and “Post-Event” (asynchronous). When a callback is specified Twilio will make an HTTP request to the designated webhook URL. This request contains all relevant variable data.
We used post-event callbacks for analytics purposes and also to re-add different dashboard as members to the channels. According to docs, “Post-Event” webhooks are “notify only” and provide information after the action has completed. Unlike Pre-Event ones, these are not blocking callbacks as they are informational.
We specifically relied on onMessageSent and onChannelAdded event handlers.
Limitations
Programmable Chat API is still young and a work in progress. While we were working on creating our brand new chat experience we faced following limitations:
- In case of campaigns (bulk messages initiated from dashboard), we don’t initially add the dashboard’s admins as a member to the channel. One limitation of current Twilio Chat API is that, an entity could be a member of up to 1000 channels. According to Twilio, this is a soft limit that lets them scale better, but on the other hand, it’s kind of limiting. Thus, we only add the dashboard as a member if there is an incoming message from the mobile users. This limitation also means that we need to remove the dashboard from the channel, when the admin is done processing it ( Open vs. Closed Channels concept mentioned earlier).
- Currently, we could set custom attributes on channels and messages; although there is no way to query via them. This is super limiting and in my opinion is the most important lacking feature.
- Each channel can only have up to 1000 members in it. To be fair, I think any group chat with more than 20 members in it is a place of utter chaos, therefore I don’t consider this a real limitation.
Conclusion
Overall, I think Twilio provides users with a much smoother experience building a chat system compared to Firebase.
In the long term, a chat system powered by a Pub-Sub protocol will be the real winner in terms of scalability and maintenance.
Let’s just know that there are different solutions for building a chat system. When you need to decide which solution works better for you, try to make a list of pros and cons. Reinventing the wheel is not always a bad idea, but you also need to consider the resources at hand. Being a startup, it’s vital to move fast. Now you could move fast without sacrificing quality by just using the right tool.
Resources: | https://daqo.medium.com/how-to-build-a-real-chat-system-for-your-startup-bdbfce744e2b?source=user_profile---------5---------------------------- | CC-MAIN-2021-39 | refinedweb | 1,893 | 64.2 |
SVN Client/Mac OS X/Java Update 1.6.0_31: A task(commit, update, refresh, etc) could sometimes fail with an IndexOutOfBoundsException.
Mac OS X: Fixed .sh scripts to work correctly with relative paths in arguments.
SVN Client/Mac OS X/Java Update 1.6.0_31: A task(commit, update, refresh, etc) could sometimes fail with an IndexOutOfBoundsException.
Mac OS X: Fixed .sh scripts to work correctly with relative paths in arguments.
DTD Validation: Unexpected(invalid) elements were sometimes not reported when validating with a DTD.
Mac OS X: Resolved a critical issue that prevented the application from starting with Java SE 6 Update 27(1.6.0_27).
The "Selected project files" scope from the "Find/Replace in Files" dialog did not work when the dialog was invoked from the Find menu.
Author API bugfix: an Author fragment containing change tracking markers was not serialized correctly.
The results of the "Find All" action were affected by any modification in the editor content. The effect was that when selecting a "Find All" result from the list, the cursor was positioned incorrectly in the editor.
Sometimes the Eclipse platform user interface was blocked while an XML file was opened in the Oxygen plugin.
Fixed a NullPointerException that appeared when the Oxygen plugin was installed in an Eclipse environment that included Maven(and/or WTP).
The action of renaming an unversioned file in the Working Copy view of the SVN Client tool removed the file from disk.
The application could not open files from disk after an upgrade from an old version to the latest version due to a bug of importing automatically the user preferences from the old version.
The action Indent on Paste reported an error when it was executed in the XSLT editor.
Now an option declared in a XProc transformation scenario does not overwrite anymore a variable with the same name that is declared in a XProc script that is used in the scenario.
Pressing Enter under a folded element scrolled the edited document to other document fragment instead of keeping the same edited fragment visible.
Now a validation error message obtained by running a validation scenario displays the main validated file from the scenario as the location of the error.
The validation of a XML document that included a XML signature was very slow due to downloading the schema from the W3C website. Now the schema comes with Oxygen so that the validation is fast.
Fixed a StackOverflowError in folding action Collapse Child Folds.
The Paste action did not insert the pasted text in a correct location in Author mode in some cases.
A wrong error message was reported instead of the correct error message from the Schematron schema when a Schematron schema was applied through a NVDL schema.
A NullPointerException was reported when generating HTML documentation for an XSLT stylesheet.
The application could not exit due to a NullPointerException obtained on the Exit action. It happened on very rare cases due to the data collected for reporting usage statistics.
A NullPointerException was reported when creating a new XML file from a W3C XML Schema if one of the options "Add optional content" and "Add first choice particle" was selected and the schema did not have a global element.
Fixed slow edit in large Relax NG schemas when schema diagram was visible.
Short description of a DITA topic was displayed twice in the XHTML output of a DITA transformation, before and after the topic title.
Short description of a DITA topic was not included anymore in the meta description tag in the XHTML output of a DITA transformation.
The application blocked in the dialog box for creating a new XML document from some remote XML Schemas when the dialog was closed too quickly due to the delay that was needed for parsing the remote schema and updating the dialog box.
Fixed a NullPointerException that happened when opening an XML file in the XSLT Debugger perspective.
MAC OS X: Ctrl+click on a file or folder in Project view or Archive Browser view triggered both the contextual menu and the rename action. Now only the contextual menu is displayed.
The tool that creates documentation for XML Schema did not generate in the documentation valid XML instances from a hierarchy of XML Schema types.
Fixed a NullPointerException that appeared when opening or editing a W3C XML Schema.
When a validation scenario was associated with the current document and the Check Well-formed action was started, it was applied in fact a number of times equal with the number of validation units from the scenario.
SSH connections remained dangling when opening/saving files from a SFTP server.
Now the floating license servlet outputs more detailed logging messages. The logging parameters are configurable according to the mechanism of the container (Apache Tomcat, etc).
The auto-close empty tag feature closed the current start tag when the user typed a '/' character even if this character was typed inside an attribute value.
When pasting text in Author editing mode the whitespaces between words with different properties and enclosed in different tags were lost.
Split editors no longer reset their position whenever the document is modified by an action.
Any preference with a value different than the default one that was set by the user in the Preferences dialog was not applied correctly in the application and was not preserved when the application was restarted. It happened when that preference was stored at project level.
Now the list of actions from the contextual menu of the DITA Maps Manager view can be filtered from a custom Startup plugin.
Fixed a NullPointerException in the SVN Client tool that appeared when a SVN working copy was loaded after switching from other working copy, which tried to compare the current content of the working copy with the content cached at previous accesses of the same working copy.
Sometimes the SVN Client tool hanged on startup when the auto-refresh option for SVN working copies was activated.
The password of the URL of a remote document that was opened by HTTPS or SFTP was displayed in the page header when the document was printed from the Oxygen application.
The embedded help could not be opened in the Large File Viewer tool started from Oxygen XML Author (only on Mac and Linux platforms).
The text copied from a Web browser or an Office suite application and pasted in Author editing mode had 2 strange characters at the beginning of the pasted text due to a wrong detection of the text encoding (only on the Linux platform). The same problem appeared in drag and drop operations between a Web browser/Office suite application and Author editing mode.
Now the special XML characters like '<' and '&' are not escaped anymore in Grid editing mode inside CDATA, XML comment and DOCTYPE subset nodes of the XML document.
In some custom Eclipse-based environments like ZendStudio 8 the Pretty Print action of the Oxygen plugin for Eclipse inserted 'null' strings instead of newline characters when executed on a one-line XML document for breaking it on more than one line.
An XML comment marked with change tracking was ignored by the change tracking management actions when some whitespace characters separated the XML comment and its change tracking marker.
On Mac and Linux computers the user help could not be opened from the Author tool of the Oxygen Editor product.
The XSD documentation generation tool and the XSLT documentation one could not be used if the user enabled the option for DTD validation in XSLT 2.0 transformations in the user preferences.
The search references/declarations now ignore the hidden folders like .svn by default.
The Preview action invoked from the Rename Component dialog displayed nothing when the Rename Component action executed on a resource that was not part of the current search scope.
Avoid deadlock on opening files that appeared on some Windows computers.
Some XQuery compilation errors were not reported in the XQuery editor.
Paste in the Author editing mode: Fixed error due to side effect of Saxon Enterprise Edition validation option. Also fixed problem of duplicated paragraphs in pasted content.
Fixed a NullPointerException that appeared when deleting a profiling attribute value.
Fixed an IllegalArgumentException that appeared when loading a huge vectorial image in Author editing mode.
Now the DITA conref references without fragment identifier are resolved correctly in Author editing mode.
The tools for generating PDF documentation for an XSLT stylesheet and for a W3C XML Schema did not use the FOP configuration file set in the user preferences.
References to remote Webdav or FTP images can be inserted in a document edited in Author mode using the toolbar actions.
Fixed errors that appeared in some cases when opening the XSLT Debugger perspective in the Oxygen Eclipse plugin.
Fixed a NullPointerException that appeared when searching XSLT template references in the XSLT editor.
Now the XLink namespace is declared by default when inserting an image in a DocBook 5 document edited in Author mode.
Fixed a ConcurrentModificationException that appeared when an XML document with bidirectional language support was opened automatically on startup.
Fixed an error that appeared when the Colors page was opened in the Preferences dialog box when the current version of Oxygen was installed as an upgrade from an older version.
The text typed in the editable text areas of the Find/Replace dialog was not visible when a dark color (for example black or dark blue) was set in the user preferences as background color of the editor panel.
The namespace of XSLT parameters was not computed and displayed correctly sometimes when editing an XSLT stylesheet.
The combo box from the Insert Entity dialog did not receive the focus automatically when the dialog was opened.
The default value of the args.xhtml.toc parameter of the DITA WebHelp transformation scenario did not end with a file extension.
Fixed inconsistent formatting in the Author editing mode when an entity reference was present between elements.
Fixed a StackOverflowError in the Import Text action that was applied to a file from history that did not exist on disk anymore.
Fixed an ArrayIndexOutOfBoundsException in the XSLT Debugger perspective.
Fixed a memory problem in the XSLT debugger. The memory was not released completely at the end of the XSLT transformation if breakpoints existed.
In Author mode in the Eclipse plugin the size and style of the default font could not be configured in the user preferences.
On Linux machines the installer wizard does not offer the option of starting the application at the end of installation when the installer was started as root user. In case of upgrade if the previous version was installed as normal user the user preferences could not be imported automatically in the new version because the application was started as root user at the end of installation.
Fixed a BadLocationException that appeared when a document with XML folds was modified in other application.
Fixed a BadLocationException that appeared when moving the mouse while pressing the left button in a document with XML folds.
The shortcut of the Stop Debugger action did not work because it was captured by a different component.
Fixed an error in the dialog for creating a new document. The error appeared when the new document was based on a DTD and the user tried to type a root element name in the combo box that listed all possible root elements.
Outline view was not able to display a function name that followed the '}}' sequence of characters in an XQuery document.
The application crashed at startup when it tried to reopen automatically an XSLT stylesheet that contained an <xsl:decimal-format> element.
Fixed a NullPointerException that appeared when opening an XSLT stylesheet that contained an <xsl:decimal-format> element.
Fixed a NullPointerException that appeared when editing a document with XML folds and trying to change the font size with Ctrl + mouse wheel.
The line number was not painted correctly in a document with XML folds when trying to change the font size with Ctrl + mouse wheel.
The validation against a Schematron schema through a NVDL schema that used the Schematron one always failed.
Now the secondary toolbar is present again in the DITA Maps manager view after it was removed in a previous version.
The menu actions for inserting generic topic references were promoted to the top of the contextual menu of the DITA Maps Manager view.
Fixed a memory problem that resulted in an Out Of Memory error when there are many validation errors detected by a Schematron schema.
The shortcut for closing the current view (Ctrl+F4) was removed because it was also used for closing an editor so it had the unexpected effect of closing a view that received the focus. Now the shortcut is associated only with the action that closes the current editor.
The action for adding or editing the conref attribute in a DITA topic was not applied on the selected element if the whole element was selected so that the cursor was positioned after the element end tag.
The user defined file templates that had an unsupported extension were filtered in the new file dialog.
Fixed a NullPointerException that appeared when creating a new profiling condition set.
Fixed a BadLocationException that appeared on some editing actions like pretty print when both folding and line wrap were enabled.
The DocBook to PDF transformation did not render MathML equations in the PDF output.
Fixed the validity errors from the template for new EPUB files.
Simple quote characters and double quote ones could not be inserted in the grid editing mode.
Special characters were displayed as escaped characters in the Open using FTP/WebDAV dialog.
The rev attribute was not ignored when the validity of a DITA map was checked based on a profiling condition set.
The DITA topic references that had external scope or peer scope were parsed completely when checking the map validity and completeness. If these topic references did not specify a format they were not reported as errors.
When checking the DITA map validity all the keydef elements that did not have a href attribute were reported as errors.
Removed the file association for EPUB files. Now the files with the .epub extension are not opened by default with the Oxygen application if the user did not specify that in the installer wizard.
Fixed a NullPointerException in the refresh task that was executed automatically when the user switched back to the window of the SVN Client tool.
Fixed a NullPointerException that appeared when all the occurrences of a user defined name were highlighted in the XSLT editor.
The edit conflict action from the SVN Client tool did not open the two compared revisions of an image file with the image viewer. This produced encoding errors.
The folded state of the child elements was not preserved when the parent element was collapsed and expanded in the editor panel.
The Find/Replace in Files dialog box did not display the checkbox for enabling regular expressions when the user interface language was set to German or Dutch because the labels from the dialog box were too long in these languages.
When the ID of an Author action was changed by editing the Author document type that contained the action the new ID was not set correctly so that the action disappeared from the Author toolbar. | http://www.oxygenxml.com/build_history_12_2.html | CC-MAIN-2018-09 | refinedweb | 2,562 | 51.78 |
A Data Scientist is the one who not only knows how to use machine learning but the one who knows when to avoid it.
Today, I will stand on the shoulder of a giant i.e. John Tukey, the father of exploratory data analysis(EDA). Often, in a hurry to fit a machine learning model, people usually ignore the important step of Data Analysis. Hence, it is quite possible that they might end up using ML where it may be overkill; usually seen amongst beginners. In this article, we will explain on this with two simple datasets viz. Iris and Haberman.
Also read: Motivating Data Science with Azure Machine Learning Studio
The Iris Dataset
Iris is an ideal dataset to introduce a student to data analytics. First created by RA Fischer, this dataset has 150 samples distributed amongst 3 classes of flowers viz. Setosa, Virginica and Versicolor. Further, it has 4 features viz. petal length, petal width, sepal length, and sepal width. Let us load the data into a pandas dataframe.
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np Iris = pd.read_csv("iris.csv")
The last column ‘species’ is the target variable i.e. the label to be classified. A newbie to data analytics might be tempted to attack this problem with some kind of classification algorithm. However, it is always advisable to hold your horses and take a ‘look’ at the data first. Hence, let’s do some exploratory data analysis.
Univariate analysis.
Univariate analysis typically comprises PDF’s and CDF’s and Box plots. Let us draw the three of them to uncover some insights on the Iris dataset.
#Using Seaborn we create a distribution of Petal Length sns.FacetGrid(Iris, hue="species", size=5) \ .map(sns.distplot, "petal_length") \ .add_legend(); plt.show();
This gives us a distribution plot of the column petal length, which is as follows.
A first look at the distribution of petal length reveals that setosa is linearly separable from the other two classes viz. versicolor and virginica. Hence, it can be classified with a simple if-else condition like petal_length<=2.
However, there is some overlap between versicolor and virginica. To classify a flower as versicolor or virginica in the overlapping region, we need to determine the probability that the flower is versicolor or virginica. Hence, let us plot the CDF of petal length.
import numpy as np Iris_setosa = Iris.loc[Iris["species"] == "setosa"] Iris_virginica = Iris.loc[Iris["species"] == "virginica"] Iris_versicolor = Iris.loc[Iris["species"] == "versicolor"]
counts, bin_edges = np.histogram(Iris_setosa['petal_length'], bins=10, density = True) pdf = counts/(sum(counts)) cdf = np.cumsum(pdf) plt.plot(bin_edges[1:], cdf, label = 'setosa') counts, bin_edges = np.histogram(Iris_virginica['petal_length'], bins=10, density = True) pdf = counts/(sum(counts)) cdf = np.cumsum(pdf) plt.plot(bin_edges[1:], cdf, label = 'virginica') counts, bin_edges = np.histogram(Iris_versicolor['petal_length'], bins=10, density = True) pdf = counts/(sum(counts)) cdf = np.cumsum(pdf) plt.plot(bin_edges[1:], cdf, label = 'versicolor') plt.legend() plt.show();
The above figure gives us the CDF of the petal length for all the three classes. Let us consider a particular flower with a petal_lenth of 5. A keen look reveals that the probability of that flower being versicolor is 0.8, while the probability of the flower being virginica is 0.2.
Nonetheless, this dataset is fairly easy and linearly separable. With some data cleansing and a few conditional statements, we can classify the three flowers without using ML. However, to appreciate the importance of stochastic analysis and later on, Machine Learning, let us go through another dataset named Haberman’s dataset.
The Haberman Dataset
The Haberman’s dataset is a breast cancer survival dataset. It studies the survival of patients after undergoing breast cancer surgery. Let us load the data first.
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np Haberman = pd.read_csv("haberman.csv") Haberman
In this dataset, the features are age, year and nodes, while the label is status. The ‘status’ comprises values i.e. 1 and 2.
1= patient survived after 5 years 2= patient died after 5 years
Now, let us do some ‘label’ engineering and transform the values 1 and 2 into the binary values ‘Survived’ and ‘Died’.
Haberman.loc[(Haberman['status'] == 1), 'status'] = 'Survived' Haberman.loc[(Haberman['status'] == 2), 'status'] = 'Died'
The transformed data is as follows.
Now, let us start with univariate analysis of the dataset.
Univariate Analysis
Firstly, let’s plot the distribution of the feature ‘age’.
#pdf of age sns.FacetGrid(Haberman, hue="status", size=5) \ .map(sns.distplot, "age") \ .add_legend(); plt.show();
Next, let’s plot the distribution for the variable year.
#pdf of year sns.FacetGrid(Haberman, hue="status", size=5) \ .map(sns.distplot, "year") \ .add_legend(); plt.show();
Finally, let’s plot the distribution of the number of nodes
#pdf of nodes sns.FacetGrid(Haberman, hue="status", size=10) \ .map(sns.distplot, "nodes") \ .add_legend(); plt.show();
The above three plots clarify that none of the features makes the two labels linearly separable. However, can a combination of variables make them linearly separable? Let us perform bivariate analysis.
Bivariate Analysis
If the number of features is less, pair plots are the best form of bivariate analysis. Let us plot the pair plot.
sns.set_style("whitegrid"); sns.pairplot(Haberman, hue="status", size=3,vars=['age', 'year', 'nodes']); plt.show()
One can clearly see that even a combination of variables does not make the labels linearly separable. We can go on with different visualisations. However, isn’t this sufficient motivation to go further with Stochastic Analysis and eventually Machine Learning? | https://www.data4v.com/knowing-when-to-consider-machine-learning/ | CC-MAIN-2022-05 | refinedweb | 938 | 60.61 |
User Name:
Published: 03 Sep 2008
By: Rupesh kumar Nayak
An introduction to CLR Database Objects.
The Common Language Runtime (CLR) is the engine behind the .NET Framework that handles the execution of all managed application code. It plays an intermediation role between the operating system and .NET applications. Applications developed in the .NET platform don’t directly interact with the operating system. Rather, they talk to the CLR and the CLR manages/handles the execution of the applications.
When we write a program using any of the .NET languages like C#, VB or C++, the source code doesn’t get compiled to machine code. Each language specific compiler (VB compiler, C# compiler etc) converts the source code to an intermediate language code which is known as IL code. The IL code then is converted to machine specific code by the CLR engine at runtime.
The CLR is responsible for managing memory allocation, starting and terminating threads and processes and enforcing security policy at runtime.
We all are familiar with T-SQL to write database objects such as stored procedures, triggers, functions, cursors etc. It has always been difficult to write database objects with more complex logic like array operations, complex math calculations in traditional T-SQL. On the other hand, it becomes an easy task to attain the same functionality in any server side language like C#, or VB.NET. If we could write the database objects in any of our server side languages and run them on SQL server then that would definitely solve the problem of writing database objects with complex logic. To accomplish this, SQL Server 2005 has integrated the Common Language Runtime (CLR), which is hosted within the SQL Server database Engine. It provides the ability to create database objects using .NET languages like C#, VB.NET etc. These objects include stored procedures, triggers, and functions and support logic and features that are not available in native T-SQL.
The integration of the CLR with SQL Server doesn’t replace T-SQL at all. It extends the capability of SQL Server in several important ways. While T-SQL, the existing data access and manipulation language, is appropriate to accomplish set-oriented data access operations, the integration of the CLR with SQL Server 2005 brings with it the ability to create database objects using modern object-oriented languages with the existing class support from the .NET framework. This helps to create database objects with more complex logic, better computation capabilities, OOP’s concepts, structured error handling mechanisms, thus facilitating code reuse.
CLR integration in SQL server 2005 supports the following object types:
By default CLR integration is disabled in SQL server2005. To be able to run the CLR database objects on SQL server we have to enable the CLR integration feature.
Open up a query window in SQL Server Management Studio and execute the following code:
To disable the CLR on SQL server execute the following in the query window of SQL Server Management Studio:
SQL Server has a list of supported .NET Framework libraries. These supported libraries do not need to be explicitly registered on the server. In fact, SQL Server loads them directly from the Global Assembly Cache (GAC) when required.
The libraries/namespaces supported by CLR integration in SQL Server are:
Unsupported libraries can still be called from your CLR database objects. The only thing you have to do is register the unsupported library in the SQL Server database, using the CREATE ASSEMBLY statement, so that it can be used in your code.
CREATE ASSEMBLY
1. Open Visual studio and create a new project, Select Project Type as Database and the SQL Server Project as template, give it a name (for example, MyCLRDatabaseObject), solution name and location. If you want to create it in any specific location then you can set that in the location field, otherwise it will create the project in the default location.
2. A dialog will pop up to set the new database references. Select the server name from the list and set the database authentication. Once you select the server name from the list then the database connect section will be enabled. Select a database name from the list where you want to deploy your object. Also you can test the connection by clicking on the Test Connection button.
3. Once you are done with adding database references, the program will prompt you to enable debugging for SQLCLR for this connection. Choose Yes.
4. In the Solution Explorer pane right click on Project, and then click on Add; you will be shown a list of objects in the menu. Select the desired object from the menu list. Alternatively you can select Existing Item and then the desired object template from the template window. We selected StoredProcedure from the Template list for our sample application.
5. Upon clicking the object name from the menu list, the following template window will be opened. Select the template type and rename it as per your requirements; then click on the Add button. Here we have selected the Stored Procedure template and renamed it to MyFirstCLRstoredProcedure.vb
MyFirstCLRstoredProcedure.vb
6. When we click on the Add button the program will generate the following code snippet in the page.
The class contains a single static method that will become a CLR stored procedure. The class is defined as public to denote that other classes can instantiate objects of this type. In the above code snippet MyFirstCLRStoredProcedure is the function which is going to be a CLR stored procedure. Methods that will become database objects must be declared as public static in C#, or Public Shared in Visual Basic. The keyword public means that they are accessible from outside and static (or shared) means that they behave like procedures (not like methods of objects that have state).
public
public static
Public Shared
static
shared
We have added following lines of code.
In the above code snipet we have opened a connection of type context connection. It is possible to have user credentials passed, but such a connection would not be part of the caller transaction. In fact, it would not be able to access to temporary tables created on the caller. Also, it would be slower because of the additional layer the commands and results would have to pass through. So it is advisable to have a context connection in a CLR object.
You can open the context connection by simply using “Context Connection = true” instead of the regular connection string.
“Context Connection = true”
I have written a simple SQL query in the Command Text section. This should return all the rows present in the Employee table. We retrieve the data from the Table into a Data Reader and then return those data rows from the Reader through SqlPipe using the Send method.
SqlPipe
Send
7. We will now create the stored procedure assembly. Select Build >> Build MyCLRDatabaseObject from the main menu. If there is no error during compilation, then Visual Studio will create a MyCLRDatabaseObject.dll assembly in the Bin folder.
8. Deploy the stored procedures by selecting Build >>Deploy MyCLRDatabaseObject from the menu. If you get a Deploy Succeeded message in the bottom section then that means the CLR database object has been successfully deployed to SQL server.
9. Open the Query window in SQL Server Management Studio and execute the Database object against the respective database.
We can check our CLR stored procedure MyFirstCLRStoredProcedure in the management studio by executing it.
MyFirstCLRStoredProcedure
Here we get the result from the database table. We can have a number of database objects inside a single class and then deploy the assembly to the server at once. This would definitely save a good amount of time over deploying each one independently.
10. You can create the table and check the stored procedure at your system.
Run the following scripts to create the tables in your SQL server.
To insert some dummy data in to the Employee table, execute the following script:
We can also develop and deploy the CLR Database objects without the help of Visual Studio. We only require the .NET framework which contains a compiler that can be used to deploy the CLR object.
1. Open Notepad or any other editor and copy the following code. Then save the file as MyFirstCLRStoredProcedure.vb.
MyFirstCLRStoredProcedure.vb
2. The .NET Framework ships with the C# (csc.exe) and the Visual Basic .NET (vbc.exe) command line compilers. You can find these compilers in the folder where the .NET Framework is installed. These compilers can be found in C:\WINDOWS\Microsoft.NET\Framework\Version Name.
We can compile our class file MyFirstCLRStoredProcedure.vb using .NET framework SDK. It should be located at:
Start>>All programs>>Microsoft .NET Framework SDK v2.0>>SDK Command Prompt.
Write the following command in the SDK command prompt and hit enter.
Here setting the /target switch to library notifies the compiler to create a .dll file. E:\CLRObject\MyFirstCLRStoredProcedure.vb is the physical location of the class file.
/target
library
Since the source code is in Visual Basic we have used the above command. If the source code is written in C# then you have to use the following command:
Upon running successfully , the above command will generate a dll in the same folder where your source code is present.
3. To use the assembly we need to register it in SQL Server using the CREATE ASSEMBLY statement. Open the Query window in Management Studio in SQL server and run the following T-SQL code against the respective database.
Here we have set MyCLRObject as the name of the assembly and E:\CLRObject\MyFirstCLRStoredProcedure.dll as the physical location of the dll file. The WITH PERMISSION_SET clause controls the type of access to external resources from the assembly.
WITH PERMISSION_SET
There are three options for PERMISSION_SET
SQL Server does not allow registration of more than one version of an assembly with the same name, so you must assign a unique name to your assembly. If you have an old version assembly running in SQL Server then you must drop that assembly and then create a new one.
4. Once our assembly is registered on SQL server, then we can create database objects. Run the following T-SQL code on the Query window in Management Studio in SQL server against the respective database to create a stored procedure.
Here MyFirstCLRStoredProcedure is the stored procedure name and the EXTERNAL NAME contains a reference to the specific Assembly, Class and Method name in the format as Assembly_Name.Class_Name.Method_Name.
EXTERNAL NAME
Assembly_Name.Class_Name.Method_Name
Since we have registered the assembly as MyCLRObject, and in the class file we have Public Class as StoredProcedures and the Shared Method as MyFirstCLRStoredProcedure, so our EXTERNAL NAME referenced to MyCLRObject.StoredProcedures.MyFirstCLRStoredProcedure.
MyCLRObject
Public
StoredProcedures
Shared
MyFirstCLRStoredProcedure
MyCLRObject.StoredProcedures.MyFirstCLRStoredProcedure
5. When we execute the stored procedure in SQL Server we get the following results.
This article described the methodology by which we can develop a CLR database object with the help of Visual Studio2005 or without it. It is not advisable to create CLR Objects for each and every task; it would be beneficial to use CLR database objects where we require complex programmatic logic, or require the .NET Framework's base class library to accomplish a task. If we are working on any relational data managing or any set-based operations then T-SQL is the best. | http://dotnetslackers.com/articles/sql/Introduction-to-CLR-Database-Objects.aspx | crawl-003 | refinedweb | 1,910 | 55.34 |
Without the .NET Framework, programmers must choose from a wealth of APIs or libraries that support system services. For example, if you want to write GUI applications on Windows, you have a slew of options from which to choose, including the Win32 API, MFC, ATL, VB, and so on. Once you've chosen the library, you have to learn how to use the structures, classes, functions, interfaces, and so forth that the library provides. Unfortunately, this knowledge doesn't transfer directly into a different environment. For instance, there's a big difference between the code to manage IO in MFC and the code to manage IO in VB.
One of the goals of the .NET Framework is to bring commonality to application development by providing a framework of common classes to developers who are using compilers that generate IL. This set of classes, known as the Base Class Library (BCL), is extremely helpful: if you know how to take advantage of IO functionality in .NET using your favorite language, you can easily port that code to another language. This is possible because the namespaces, classes, methods, and so forth are equally accessible in all languages. For example, you can output a line of text to the console the same way across all .NET languages by using the WriteLine( ) method of the Console object, as we have seen elsewhere in this book. This consistent framework requires less development training and enables higher programmer productivity.
Since a full discussion of the entire set of classes in the .NET BCL is beyond the scope of this book (see O'Reilly's In a Nutshell .NET series), we talk about the System.Object class and present the major namespaces in the .NET Framework, opening the doors for you to step into this world.
Every type in .NET is an object, meaning that it must derive directly or indirectly from the Object class. If you don't specify a base class when you define a class, the compiler will inject this requirement into the IL code. The Object class supports a commonality that all .NET classes inherit and, thus, automatically provide to their consumers. The Object class exposes the public methods listed in Table 3-1, which you can invoke on any given .NET object at runtime.
Examine the following program, which illustrates the use of all these methods:
using System; namespace Cpm { class CPModel { public static void Main( ) { CPModel c = new CPModel( ); // Test for self equivalence. Console.WriteLine("Equivalence:\t" + c.Equals(c) ); // Get the hash code from this object. Console.WriteLine("Object hash:\t" + c.GetHashCode( ) ); // Use the type to obtain method information. Console.WriteLine("Object method:\t" + c.GetType( ).GetMethods( )[1] ); // Convert the object to a string. Console.WriteLine("String representation:\t" + c.ToString( ) ); } } }
If you compile and run this C# program, you get the following output:
Equivalence: True Object hash: 2 Object method: Boolean Equals(System.Object) Object dump: Cpm.CPModel
The boldface line displays the second method of the CPModel class. If you look back at the program's code, you'll see that we use the GetType( ) method to get the type, and then we use the GetMethods( ) method to retrieve the array of methods supported by this type. From this array, we pull off the second method, which happens to be Equals( ), a method that's implemented by System.Object.
As you can see, the System.Object class provides a mechanism for runtime type identification, equivalence, and inspection for all .NET objects.
Table 3-2 is a short list of important namespaces and classes in the .NET Framework that provide support for almost any application that you will develop. These are the namespaces that you'll find yourself using again and again the more you develop .NET applications. For more information, consult MSDN Online or your SDK documentation, as a detailed discussion of these namespaces and classes is beyond the scope of this book.
Keep in mind that if you know how to use any of the classes in these namespaces, you can write the code to take advantage of them in any language that targets the CLR, because the class and method names remain consistent across all .NET languages. | http://etutorials.org/Programming/.NET+Framework+Essentials/Chapter+3.+.NET+Programming/3.1+Common+Programming+Model/ | CC-MAIN-2018-17 | refinedweb | 702 | 64.51 |
Day 3 at JavaOne 07
By divas on May 11, 2007
I saw one of the best sessions on Thursday, Using Ajax With POJC (TS-9511). Craig talked about the various ways to Ajaxify plain old JavaServer Faces components and discussed the various challenges. One important point that he made is that you need to consider whether it is necessary to keep the client state and server state synchronized. The answer to this question can make a difference on what technology you choose. Jayashri followed with a quick demo on how easy it is to use Ajax4jsf to dynamically update one field based on the input in another, and then Matt did the same using Dynamic Faces. The session ended with a kick-butt demo by Matt, who built the Currency Trader application in 3 minutes 10 seconds, with music no less! (Note: I am extremely biased because these three are among my favorite engineers to work with).
They are redoing the talk on Friday, so don't miss it.
The AJax and JavaServer faces panel was another great session (TS-6713) because they were very interactive with the audience and answered some hard questions. The key takeaway for me was that you should not expect interoperability from the various Ajax JavaServer faces frameworks due to some issues with JavaScript, especially if the framework doesn't utilize namespaces well. At least not now. JSF 2.0, whenever that comes out, will include some Ajax features which hopefully will make it easier for these frameworks to play together.
Both of these talks discussed why you would want to use JSF components in your Ajax apps. The both mentioned that JSF offers accessibility, security, validation, conversion, and localization. | https://blogs.oracle.com/divas/entry/day_3_at_javaone_07 | CC-MAIN-2016-26 | refinedweb | 286 | 59.64 |
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; InfoPath.1) Build Identifier: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.1) Gecko/20060111 Firefox/1.5.0.1 Firefox enables certificates with keyusage nonRepudiation as SSL client certificates. nonRepudiation keyusage is used for certificates that is to be used with advanced signatures, not for authentication which corresponds to SSL client authentication. RFC 3280 states: ." This conflicts with that Firefox uses this as a SSL client certificate, since SSL isn't a non-repudiation service. At least in the nordic countries, it is very common to use a certificate pair, where one certificate is used for authentication purposes, for example client authenticated SSL (with keyusage digitalSignature, keyEncipherment) and the other is used for non-repudiation signatures with software outside of the browser. Reproducible: Always Steps to Reproduce: 1. Import a nonRepudiation certificate or connect a pkcs#11 security device which exposes a nonRepudiation certificate 2. Go to a site which accepts the CA for SSL authentication Actual Results: Firefox logs on with the nonRepudiation certificate. Some web servers regards the certificate as invalid for authentication and SSL negiotiation fails with those. Expected Results: SSL negiotiation should never be attempted with a nonRepudiation certificate It seems that bug# 217721 introduced the behavior to allow login with nonRepudiation. In version 1.0.5-7 this worked as expected.
-> NSS
Actually the behavioral change was the result of the fix for bug 240456 . I might agree that a cert with only NR KU (not NR + others) ought not be used with SSL at all (client or server), since SSL leaves no verifiable signature after the fact. However, I think there are some countries whose national PKI standards rely on NR certs being usable for email signatures and SSL client auth.
*** Bug 328458 has been marked as a duplicate of this bug. ***
> However, I think there are some countries whose national PKI standards > rely on NR certs being usable for email signatures and SSL client auth. As I read 240456, that only handles the way a OCSP response is verified, where the RFC 3280 doesn't state anything about keyusage in the OCSP responder certificate, but rather EKU. The sideaffect that nonRepudiation is accepted in all cases where digitialSignature is required is IMHO wrong. I agree that the validation of the OCSP signer certificate should accept NR keyusage, but SSL should not. I haven't heard of a country using nonRepudiation keyusage only certificates in SSL. Can you give any example? The bug#217721 was reported in 2003-08-29 and the reporter hasn't even confirmed the fix or posted comments after 2004-03-12. AFAIK the germans also use nonRepudation certificates for signatures only, so I was a bit surprised that the reporter was german. I still think this is in conflict with RFC 3280 and should be fixed. If you still disagree and refuses to fix this, I have two suggestions: 1. Make sure certificates with other keyusage that nonRepudiation only are automaticly choosen first. As it is right now, our nonrep certificate is always choosen by Firefox, even though there is a digitalSignature certificate also. 2. When the option to manually select a certificate to log on with is selected, there is no way to distinguish a nonRepudiation certificate from a digitalSignature certificate. The GUI has to be updated to reflect the keyUsage.
Sorry, I used the wrong RFC for OCSP. It's supposed to be 2560, not 3280 as I wrote.
(In reply to comment #2) > However, I think there are some countries whose national PKI standards > rely on NR certs being usable for email signatures and SSL client auth. Refering to the SSL client certificate must have key usage digitalSignature. SSL servers do not accept certificates with key usage nonRepudiation so I think this issue should be fixed.
*** Bug 346100 has been marked as a duplicate of this bug. ***
This is definitly a bug. in RFC 2459 (X.509 v3), chapter 4.2.1.3 (Key Usage), it is specified that ." If that bit is not present, it shouldn't be used for authentication. If you only have the nonRepudiation bit, it shouldn't be used: "The nonRepudiation bit is asserted when the subject public key is used to verify digital signatures used to provide a non-repudiation service which protects against the signing entity falsely denying some action, excluding certificate or CRL signing." The point is not to disable certificates that have both bits set, but only those which don't have the digitalSignature set.
Giving NR client auth complaints to Bob. It is sufficient to remove the patch from that bug. Theoretically thinking: If the key has a usage 'nonrepudiation' how come 'signing' can be translated into 'nonrepudiation', when it means something else in real life (yes, technically it is signing)? In addition to flushing most if not all European digital signature schemes, it definitely renders the usability of firefox into close to 0, as the usability of 'client certification selection' every time a new session is opened is as good to end users as 'not functioning correctly'. Most if not all European eID cards have two or more certs/keys, one being for authentication and one for digital singatures (and digitalsignatures having nonrepudiation usage only) So unless a proper solution (nonrep having a lower priority or something similar) is made, please do try to get this thing changed in FF 2.0.
This is seriously blocking FF 2.0. Having it the same way in FF 2.0 as in FF 1.5 shall cause people to drop using smartcards in EU with FF.
I'm not in a position to decide about this bug here, but it will be very hard (or rather: impossible) to get this fixed for FF2. Firefox 2 is basically ready for shipping and I doubt any code changes will be allowed to get in (except for security bugs and such). If this bug will get fixed, then in a Firefox 2.0.x release at earliest.
If this is important enough, we can fix it for Firefox 2 still. Bob, Nelson, Wan-Teh: please advise on whether there is an expedient fix, and if so, who will make the patch. /be. I think the jury is still out. I wouldn't advise to stop FF 2.0 for it. Expect more vociferout response here.
(In reply to comment #14) > 90% of people who are not forced to use FF don't look back if they have to do manual steps for things that JustWorks with other browsers. > situation where they believe they should not use it. ("Doctor, it hurts when > I do this.")
AFAICT there are two issues: 1) A claim that we don't follow the RFC. 2) The argument that it just works in other browsers. Both are compelling by themselves. Firefox has gained market share in part by emulating IE quirks (e.g., undetected document.all). I don't advocate making up certificate-related quirks, but I'd like to understand whether 2 is caused by 1 above. If so, we should fix this bug based on item 1. If the RFC is incomplete or ambiguous, then 2 still may be decisive (de-facto complete standard trumps de-jure incomplete/ambiguous standard). /be
Hi Nelson, all, I can imagine that people who have a "single key for everything" do want this feature. Or that there are other good reasons (which I'm curious to hear about?) On the other hand, it's probably clear to all that e.g. eID cards that have a key for legally binding sigs don't want this key to be used to log to a web site... So: wouldn't it be possible to make it an option? (Preferably one that could be set by an installation program) Just my 2 cents... (sorry if I'd sound too vociferous:)
Brendan, The arguments would be compelling if they were indisputably true. SSL isn't an NR service. It isn't an application service at all. It is a protocol that is used by some appliation services, some of which want NR and some of which do not. There is no clear-cut standard that defines which protocols are elligible to use NR certs and which ones aren't. There may never be. For example, S/MIME email sends signed messages. Some messages (e.g. bearing contracts) are elligible for NR signatures, others are not. The appropriateness of using NR certs for signatures depends on the application (sevice) context, not the protocol used to reach that service, especially when the protocol is not exclusively linked to a single appliation service. The LDAP protocol may be linked to a single service exclusively, but SSL is not. Regarding the claim that it "works in other browsers", rather the claim is that NR DOESN'T (yet) work in other browsers, and some like it that way. In the past, when we NEVER used NR certs for any reason, the people who didn't want us to use NR certs for client auth were happy with that situation and the services who wanted their clients to be able to use NR certs with FF were unhappy. Now that we've made NR certs work, the people who don't want their clients to use NR certs claim that it worked correctly before (when it didn't work at all). They're happy to point at other products that also do not yet use NR certs. Think of signature and NR certs like Visa and Master Card cards. Imagine if a merchant who accepts Visa but not MC said "we don't want any card swipe readers anywhere to ever accept MC cards, because we don't accept them." The one argument that I've heard against using NR certs for SSL client auth that seems at all persuasive to me is that SSL client auth (today) leaves no signed record of the transaction that can be verified after the fact independently of the server's cryptographic info (keys). However, the IETF is working on extending TLS to provide that very capability. See So, I would not say that the argument against using NR certs with SSL client auth is indisputable. The SSL/TLS standards predate the use of NR certs. Today the SSL protocol lets the server tell the client the list of issuers whose client certs are acceptable to the server. It does not also let the server express its willingness (or lack thereof) to accept NR certs from a single issuer who issues both types. That may be seen as a deficiency of SSL/TLS, or alternatively, it may be seen as a deficiency of a PKI deployment that uses a single issuer for both NR and ordinary (non-NR) signature certs alike. Such a deployment failed to consider the capabilities of the extant standards for enabling clients to distinguish between the two. In the very short timeframe remaining for FF2, we can go back to the state of disallowing NR certs by backing out the fix for bug 240456, and reopening that bug. Producing a patch that allows NR for some protocols and not others is a much larger change that IMO is likely to take longer than the desired time, or to incur high risk of regression. However, I expect the howl from disabling NR certs to be greater than the howl against leaving them enabled..
(In reply to comment #15) > Nelson, what about comment 8? RFC 2459 was obsoleted by RFC 3280. RFC 3280 doesn't contradict the older RFC in many areas, but in the area of key usage, it says some different things. For example, RFC 3280 does *not* say (concerning the digital signature usage bit) "If that bit is not present, it shouldn't be used for authentication."
> For example, RFC 3280 does *not* say (concerning the digital signature usage > bit) "If that bit is not present, it shouldn't be used for authentication." Nor does rfc2459, that was an interpretation from sternmarc (outside the quote). (In reply to comment #14) >. That may be what comment 0 says, but the real issue seems to be that in countries where it's common to have both kinds of certs we're now defaulting to the NR-cert which the server rejects, and our unclear UI doesn't let people distinguish. It sounds like (comment 4, comment 10) people would accept us using NR certs as long as we don't default to them if there's a more appropriate cert also available. It's not that people are spec nazis, it's that the spec is ammo in a fight against a usability problem that's confounding non-expert users (that is, most people) in their regions. Maybe the usability problem can be solved or ameliorated in the PSM UI without having to decide the NR issue in NSS.
(In reply to comment #22) > It sounds like (comment 4, comment 10) people would accept us using NR certs as > long as we don't default to them if there's a more appropriate cert also > available. How do we judge algorithmically which is the "more appropriate cert"? > Maybe the usability problem can be solved or ameliorated in the PSM UI without > having to decide the NR issue in NSS. UI won't solve this one, but it could ameliorate/palliate/mitigate. I'm looking for a real fix. However fine the new RFC is, between its change in semantics and the de-facto practices (bad or not, they're out there), we have an incompleteness or an inconsistency (or both) that should be fixable with an algorithm to choose NR or not. Is there such an alg? /be
The problem is that the term non-repudiation has no meaning anymore. In actual legal cases people are convicted based on IP address logs etc. Due to this, I personally don't see any point with having separate authentication and signature certificates. It was a great idea 10 years ago though. The problem with the TLS use-case is really that the algorithm for finding out if the user has a separate signature and authentication certificate is *undocumented* making it hard to filter this the way it is supposed to work. For signatures it becomes even worse, since you may have to offer the user a choice of using a repudiatable signature or a non-repudiapable signature! Who can possibly understand that?
(In reply to comment #20) >. > I don't really know the relation between all mozilla products and components, but for example Camino - that does not expose the manual certification selection option is currently not usable if presented a smartcard via pkcs#11 that has two certificates/keys - one with ssl client usage and one with nonrepudiation usage. If PSM is used in Camino as well, this would solve it. If not - the problem comes from NSS and would require a separate fix for Camino. In the end I can only describe the 'totally right' behavior, whereas the technical details and RFCs have been quoted by others already: * If visiting a website that uses SSL client authentication * and having two certificates from the required issuer (usually on a smart card via pkcs#11) * One having SSL client authentication extendued usage and the other one for binding digital signatures with NR KU bit. * The certificate for SSL client authentication must be chosen automatically. I agree that the real problem might be somewhere else and more complicated (I even remember reading some blog post a year or so ago, telling that 'PSM has been abandoned and not really improved for long time') this is the right behavior that needs to be achieved. I linked to a wrong bug before - reverting bug 240456 will fix the proble just fine to previous state - but when allowing nonrepudiation bit the test case for the change shall still be the one i described before - taking into account extended key usage. I suggest to revert that change.
Here's my take about the NR thing, which is in a totally different area. If it would have been more appropriate to file a new bug about this, I apologize for not understanding the process. Anyway, If the NR bit is set in a certificate (regardless of which other keyUsage bits are set or how they are interpreted), then there's one thing that MUST NOT happen. A signature cannot be affixed without the user taking some action. For instance, if a user checks the "sign by default" option when configuring an email agent, certificates with the NR bit set should be excluded as possible choices. The reaason for this is that a lot of folks think that in order for the notion of non-repudiation to be viable, then a user must perform some action (like clicking an "I agree" button) to signify their intent to sign the document when they are looking at it. That is, if the default case is to sign a document when it is sent, clicking the "send" button" signifies just intent to send, not intent to sign.
My suggestion is to go with comment #19 and to revert 240456. (In reply to comment #17+19) I can't find the claim that it just works in other browsers, especially not in my own postings. But I can do that now... Internet Explorer doesn't care about KU, only EKU. If KU is missing in the certificate, all EKU is enabled by default (leaving nonRep certificates usable with SSL). The CSP that publish the certificate to CAPI has the option to set EKUs which we use to disable for example client authentcation on the NR certificate. That way everyone is happy. AFAIK there is no way to accomplish the same thing via PKCS#11, which othervise would be a viabile solution. (In reply to comment #22+23) Yes, this is a usabillity issue with RFC's (and drafts) as "weapons"... From a usabillity point of view, FF currently by default automaticly chooses the certificate to logon with, regardless if there are other valid certificates available. It would be nice if FF would ask the user what certificate to use if there are more than one available. When using the option to always let the user choose certificate to logon with, there is currently no way to distinguish the two certificates by KU or EKU. My suggestion for choosing certificate algorithm would be: 1. EKU Client Authentication 2. KU DS 3. KU NR (In reply to comment #26) In the whole, I agree with Eric, but I don't think that's FF's problem to handle, but rather the PKCS#11 provider. That's how we currently handle that problem, letting the PKCS#11 provider popup both PIN dialogue and additional info, to show if its a "legal signature" or "authentication".
After reading this it does not come as a huge surprise that the majority of e-government C2G services in the EU do NOT use TLS-client-authentication, but rather "home-grown" authentication schemes closely matching the certificates in question. I'm personally unconvinced that TLS-client-authentication is the right solution in this segment; at least not until there is a "companion" signature scheme in place as well, and that seems to be a very long journey.
PSM (using NSS) fetches ALL the user's certs (certs for which the user has the private key) and makes a list of certs that are eligible to be used for client auth, then picks one from that list. The eligibility is based on a number of factors including the name of the cert issuer, and the cert extensions. KU and EKU are both used in making that determination. If PSM wishes to exclude NR certs from that list, it may do so. This can all be solved in PSM. I agree that, in the case where the user has multiple elligible certs, some with NR and some without, giving preference to the non-NR certs would resolve this issue, for SSL client auth.
(In reply to comment #29) > I agree that, in the case where the user has multiple elligible certs, > some with NR and some without, giving preference to the non-NR certs would > resolve this issue, for SSL client auth. Then let's do that for Firefox 2 -- Kai, can you whip up a patch? /be
Search for "repudiat" in the following US Federal government standards. I believe you'll come to the same conclusion as me that the PIV cards will be affected by this bug, too. In the second document, look in particular at the nonRepudiation field values in Worksheet 5: End Entity Signature Certificate Profile and Worksheet 9: PIV Authentication Certificate Profile.
The one primary reason for prefering certs with NR over certs without in authentication cases is certain tokens will require another pin prompt for the use of NR. I agree with nelson that 1) this can be fixed in psm and 2) we should allow the use of NR while prefering certs without NR. This can be done by sorting the NR certs to the 'bottom' of the cert list. This is a bit more code than just removing, and should be reviewed (NR certs shouldn't be sorted below certs that are expired or don't match the CA list sent by the server), but it is less likely to break users which only have 1 signing cert and happen to have the NR bit turned on in it. bob
re: comment 27, John, the PKCS#11 spec doesn't say anything about modules popping up their own UI. PKCS#11 modules can and do get used in non-GUI programs (eg. servers). If you have a UI component in your PKCS#11 library, then that module may not work in those programs. In this case we have a GUI program, Mozilla/PSM, but IMO we still need to have a solution that doesn't require the PKCS#11 modules to do things outside the spec.
Created attachment 241770 [details] [diff] [review] Patch v1 We seem to agree on the salomonic compromise "allow NR-only certs, but prefer those who have only DS or both DS/NR". I'm attaching a patch. But in my opinion, we must fix this for both "select automatically" and "prompt" configuration settings. First, let's talk about those users who have set their client auth pref to "auto". The fix seems obvious, check key usage for NR-only, and only use it if no better cert can be found. In the existing code, we call NSS function CERT_FindUserCertsByUsage with a parameter "oneCertPerName" set to True. I believe I have to toggle this bool to False, so NSS will us return all the certs - a requirement for allowing PSM to make a choice. I am not sure whether this has the potential to introduce side effects. Because the comment for this parameter describes it as "return the best cert per name", I wonder if NSS is doing any selection, based on the certUsageSSLClient we are passing to it. But looking at the implementation of CERT_FindUserCertsByUsage, it appears it actually uses a very simple selection, returning the first cert that is found. So this is probably safe to do. Second, let's talk about those users who have set their client auth pref to "prompt". It has been suggested to sort the certs in the list and put the NR-only certs behind the other ones. I think this is hard to do right in a small amount of code. A helpful function used internally by NSS is not exported (CERT_SortCBValidity) and therefore not available to be used by PSM. As we are looking for a small patch for last minute inclusion, I propose we do not attempt to re-sort this already sorted list. My proposal is to show more information in the UI and make it the user's responsibility to select a good one. After all, the user has explicitly configured the wish to manually select. It was said in this bug, the UI currently does not allow the user to distinguish between differences at the key usage level. I created test certificates and I can confirm that. My minimal-change-proposal is: Let's add " [NR]" to the "short cert name [serial]" currently displayed in the drop down box. I hope this does not have a side effect. Looking at all involved code, it appears, the string is only displayed for display, but never as a key. So the change seems safe. The drawback of that minimal change, the [NR] can not be localized in FF2. My complete-UI-info proposal is: In the detailed description text box, let's add a line below the "Purposes" and display all key usages for this cert. Luckily we seem to have all strings readily available in our bundle. In the attached patch, I have added code for both UI proposals. While the minimal approach is simpler, I think the key usages string is better. For testing, I created 3 certs: - a) no key usage extension - b) key usage non-repudiation only, cert type both SSL client and S/Mime - c) key usage digital signature only, cert type both SSL client and S/Mime I got displayed all 3 certs, while only cert b) had the [NR] string appended in the dropdown box. Only for b) and c) I had an additional information line in the text box. Using cert b), I was not able to connect to my test server (as expected). Using certs a) and c) worked fine to connect to my test server.
(In reply to comment #34) > But in my opinion, we must fix this for both "select automatically" and > "prompt" configuration settings. > > My proposal is to show more information in the UI and make it the user's > responsibility to select a good one. After all, the user has explicitly > configured the wish to manually select. I filed a new bug that I think is relevant to certificate selection. I'm not sure I did it right. But anyway, it's bug #356060
Created attachment 241774 [details] [diff] [review] Patch v2 Per discussion with Bob and Brendan, we prefer the [NR] change for now.
Created attachment 241776 [details] [diff] [review] Patch v3 Addressed review comments from a chat.
Comment on attachment 241776 [details] [diff] [review] Patch v3 r+ this one looks right. Note that NR is set on all non-repudiation certs, not just ones with the signing bit set to zero. (this is correct behavior).
Comment on attachment 241776 [details] [diff] [review] Patch v3 >+ if (hasExplicitKeyUsageNonRepudiation(node->cert)) { >+ // Not a prefered cert s/prefered/preferred/, please. :)
fixed on trunk
!)
Sorry, so many comments and being in 12h different timezone... No, this patch does not fix it. Showing [NR] in the cert selection popup is nice, BUT the test case, as I described before, is still wrong: 1) Have two certificates, one with EKU SSL authentication and KU DS, and one with KU NR and 2) Automatic certificate selection is turned ON 2) I go to a SSL website requesting a certificate from the CA who had issued the two previous certificates The expected result is: 3) If automatic certificate selection is turned on, the cert from auth.sig.txt certificate is used. 3) If automatic certificate selection is turned off, the cert from auth.sig.txt certificate (as the one having TLS Client authentication usage bits) is suggested first. Current result is: 3) NR cert is used by default or selected in the popup. This certificate does NOT have a EKU of TSL client authentication. There exists one that has (both certificates and keys come from pkcs#11 of opensc-project.org) and that is not used. I tried the build from:) Removing the patch from bug 240456 makes it back to normal. I suggest to do that and then decide what is the right way of handing the NR bit so that it is done semi-correctly. This still not usable.
(In reply to comment #42) > No, this patch does not fix it. I notice your certificates are EXPIRED: Validity Not Before: Sep 29 21:00:00 2003 GMT Not After : Oct 3 21:00:00 2006 GMT ^^^^^^ 1 week ago > 1) Have two certificates, one with EKU SSL authentication and KU DS, and one > with KU NR > and > both expired > Current result is: > 3) NR cert is used by default Are you sure? Is it possible that Firefox does not use any cert at all? As far as I can tell, our "automatic selection" will only use valid certs - it will not use expired certs. >? > I tried the build from: > correct >) Before we continue this discussion, can you please retry with not-yet-expired certs, certs that are still valid? Thanks
Call for testers: Everyone who owns valid certificates and previously ran into this issue: Can you please test whether the nightly test build from works for you?
The certificates on that webpage are expired, but the ones on my ca(In reply to comment #43) > (In reply to comment #42) > > No, this patch does not fix it. > > I notice your certificates are EXPIRED: This webpage and the files are from an earlier post on the same topic. In real life the certs I use are not expired. It is just to show the (E)KU bits in certs. > > 1) Have two certificates, one with EKU SSL authentication and KU DS, and one > > with KU NR > > and > > > > both expired They are there just for reference - but i updated the files. except sig.cert is sign.cert now. > > Current result is: > > 3) NR cert is used by default > > Are you sure? > Is it possible that Firefox does not use any cert at all? > As far as I can tell, our "automatic selection" will only use valid certs - it > will not use expired certs. Yes, I'm sure. Forget about the validity period. > >? Everything works as expected if I select the authentication certificate manually. > Before we continue this discussion, can you please retry with not-yet-expired > certs, certs that are still valid? I never test with invalid certificates as the site I'm testing against does an extra check against OCSP. Just the references in the web are old and wrong (certificate profiles are still exactly the same)
I still suggest to remove the 'if asked KU is DS, allow NR to act as DS' change in certdb.c introduced with bug 240456 and then think how to support NR only KU so that it would make most sense. Future solution would be making PSM use TSL client authentication EKU as a filter or something similar.
> Touching nsNSSIOLayer.cpp this late in the game makes me very nervous, and > I'd like to get a clear statement of the various risks in taking and not-taking > this patch at this late point in the game. "taking" assessment: The change is limited to SSL connections where the server requires client authentication. If automatic cert selection is configured (the default), a different cert may be selected by Firefox. If manual cert selection is configured (non-default), the change is limited to a cryptic suffix [NR] displayed, which assists power users in making the right selection. I believe the code does not have a potential to introduce crashes.
Reopening. Martin, thanks a lot for your comments and examples. I created test certificates that match your example, and I am able to confirm: The automatic selection does not yet work. I made a mistake in my patch. We are still aborting the search for a good cert after we find the first user cert. (The break statement at the wrong position). Sorry. With Patch v4 applied, using the example certs, the automatic selection now works correctly for me. (In reply to comment #45) > Everything works as expected if I select the authentication certificate > manually. This is good to know.
Created attachment 241833 [details] [diff] [review] incremental patch after v3
Created attachment 241834 [details] [diff] [review] Patch v4 This is v3 + the incremental patch.
(In reply to comment #48) > > With Patch v4 applied, using the example certs, the automatic selection now > works correctly for me. Good! This means that it becomes usable again! Waiting for a new mac nightly to test it...! I leave you in a nice discussion about the the most right solution to the NR bit problem, but IMHO it starts from 'If we have a EKU TSL client authentication'cert to present - we do it'. After that starts the problem of the NR bits... Thanks! What are the plans for FF 2.0 line regarding this issue ? 2.0 ? 2.0.1 ? 2.0.x ?
?
Not reviewed, not a regression, we'll try to get this in 1.8.1.1/Fx 2.0.0.1
(In reply to comment #52) > ? While I didn't want to make a decision whether this is a "must fix" for FF 2, please see my comment 47 where I try to answer your question about the risk. Using the test certs I just verified - FF 1.5 is broken already. So if this is a regression, and if it worked in FF 1.0, it seems we have been living with this regression since 1.5
(In reply to comment #44) Kai, I have tested the nightly build. When certificate selection is set to manual I can see the [NR] suffix in the list of valid certificates. This is nice for power users that know everything about X.509 but is not very useful for end users. When certificate selection is set to automatic Firefox should select a certificate wiht KU digitalSignature. Please fix the automatic certificate selection as soon as possible. As it is now, we have to advise our users to use a different browser.
What is the status of the last patch? I'd give a nightly a try but it seems that the last patch has not been reviewed nor applied? 2.0.x is not far :)
Would be great to change the cert-picking logic if we can for 1.8.1.1, not sure we could take the UI change.
Comment on attachment 241833 [details] [diff] [review] incremental patch after v3 r=kengert on my own obvious single-line correctness fix.
Comment on attachment 241834 [details] [diff] [review] Patch v4 r=kengert on this v4, which is patch v3 (r=rrelyea) plus the obvious fix listed above.
Comment on attachment 241833 [details] [diff] [review] incremental patch after v3 I checked in this incremental fix to the trunk.
Marking fixed on trunk, you might want to test tomorrow's nightly trunk build.
Comment on attachment 241834 [details] [diff] [review] Patch v4 Requesting 1.8.1.1 approval of patch v4. Note that v4 simply combines v3+fix. I propose to take the simple UI change, which does not cause any harm, and does not affect localization.
Comment on attachment 241834 [details] [diff] [review] Patch v4 approved for 1.8 branch, a=dveditz for drivers. Is this something we would also want for Firefox 1.5.0.x? Probably not, it's not a security fix and a working version will be available in FF2.0
checked in to 1.8 branch (In reply to comment #63) > Is this something we would also want for Firefox 1.5.0.x? Probably not, it's > not a security fix and a working version will be available in FF2.0 I tend to agree.
(In reply to comment #62) > (From update of attachment 241834 [details] [diff] [review] [edit]) > Requesting 1.8.1.1 approval of patch v4. > > Note that v4 simply combines v3+fix. > > I propose to take the simple UI change, which does not cause any harm, and does > not affect localization. > Latest nightly build (3.0a1) Does not fix the problem. Still the NR only certificate is selected automatically when another more suitable certificate with EKU SSL-client is available. I still suggest to drop the certdb.c change in the old OCSP & NR related changeset and then introduce NR support again, after giving it some more though. Or fix it in PSM. Is somebody would point me to some PSM tutorials I would look at it myself (and also make FF respect pinpads...)
(In reply to comment #65) > Latest nightly build (3.0a1) Does not fix the problem. Still the NR only > certificate is selected automatically when another more suitable certificate > with EKU SSL-client is available. Martin, sorry, it works for me now, with the test cases I had produced. I just repeated my test and it still works as expected. I have a test site, requiring client auth, accepting certs from a test CA, I own two certs from that test CA, one having Certificate-Usage NR only, another one having Certificate-Usage Signing+KeyEncipherment+DataEncipherment. When I have "manual cert selection" configured, I get prompted to select from those two, selecting the NR results in a failure (as expected), selecting the other one works (as expected). When I restart the browser, and switch to "select cert automatically" it will give me a successful connection, which demonstrates the right cert got selected. Can you please make a test case available to me? A set of test certs and a server to connect to?
(In reply to comment #66) (In reply to comment #66) The latest build looks good! I have tested the build with a smartcard that contains three certificates with the following key usage bits: 1: nonRepudiation 2: digitalSignature 3: keyEncipherment, dataEncipherment, keyAgreement With automatic certificate selection turned on, Firefox now selects the certificate with digitalSignature.
*** Bug 329897 has been marked as a duplicate of this bug. ***
(In reply to comment #67) I have tried it on both 2.0.0.4 and latest nightly Minefield build and it automatically choses the right cert now. I am using the service that the initial reporter of the bug had found the bug through so there is definitely a change for the better now.
Latest minefield (downloaded today) really does the right thing. 2.0.0.4 not yet (should it? It sure does display the [NR]...)
(In reply to comment #70) > Latest minefield (downloaded today) really does the right thing. 2.0.0.4 not > yet (should it? It sure does display the [NR]...) Martin, we assumed the bug is fixed. Can you please explain more? What is the incorrect behavior that you get in 2.0.0.4?
Regardless the fix, FF TLS sucks since it does not honor AIA CA-issuer which means that a FIPS201 user must install CA certificates in order to get the issuer selection working. Yes, this is outside of TLS... Remedy: Which has a signature counterpart in:
Anders, please refrain from using bugzilla to promote your WASP software. Thanks.
Dear Nelson, I just skimmed a 400 page document by the Swedish government. In the document they had among many things asked 22 departments which area in IT which needed more standardization. The thing that got (by far) most scores was eID. Since eID is mainly used in conjunction with browsers, there apparently is a disconnect here between what the browser vendors offer and what at least the Swedish government wants. I believe that is another indication that FF's crypto.signText is not perceived as very useful. signText does not have any standards status either. Neither MSFT or Opera supports signText. ========================================================================== The question that begs for an answer is how Mozilla anticipates that a useful signature solution will eventually become a part of FF? ========================================================================== BTW, WASP/WebAuth is a standards proposal, not a piece of software. Just to make it even more complex: There are wide incompatibilities in the on-line provisioning of PKI as well here thinking of Xenroll, KeyGen and generateCRMFrequest (). Going back to the actual bug, the true culprit is that TLS wasn't designed for the variant eID world which is the reason a lot of eID-using web-applications do not use TLS-client-certificate authentication. Microsoft's CardSpace is an indication where we are [probably] going; away from protocol-level authentication. Anders
Note this patch just introduced a prbool violation. /security/manager/ssl/src/nsNSSIOLayer.cpp: 2006:- return (keyUsage & KU_NON_REPUDIATION); + return (0 != (keyUsage & KU_NON_REPUDIATION));
The behaviour that the authentication certificate should be choosen before the non-repudiation has been broken in FF 3.0. I'm trying to re-open this bug report.
John, please let's keep this bug closed, as it does not refer to firefox 3. Can you please file a new bug against ff3 and explain what you do and what fails?
Just for the record: FF 8.0b1 seems to have finally got this right, non-repudiation only certificates are not even shown as suitable in the certificate selector!
Yes, that's the result of fixing NSS bug 217721.
Now it would be cool if bug 511652 could also get a verdict and/or solution. That's the last requirement to drop the "onepin" hack from OpenSC which exists solely for NSS.. :) | https://bugzilla.mozilla.org/show_bug.cgi?id=328346 | CC-MAIN-2017-26 | refinedweb | 6,897 | 62.88 |
Hi Dennis,
We often use a bundle db PM in a cluster and I've never seen the
problem you describe. It woul help if you can provide more detailed
logging, and which version of Jackrabbit are you using?
Best regards,
Martijn
On Wed, Dec 16, 2009 at 12:18 AM, Dennis van der Laan
<d.g.van.der.laan@rug.nl> wrote:
> Dennis van der Laan wrote:
>> Hi,
>>
>> I have two identical machines (A and B) running Jackrabbit 1.6.0 on
>> Tomcat 6.0. I made an empty folder on each machine, containing only a
>> repository.xml file, again both identical (using System properties to
>> set the cluster ID). The repository configuration uses a bundle PM
>> (Oracle 10g database) and a local filesystem for all components.
>>
>> When I start A, the repository tables are created in the database and
>> all works well. After the repository is initialized, I add some custom
>> namespaces and nodetypes, and create a basic folder hierarchy.
>> Then, when I start B, I get)
>>
>> When I stop both A and B, and starting them again, A can startup again
>> but B still gives the exception.
>>
>> I removed all tables from the database and re-created the repository
>> folders on both machines and inverted the startup: first I started B and
>> then I started A. Now B starts up fine, but A gives the exception.
>>
>> In the LOCAL_REVISIONS table I can see both cluster instances add their
>> revision (revision 12 for the started repository and 0 for the failed
>> repository).
>>
>> What am I doing wrong here? I found an issue involving LockFactory
>> exceptions, but they all had to do with starting and stopping multiple
>> repositories in the same VM or concurrently on the same machine.
>>
> I changed the repository configuration from using a bundle database PM
> to a simple database PM (from
> org.apache.jackrabbit.core.persistence.bundle.OraclePersistenceManager
> to org.apache.jackrabbit.core.persistence.db.OraclePersistenceManager).
> Now it works! But a bundle PM should have better performance. Is this a
> bug? Is anybody else using a bundle database PM in a cluster configuration?
>
> Thanks,
> Dennis
>
> --
> Dennis van der Laan
>
> | http://mail-archives.apache.org/mod_mbox/jackrabbit-users/200912.mbox/%3Cdc0c11da0912160018y754a7eefw2d22d040520fc6d0@mail.gmail.com%3E | CC-MAIN-2017-34 | refinedweb | 354 | 56.96 |
On Wed, Dec 17, 2008 at 1:52 PM, Rominsky <john.rominsky at gmail.com> wrote: > On Dec 17, 10:59 am, Christian Heimes <li... at cheimes.de> wrote: > > Rominsky schrieb: > > > > > I am trying to use dir to generate a list of methods, variables, etc. > > > I would like to be able to go through the list and seperate the > > > objects by type using the type() command, but the dir command returns > > > a list of strings. When I ask for the type of an element, the answer > > > is always string. How do I point at the variables themselves. A > > > quick example is: > > > > > a = 5 > > > b = 2.0 > > > > > > > lst = dir() > > > > > for el in lst: > > > print type(el) > > > > for name, obj in vars().iteritems(): > > print name, obj > > > > Christian > > I do have some understanding of the pythonic methodology of > programming, though by far I still don't consider myself an expert. > The problem at hand is that I am coming from a matlab world and trying > to drag my coworkers with me. I have gotten a lot of them excited > about using python for this work, but the biggest gripe everytime is > they want their matlab ide. I am trying to experiment with making > similar pieces of the ide, in particular I am working on the workspace > window which lists all the current variables in the namespace, along > with their type, size, value, etc.... I am trying to create a python > equivalent. I can get dir to list all the variables names in a list > of strings, but I am trying to get more info them. hence the desire Are you familiar with the ipython console? It is quite powerful; in particular, the %who and %whos 'magic functions' will do much of what you'd like: [501]$ ipython Python 2.5.2 (r252:60911, Jul 31 2008, 17:31:22) Type "copyright", "credits" or "license" for more information. IPython 0.8.1 -- An enhanced Interactive Python. ? -> Introduction to IPython's features. %magic -> Information about IPython's 'magic' % functions. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [1]: os module <module 'os' from '/usr/lib/python2.5/os.pyc'> In [7]: import numpy as np In [8]: aa = np.zeros(100) In [9]: whos Variable Type Data/Info ------------------------------- a str foo aa ndarray 100: 100 elems, type `float64`, 800 bytes b str bar c float 5.234 d module <module 'os' from '/usr/lib/python2.5/os.pyc'> np module <module 'numpy' from '/us<...>ages/numpy/__init__.pyc'> os module <module 'os' from '/usr/lib/python2.5/os.pyc'> And I trust you've heard of numpy, scipy and matplotlib? Cheers, Kurt -------------- next part -------------- An HTML attachment was scrubbed... URL: <> | https://mail.python.org/pipermail/python-list/2008-December/475139.html | CC-MAIN-2019-30 | refinedweb | 453 | 83.86 |
Unanswered: Upgrade sencha touch 2.0 to 2.1 issues
Unanswered: Upgrade sencha touch 2.0 to 2.1 issues
I]Uncaught Error: [Ext.Loader] Failed loading 'touch/src/dataview/Override.js', please verify that the file exists [/COLOR]
- [COLOR=red !important][/COLOR]
- [COLOR=red !important][/COLOR]
[/COLOR]
- Join Date
- Mar 2007
- Location
- Gainesville, FL
- 37,642
- Vote Rating
- 898
- Answers
- 3573
When you upgraded, you probably didn't copy the Override.js file over. If this is the case then it's a good reason why you shouldn't touch (edit/add/delete) anything in the library directory (touch). Any overrides should go into your app directory and be namespaced for your app. If you want to have shared overrides then you can have an override directory outside the app directory. Just don't touch the touch. | http://www.sencha.com/forum/showthread.php?258523-Upgrade-sencha-touch-2.0-to-2.1-issues&p=947259 | CC-MAIN-2014-52 | refinedweb | 138 | 62.44 |
I'm on a cpanel environment and I get a daily notification to tell me my hostname could not be resolved to ip address. Looking at my /etc/hosts file I then find this:
127.0.0.1 localhost.localdomain localhost
[my server ip] server7 server7
My understanding is that this file should be more like
[my server ip] subdomain.primarydomain.com subdomain
A few things come up for me:
1) Do I need to add all the subdomains in here that I'm using, ie ftp, mail, www ?
2) Is this setup actually erroneous - and if so, what is it in my WHM/Cpanel setup which has created this erroneous /etc/hosts file so that I can fix it?
My assumption is that you currently using a purchased domain name and trying to associate your host with the domain name.
Check your /etc/resolv.conf file. It handles how your computer does DNS lookups.
If your computer is searching a namespace indicated by the "search domain.com" line in /etc/resolv.conf, then your computer will actually do a DNS lookup for "server7.domain.com".
To have those names successfully resolve, your hostname must be added on the DNS server that your domain is registered on.
For example, if you have purchased a domain from godaddy.com, then you would go to your godaddy account and add those host records there. Then you would edit the /etc/resolv.conf file on your host, add your godaddy nameservers to the "nameservers" line, and change the "search" line to yourdomain.com.
Then your host should be able to do a successful lookup of "server7.yourdomain.com"
I don't think so that you have to list all subdomains to your IP. Otherwise, i can cause few other errors, because of this, you are telling the system, that the IP of the subdomain hostnames are on it's IP, and the system is not telling the DNS to matching IP address. The Error, you've telling us, should be a problem with not resolving hostname on IP.
Which hostname, which is listed in first information box under Current Hostname - This Hostname should be in the /etc/hosts assinged to any IP or must have a valid DNS record.
By posting your answer, you agree to the privacy policy and terms of service.
tagged
asked
1 year ago
viewed
316 times
active | http://serverfault.com/questions/382406/is-this-an-erroneous-looking-etc-hosts-file?answertab=votes | CC-MAIN-2013-48 | refinedweb | 399 | 72.05 |
QObject::connect fails ... Don't know why (solved)
Hi guys,
I'm new at developing with Qt, but I promised a friend of mine to programm a Raspberry Pi Software to controll a hookah desk. Of course we want a grafical UI but we need C++ as programminung language due to some interfaces. So I thought I wanna try QML in combination with C++.
Me - a total Qt noob - spend the last few hours figuring out why I always get this error messenge:
QObject::connect: No such slot QObject::qmlSignal(QString) in ..\Shishatisch\main.cpp:18
I searched for a sollution for this problem and it turned out that some other guys have that problem, too. The solution always was to name all functions the same way. But mine are since the beginning. So that didn't help me. 1.000.000 Google searches later I gave up and decided to ask some experts.
Due to the fact that this isn't exactly a secret project I will now post all of my source code (beside the qml code cause it would be too long)
connect.h:
#ifndef CONNECT_H #define CONNECT_H #include <qstring.h> #include <QObject> class Connect : public QObject { public: explicit Connect(QObject *parent = 0); signals: public slots: void qmlSignal(QString msg); }; #endif // CONNECT_H
connect.cpp
#include "connect.h" #include <QDebug> Connect::Connect(QObject *parent) : QObject(parent) { } void Connect::qmlSignal(QString msg) { qDebug() << msg; }
main.cpp:
#include <QGuiApplication> #include <QQmlApplicationEngine> #include <connect.h> #include <QQmlContext> #include <QQuickItem> #include <QtCore> #include <QDebug> int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); Connect* data=new Connect(); QObject* item=engine.rootObjects().value(0); QObject::connect(item,SIGNAL(qmlSignal(QString)),data,SLOT(qmlSignal(QString))); return app.exec(); }
- code_fodder
@onlydp You have some little issues here regarding the difference between a slot and a signal I think.
I signal is not really a function - you declare it but do not define its implementation. You will "emit" the signal at some point and pass parameters with it. The slot is where a signal can be received and you declare it in the header and also declare an implementation. So in the header file its:
signals: void mySignalToSendData(QString msg); publis slots: void mySlotToReceiveData(QString msg);
and in the cpp file:
void myClass::mySlotToReceiveData(QString msg) { .. do stuff.. }
Then you connect a signal to a slot (maybe in main):
myClass myclass; connect(&myclass, SIGNAL(mySignalToSendData(QString msg)), &myclass, SLOT(mySlotToReceiveData(QString msg))
In your code you do not want to make your slots and signals have the same name - it will be very confusing I think. Signals are like "send message" functions and slots are like "message receivers"
- alex_malyu
class Connect : public QObject
{
public:
explicit Connect(QObject *parent = 0);
signals:
public slots:
I would suggest not to name slot FOO "signalFoo" so people are not confused.
But you are missing Q_OBJECT macro:
class Connect : public QObject
{
Q_OBJECT
public:
......
Thx guys,
the missing Macro was my fault. I added it and magic it works. And I renamed the slot into qmlslot so there shouldn't be problems by that, too.
Big thank you!
- Joel Bodenmann
@onlydp Can you please mark this question as solved (by adding [Solved] in front of your post title when editing the first post) so others don't drop by in order to try to help? | https://forum.qt.io/topic/58223/qobject-connect-fails-don-t-know-why-solved | CC-MAIN-2018-34 | refinedweb | 563 | 55.03 |
Basic Concepts of Monero
Basic Concepts of Monero
We give a basic, but low-level, introduction into the world of cryptocurrencies by taking a look at Monero. We'll see how it works, a little of the code that makes it go, and more.
Join the DZone community and get the full member experience.Join For Free
Several hundred cryptocurrencies are out there today. Many of them exist for a few months without any unique idea. But there are cryptocurrencies which promise great prospects. One of them is Monero (XMR). Monero (from Esperanto for "coin") is an open-source cryptocurrency, and is intended for anonymous cash settlements. Monero is based on the CryptoNote protocol, which allows you to make transactions with a very high degree of anonymity via obfuscation of transactions (more detail how on this happens will be given below) and it works exclusively on Proof-of-Work.
At the moment of writing this article, capitalization of Monero is $1,376,648,631 USD, which is #9 among all cryptocurrencies. One of the main reasons for the growth of Monero was the addition of Monero to the trading platforms of Darknet Oasis and AlfaBay. Entering on the huge market, albeit with a negative reputation, produced a significant increase in the price of Monero. A little disclaimer - this article is not about "Is anonymity good or bad?" or the philosophy of "how DApps change the world." It's about "Basic concepts of Monero." So let's start.
Ring Signatures
Ring signatures are used to hide the real inputs of transactions in such a way that it is impossible to tell what the story behind each output of this transaction is in the chain of blocks. A ring signature is an electronic signature that allows one of the group members to sign a message on behalf of the entire group, and it will not be known for sure which of the group members signed it.
Picture 1 - Ring signature schema
The curious reader can consider the following ring signature code in Python from this wiki:
import os, hashlib, random, Crypto.PublicKey.RSA class ring: def __init__(self, k, L=1024): self.k = k self.l = L self.n = len(k) self.q = 1 << (L - 1) def sign(self, m, z): self.permut(m) s = [None] * self.n u = random.randint(0, self.q) c = v = self.E(u) for i in (range(z+1, self.n) + range(z)): s[i] = random.randint(0, self.q) e = self.g(s[i], self.k[i].e, self.k[i].n) v = self.E(v^e) if (i+1) % self.n == 0: c = v s[z] = self.g(v^u, self.k[z].d, self.k[z].n) return [c] + s def verify(self, m, X): self.permut(m) def _f(i): return self.g(X[i+1], self.k[i].e, self.k[i].n) y = map(_f, range(len(X)-1)) def _g(x, i): return self.E(x^y[i]) r = reduce(_g, range(self.n), X[0]) return r == X[0] def permut(self, m): self.p = int(hashlib.sha1('%s' % m).hexdigest(),16) def E(self, x): msg = '%s%s' % (x, self.p) return int(hashlib.sha1(msg).hexdigest(), 16) def g(self, x, e, n): q, r = divmod(x, n) if ((q + 1) * n) <= ((1 << self.l) - 1): rslt = q * n + pow(r, e, n) else: rslt = x return rslt
Stealth Addresses
Stealth addresses are the method by which the sender can receive the public address of the recipient and convert it into a one-time address in such a way that it's publicly impossible to establish a connection with any other address. The originator of the initial public address and only the recipient can receive a secret key associated with a one-time address. Stealth addresses rely on the Elliptic curve Diffie-Hellman algorithm to let users accept payments on addresses they never generated. You have one public address that you can transfer to anyone, not allowing observers to know anything about the transaction history or the balance of this address. The Monero address system uses two private keys: a view key and a spend key (key for waste, you sign the transaction with it). The view key is used to search for incoming payments in the chain of blocks.
RingCT
RingCT allows users to hide transaction amounts. RingCT introduces an improved version of ring signatures called A Multi-layered Linkable Spontaneous Anonymous Group signature. RingCT was activated on the Monero network on January 9, 2016. Initially, RingCT was optional, but after the planned update, the RingCT technology in Monero is mandatory, without any way to circumvent it.
Kovri — I2P
The Kovri project aims to implement an I2P router, which will eventually allow Monero users to hide their IP addresses. Kovri is currently in heavy, active development and not yet integrated with Monero. When Kovri is integrated into your Monero node, your transactions will be more secure than ever before. Kovri will protect you and Monero from node partitioning attacks and metadata leakage.
Fungibility
Monero is fungible, meaning one Monero will always be equal to another. This means you won't have to worry about Monero blacklisted by exchanges or vendors.
Monero is a revolutionary technology in the world of distributed applications, it uses reliable time-tested cryptography and, because of its reliability, will be in demand.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/basic-concepts-of-monero?fromrel=true | CC-MAIN-2019-22 | refinedweb | 921 | 57.67 |
A Review of Transact-SQL Built-In Stored Procedures
Server-Related Stored Procedures
Introduction
To assist you with managing Microsoft SQL Server
databases, Transact-SQL provides many built-in stored procedures.
Getting Information About the Server
To let you get many statistics about your Microsoft
SQL Server installation, Transact-SQL provides the sp_monitor
stored procedure, which produces many values. Here is an example of
executing it:
It is important to know that the values produced by
the sp_monitor stored procedure depend on many factors
such as the capacities of the machine, the type of connection, and what is
going on at the time this procedure executes.
Getting Information About a User
Imagine that at one time you want to know who is
currently connected to your Microsoft SQL Server. Transact-SQL provides
the sp_who stored procedure. This procedure lets you know
who is (actually who are) currently using the computer(s) in your network,
what computers they are using (this procedure gives you the name of the
computer a person is using), what database the person is using (what
database the user is connected to), etc.
The syntax of the sp_who stored
procedure is:
sp_who [ [ @loginame = ] 'login' | session ID | 'ACTIVE' ]
This stored procedure takes one argument, which is
optional, which means you can execute this procedure without any argument.
When it has executed, sp_who produces a window made of
nine columns. One column (the fourth) is labeled loginame and another
column (the fifth), labeled hostname, shows the name of the computer the
user is using.
Observe the following example that executes the
sp_who stored procedure:
Notice the values in the loginname. This shows the
name of the domain followed by the user name of a person who is currently
connected. The hostname shows the name of the actual computer the person
is using.
As mentioned previously, the sp_who
stored procedure produces a window with nine columns. There are some
issues you should be familiar with (even slightly) in order to understand
some of the results.
A process can be considered an application (like
Notepad) or part of an application (like one part of an application that
is ripping music from a CD while another part of the same application is
playing music from the same CD). Thread programming, also called
threading, is the operating system's way of allocating the computer
resources (memory for example) to each process (or each application) that
needs it.
One of the problems the operating system faces is that
there may not be enough resources for all processes in the computer. One
of the consequences is that sometimes some processes must wait; that is,
sometimes a certain process A must wait for a certain resource (like a DVD
player), especially if that particular resource is currently being used by
another process B (maybe process B is currently playing a movie on the DVD
player but process A needs the DVD player to install a driver). In some
cases, process A must "sit" and wait for process B to free the needed
resource. In some other cases, process A may want to "steel" or grab the
resource even if process B has not finished using it. To prevent a process
A from accessing a resource that is not available, process B can (or must)
lock the resource.
The columns produced by the sp_who
stored procedure are:
As mentioned already, sp_who takes
one argument. The value of the argument can be:
Database-Related Stored Procedures
Renaming an Object
To give you the ability to rename an object in
a database, Transact-SQL provides a stored procedure named
sp_columns. Its syntax is:
sp_rename [ @objname = ] 'object_name' , [ @newname = ] 'new_name'
[ , [ @objtype = ] 'object_type' ]
This procedure can be used to change the name
of a database, a table, a view, a column, an index, a Transact-SQL
type-defined data type, or a CLR type-defined data type.
This stored procedure takes two required and
one optional argument. The first argument specifies the current
name of the object you want to rename. The second argument
specifies the new name that will be given to the object. The third
argument is not required but it is (highly) recommended. Since
this argument is optional, you can omit it. Here is an example:
USE Exercise1;
GO
sp_rename N'Houses', N'Properties';
GO
If you omit this argument, the database engine
would look for an object that holds the first argument's name. For
example, if it finds a table or a view, it would change its name
to that of the second argument. Therefore, to rename a table or a
view, pass the first argument as the current name of the table and
omit the third argument. To rename a database, pass the third
argument as DATABASE. Here is an example:
USE master;
GO
sp_rename N'Exercise', N'Example', N'DATABASE';
GO
To rename a column, pass the first argument as
TableName.ColumnName, the second argument as the
new name of the column, and the third argument as COLUMN.
Getting Information About a Database
To let you get as much information as possible about a
database, Transact-SQL provides the sp_helpdb stored
procedure. Its syntax is:
sp_helpdb [ [ @dbname= ] 'name' ]
This procedure takes one argument, which is optional.
If you call it without an argument, the procedure would show you, among
other things, the names of the databases, their sizes, and the dates they
were created. Here is an example:
As an alternative, to get information about a specific
database, pass it as argument. Here is an example:
Getting Information About the File Groups of a
Database
Besides sp_helpdb, Transact-SQL
provides the sp_helpfile stored procedure that produces
information about a database. The syntax of the sp_helpfile
stored procedure is:
sp_helpfile [ [ @filename= ] 'name' ]
Like sp_helpdb, sp_helpfile
takes one optional argument. We saw that if you call the sp_helpdb
stored procedure without an argument, the database engine would consider
all database of the server. By contrast, if you call sp_helpfile
without an argument, the database engine would find what the current
database is. If you had not previously selected a database, then the
master database is the current one. Here is an example:
Otherwise, if you want to get information about a
particular database, you can first select it:
As an alternative, you can pass the name of the
database or the name of one of its files as argument. Here is an example:
Getting Information About the File Group of a
Database
To let you get some information about the file groups
of a database, Transact-SQL provides the sp_helpfilegroup
stored procedure. Its syntax is:
sp_helpfilegroup [ [ @filegroupname = ] 'name' ]
This stored procedure takes an optional argument. Here
is an example of calling it without an argument:
If you pass the argument as 'primary',
you would get the location of the main file group. Here is an example:
Tables and View-Related Stored Procedures
Getting Information About an Object
To get information about an object of a database, you
can execute the sp_help stored procedure. Its syntax is:
sp_help [ [ @objname = ] 'name' ]
This stored procedure takes one optional argument. If
you call it without passing an argument, it produces information about the
database that is currently selected. This means that you should first
specify a database before executing this procedure. Here is an example:
USE Exercise;
GO
sp_help;
GO
To get information about a specific object, pass its
name as argument. Here is an example:
USE Exercise1;
GO
sp_help N'Employees';
GO
Getting the Size of an Object
The sp_spaceused stored procedure
allows you to know how much memory a database or one of its objects is
occupying. The syntax of this procedure is:
sp_spaceused [[ @objname= ] 'objname' ]
[,[ @updateusage= ] 'updateusage' ]
This procedure takes two optional arguments. If you
execute it without an argument, you would get the different amounts of
memory space the current database is using. To specify the database whose
size you want to check, you should first select it. Here is an example:
To know the space that a particular object is using,
pass it as argument. Here is an example:
Getting Information About the Columns of a Table
To get details about the columns of a table, you can
execute the sp_columns stored procedure. Its syntax is:
sp_columns [ @table_name = ] object [ , [ @table_owner = ] owner ]
[ , [ @table_qualifier = ] qualifier ]
[ , [ @column_name = ] column ]
[ , [ @ODBCVer = ] ODBCVer ]
This procedure can take many arguments but one is
required. The required argument is the name of the table whose columns you
want to investigate. Here is an example:
USE Exercise1;
GO
sp_columns N'Employees';
GO
Refreshing a View
The sp_refreshview stored procedure
allows you to update the metadata of a view. The syntax of this procedure
is:
sp_refreshview [ @viewname= ] 'viewname'
Here is an example that executes this procedure:
USE Exercise;
GO
sp_refreshview N'People';
GO
Getting Information About a Trigger
To let you get information about a trigger, Transact-SQL
provides a stored procedure named sp_helptrigger. Its
syntax is:
sp_helptrigger [ @tabname= ] 'table'
[ , [ @triggertype = ] 'type' ]
Deleting an Alias Data Type
Imagine you had created a custom data type for your
database:
USE Exercise;
GO
CREATE TYPE NaturalNumber FROM int;
GO
If you don't need such a data type any more, to assist
you with removing it, Transact-SQL provides the sp_droptype.
Its syntax is:
sp_droptype [ @typename= ] 'type'
This procedure takes one argument as the name of the
custom data type you want to delete. Here is an example of executing it:
sp_droptype NaturalNumber;
GO
Showing the List of Constraints of an Object
Imagine you had created a database and added some
constraints to it. Here are examples:
USE master;
GO
CREATE DATABASE Exercise1;
GO
USE Exercise1;
GO
CREATE TABLE Genders
(
GenderID int identity(1, 1) not null,
Gender nvarchar(20) not null,
CONSTRAINT PK_Genders PRIMARY KEY(GenderID)
);
GO
CREATE TABLE Employees
(
PersonID int identity(1, 1) not null,
FirstName nvarchar(22) null,
LastName nvarchar(22) not null,
GenderID int
CONSTRAINT FK_Genders FOREIGN KEY REFERENCES Genders(GenderID),
HourlySalary money,
CONSTRAINT PK_Persons PRIMARY KEY(PersonID),
CONSTRAINT CK_HourlySalary CHECK (HourlySalary > 12.20),
CONSTRAINT CK_Gender CHECK (GenderID BETWEEN 0 AND 4)
);
GO
To let you get information about the constraints in a
database, Transact-SQL provides the sp_helpconstraint
stored procedure. Its syntax is:
sp_helpconstraint [ @objname= ] 'table'
[ , [ @nomsg= ] 'no_message' ]
This procedure takes an argument as the name of the
object whose constraints you want to find out. The argument can be the name
of a table. Here is an example:
As you can see, this procedure produces all constraint
reference, both the primary key and foreign key(s). If a table contains many
constraints, the database creates a summary. Here is an example:
Automatically Executing a Stored Procedure
A stored procedure usually shows its result only when it
executes. Sometimes, you wish to automatically execute it at the time of
your choosing. This is possible using the sp_procoption
built-in stored procedure. Its syntax is:
sp_procoption [ @ProcName = ] 'procedure'
, [ @OptionName = ] 'option'
, [ @OptionValue = ] 'value'
Setting the Order of Triggers
The sp_settriggerorder built-in stored
procedure allows you to specify the order by which your AFTER
triggers should/must execute. Its syntax is:
sp_settriggerorder [ @triggername= ] '[ triggerschema. ] triggername'
, [ @order= ] 'value'
, [ @stmttype= ] 'statement_type'
[ , [ @namespace = ] { 'DATABASE' | 'SERVER' | NULL } ]
Sending Email
To give you the ability to send an email from a
database, Transact-SQL provides the sp_send_dbmail stored procedure.
This store procedure is created in the msdb database. This means that
you must reference it when executing this procedure. It's syntax is:
sp_send_dbmail [ [ @profile_name = ] 'profile_name' ]
[ , [ @recipients = ] 'recipients [ ; ...n ]' ]
[ , [ @copy_recipients = ] 'copy_recipient [ ; ...n ]' ]
[ , [ @blind_copy_recipients = ] 'blind_copy_recipient [ ; ...n ]' ]
[ , [ @subject = ] 'subject' ]
[ , [ @body = ] 'body' ]
[ , [ @body_format = ] 'body_format' ]
[ , [ @importance = ] 'importance' ]
[ , [ @sensitivity = ] 'sensitivity' ]
[ , [ @file_attachments = ] 'attachment [ ; ...n ]' ]
[ , [ @query = ] 'query' ]
[ , [ @execute_query_database = ] 'execute_query_database' ]
[ , [ @attach_query_result_as_file = ] attach_query_result_as_file ]
[ , [ @query_attachment_filename = ] query_attachment_filename ]
[ , [ @query_result_header = ] query_result_header ]
[ , [ @query_result_width = ] query_result_width ]
[ , [ @query_result_separator = ] 'query_result_separator' ]
[ , [ @exclude_query_output = ] exclude_query_output ]
[ , [ @append_query_error = ] append_query_error ]
[ , [ @query_no_truncate = ] query_no_truncate ]
[ , [ @mailitem_id = ] mailitem_id ] [ OUTPUT ]
As you may guess, most of the arguments are optional.
Otherwise:
Click Next. If you are trying a new profile, click the first
radio button:
Click Next. This would bring the third page of the wizard:
In the Profile Name text box, enter the desired name. If you
want, type some explanation in the Description text box. To
specify an account that can send emails, click Add and fill out
the form. Once you are ready, click OK. If you want to add
another profile, click Add again, fill out the form, and click
OK. On the third page of the wizard, click Next twice. When the
wizard has finished, click Close.
Here is an example of executing this stored procedure:
USE Exercise;
GO
EXEC msdb.dbo.sp_send_dbmail
@profile_name = N'Central Administrator',
@recipients = N'jaywiler@hothothot.net',
@body = N'The Persons table has received a new record.',
@subject = N'New Record';
GO
Before executing this procedure, you should check the
security settings on your server. Otherwise you may receive an error. Here
is an example:.
To solve this problem, open a Query Editor and type the
following:
sp_configure N'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure N'Database Mail XPs', 1;
GO
RECONFIGURE;
GO | http://www.functionx.com/sqlserver/Lesson44.htm | CC-MAIN-2015-06 | refinedweb | 2,147 | 50.46 |
#include "UT_Assert.h"
#include "UT_IteratorRange.h"
#include "UT_NonCopyable.h"
#include <SYS/SYS_Types.h>
#include <SYS/SYS_TypeTraits.h>
#include <functional>
#include <list>
#include <type_traits>
#include <unordered_map>
Go to the source code of this file.
A default helper function used by UT_LRUCache to determine whether an object is currently in use and so should not be deleted when the cache gets pruned.
Definition at line 59 of file UT_LRUCache.h.
A default helper function used by UT_LRUCache to determine the size of the objects it stores to help prune the storage so that it doesn't exceed the maximum given in the constructor.
Definition at line 46 of file UT_LRUCache.h. | http://www.sidefx.com/docs/hdk/_u_t___l_r_u_cache_8h.html | CC-MAIN-2018-17 | refinedweb | 109 | 60.31 |
New?
CheersChris.
I.
works perfectly now... thanks!
I installed the plugin on ST2 but I keep on getting this error when using the Check System option. I use Miktex and has latexmk and texcount and the necessary directories are already in the path.
Can you run latexmk from the cmd? As default latexmk is not installed on MikTeX, you have to run it once from the command prompt window and then it will be fetched automatically. If that is not solving the problem please check the python console for the detected path for your system.
import os
os.environ"PATH"]
I see. When I try running latekmk from the command prompt, I get this error:
Can't locate loadable object for module IO in @INC (@INC contains: C:/Program Files (x86)/MiKTeX 2.9/miktex/lib .) at C:/Program Files (x86)/MiKTeX 2.9/miktex/lib/IO/Handle.pm line 266
Compilation failed in require at C:/Program Files (x86)/MiKTeX 2.9/miktex/lib/IO/Handle.pm line 266.
BEGIN failed--compilation aborted at C:/Program Files (x86)/MiKTeX 2.9/miktex/lib/IO/Handle.pm line 266.
Compilation failed in require at C:/Program Files (x86)/MiKTeX 2.9/miktex/lib/IO/Seekable.pm line 101.
BEGIN failed--compilation aborted at C:/Program Files (x86)/MiKTeX 2.9/miktex/lib/IO/Seekable.pm line 101.
Compilation failed in require at C:/Program Files (x86)/MiKTeX 2.9/miktex/lib/IO/File.pm line 133.
BEGIN failed--compilation aborted at C:/Program Files (x86)/MiKTeX 2.9/miktex/lib/IO/File.pm line 133.
Compilation failed in require at C:/Program Files (x86)/MiKTeX 2.9/miktex/lib/FileHandle.pm line 9.
Compilation failed in require at C:\Program Files (x86)\MiKTeX 2.9\scripts\latexmk\perl\latexmk.pl line 120.
BEGIN failed--compilation aborted at C:\Program Files (x86)\MiKTeX 2.9\scripts\latexmk\perl\latexmk.pl line 120.
Is there other pre-requisites to run latexmk? I can see that this is no longer related to Latexing but I'll appreciate if you guys can help. I'm fine with creating a new thread if it's necessary so as not to highjack this one.
No bother, do you have perl installed (see here if not)? Normally I always prefer to install MiKTeX simple in "C:/MiKTeX" to avoid problems with spaces in your path but that problem what I had was versions ago and shouldn't related to this one here....' | https://forum.sublimetext.com/t/latex-plugin-latexing-for-st2-and-st3/9802/23 | CC-MAIN-2017-09 | refinedweb | 415 | 61.73 |
0
I am trying to use a loop to write randomly generated numbers to a text document. Then, using a different program, I need to use a loop to read the numbers. The first program needs to output the numbers in the SAME LINE, the second program needs to output them in DIFFERENT LINES (their own, one per line) Here is what I have:
**The write one works, I can't get the read one to become a float.
for the first program (write)
import random def main(): one = 1 thirteen = 13 subtract = 1 number_gen = open('numbers.txt', 'w') for number in range(one,thirteen,subtract): numbers = random.randit(1,100) number_gen.write(str(numbers + ' ') number_gen.close() main()
For the second program (read)
def main(): numbers_read = open('numbers.txt', 'r') for line in numbers_read: amount = float(line) print(format(amount, '.2f')) numbers_read.close() main() | https://www.daniweb.com/programming/software-development/threads/491950/python-using-a-loop-to-write-numbers-to-a-text-using-a-loop-to-read-them | CC-MAIN-2017-22 | refinedweb | 144 | 61.77 |
cmdmodule contains a base class for creating command interpreters.
Module: cmd
Purpose: Create line-oriented command processors.
Python Version: 1.4 and later, with some additions in 2.3
Description:
The
cmd module contains one public class,
Cmd, designed to be used as a base class for command processors such as interactive shells and other command interpreters. By default it uses readline for interactive prompt handling, command line editing, and command completion.
Processing Commands:for “foo”, 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, hitting Ctrl-D will drop us out of the interpreter.
(Cmd) ^D$
Notice that no newline is printed, so the results are a little messy.
Command Arguments: optional argument to the greet command, “person”. There is a distinction between the argument to the command and the method. The method always takes the argument, but sometimes the value is an empty string. It is left up to the command processor processor does not include the command itself. That simplifies parsing in the command processor, 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 our source. Of course we could edit the source to remove the extra white-space, but that would leave our application looking poorly formatted. An alternative solution is to implement a help handler for the greet command, named
help_greet(). When present, it is called on to produce help text for the named command.():
Cmdincludes support for command completion based on the names of the commands with processor methods. Completion is triggered by hitting the tab key on a line., " +:
Cmdincludes. processor is looked up and invoked. If none is found,
default()is called instead. Finally
postcmd()is called.
Here’s an example session with print statements added:
$ python:
In addition to the methods described above,):
self.prompt = line + ': '
def do_EOF(self, line):
return True
if __name__ == '__main__':
HelloWorld().cmdloop()
$ python cmd_attributes.py
Simple command processor example.
prompt: prompt hello
hello: help
doc_header
----------
prompt
undoc_header
------------
EOF help
hello:
Shelling Out:
To supplement the standard command processing,
Cmdincludes:
While the default mode for
Cmdis to interact with the user through the
readlinelibrary,interactsand prompt set to an empty string, we can all the script on this input file:
greet
greet Alice and Bob
to produce output like:
$ python cmd_file.py cmd_file.txt
hello,
hello, Alice and Bob
Commands from sys.argv:
If, instead of reading commands from stdin or a file, you want to process command line arguments to the program as a command for your interpreter class, that is also possible. In that case, you can cmd_argv.py greet Command Line User
hello, Command Line User
$ python cmd_argv.py
(Cmd) greet Interactive User
hello, Interactive User
(Cmd)
References:
Python Module of the Week Home
Download Sample Code
Technorati Tags:
python, PyMOTW | http://www.oreillynet.com/onlamp/blog/2008/05/pymotw_cmd.html | crawl-002 | refinedweb | 503 | 57.57 |
Hi,
When you select the DataSet in the Solution Explorer and look at it's properties there is a Custom Tool Namespace option. Enter your namespace in there and your DataSet is placed in that namespace. Do not open the DataSet and look at the properties, where you have the XSD namespace. It's the properties when the DataSet is selected in the Solution Explorer it's in with the Build Action property.
Microsoft is conducting an online survey to understand your opinion of the Msdn Web site. If you choose to participate, the online survey will be presented to you when you leave the Msdn Web site.
Would you like to participate? | https://social.msdn.microsoft.com/Forums/en-US/1c62c147-6fc5-44bf-87b6-3e0c803fd4cb/typed-dataset-generator-and-namespaces?forum=xmlandnetfx | CC-MAIN-2015-32 | refinedweb | 113 | 72.46 |
#include <aflibAudioMemoryInput.h>
Inheritance diagram for aflibAudioMemoryInput::
This class allows one to insert raw data into an audio chain at the start of the chain. This class can't be used anywhere in a chain other than at the start. Once an audio chain is formed then the caller can call the process member function of the last item in the chain and retrieve the aflibData object to get the raw audio data out of the chain. Users will call the process member function at the end of an audio chain. This will result in data being requested down the chain until this class is reached. Then the samples_callback will be called requesting audio data from the user. Users of this class should call the setAudioMemoryInputCallback function to register a callback function that will provide data to the chain. This callback function shall have 5 parameters and shall return the actual number of data stored. Since this object is at the beginning of the audio chain then in order for data to be inserted into the chain the caller must register a callback function before calling the process member function of the chain. The 5 parameters are:
aflibAudio * - the aflibAudioMemoryInput object that is making this call.
void * - pointer to the audio data memory location.
long - number of samples to read.
long - total length of samples (ie samples above * size of each sample).
long long - position in data stream that is requested.
The last parameter is the position of the data to read from. The user can request to start reading anywhere they wish. Thus they can start 10000 samples from the beginning of the audio data. If the user is streaming data then the library will make every attempt to request data sequentially from this class, but this is not guaranteed. | http://osalp.sourceforge.net/doc/html/class_aflibAudioMemoryInput.html | crawl-001 | refinedweb | 301 | 63.09 |
package adraw; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; /** * Copyright 2008 Viera K. Proulx * This program is distributed under the terms of the * GNU Lesser General Public License (LGPL) */ /** *
The implementation of callbacks for the key events.*
Report all regular key presses and the four arrow keys*
Ignore other key pressed events, key released events, * special keys, etc.*
The class has to be defined as public for the applet * classes to have access to it.* * @author Viera K. Proulx * @since May 1, 2008 */ public class MyKeyAdapter extends KeyAdapter { /** the current
{@link World World}* that handles the key events */ protected World currentWorld; /** the
KeyAdapterthat handles the key events */ protected MyKeyAdapter(World currentWorld){ this.currentWorld = currentWorld; } // --------------------------------------------------------------------// // the key event handlers // // --------------------------------------------------------------------//- /** *
Handle the key typed event from the canvas.*
This is where we get the letter keys.* * @param e the
KeyEventthat caused the callback */ public void keyTyped(KeyEvent e) { processEvent(e, "KEY TYPED: "); } /** *
Handle the key pressed event from the canvas.*
This is where we get the arrow keys.* * @param e the
KeyEventthat caused the callback */ public void keyPressed(KeyEvent e) { processEvent(e, "KEY PRESSED: "); } /** *
The key event major processor. The code is adopted from the code * provided by the Java documentation for key event processing.* *
We process all characters that can be typed on a keyboard, including * lower and upper case, digits, and special symbols.* *
KNOWN BUG: The key adapter stops processing key events after the * "TAB" key has been pressed. * We hope to solve this problem in a later release.* *
We have to jump through some hoops to avoid * trying to print non-printing characters * such as Shift. (Not only do they not print, * but if you put them in a String, the characters * afterward won't show up in the text area.)* *
The code for converting a single character
* to
String is included here. | http://www.ccs.neu.edu/javalib/Sources/v1.0/adraw/MyKeyAdapter.java | crawl-003 | refinedweb | 307 | 73.47 |
The Fundamental Theorem of Arithmetic states that every positive integer can be factored into primes in a unique way.
But first, what is a prime number? A prime number is a number greater than 1 that has no positive divisiors except 1 and itself e.g. 2 is prime. The primality of a given number can be find out by trial and error. It consists of testing whether is a multiple of any integer between and .
def is_prime(n): """returns True if given number is prime""" if n > 1: for i in range(2, int(n**0.5)+1, 1): if n % i == 0: return False else: return True else: return False
Some better algorithms exist to test the primality of a number.
Coming back to The Fundamental Theorem of Arithmetic, can be written as . There is no other way to factor it.
There are infinite prime numbers. One of the earliest proofs was given by Euclid.
Suppose there are finitely many primes. Let’s call them .
Now, consider the number .
is either prime or not. If it’s prime, then it was not in our list. If it’s not prime, then it’s divisible by some prime, . Notice, can’t be because of remainder 1. Thus, was not in our list. Either way, our assumption that there are finite number of primes is wrong. Hence, there are infinite primes.
One of the widely used applications of primes is in the public-key cryptography e.g. in the RSA cryptosystem. The RSA algorithm is based on the concept of trapdoor, a one-way function. Its strength lies in the fact that it’s computationally hard (impossible) to factorize large numbers. For now, there doesn’t exists any efficient algorithm for prime factorization.
For example, It’s easy for a computer to multiply two large prime numbers. But let’s say you multiply two large prime numbers together to get a resulting number. Now, if you give this new number to a computer and try to factorize, the computer will struggle e.g. to find which two prime nubmers are multiplied together to get 18848997161 is difficult.
The thirst to find the order in primes is one of the reasons for its quest.
References: | https://kharshit.github.io/blog/2018/01/05/some-prime-thoughts | CC-MAIN-2020-16 | refinedweb | 374 | 68.67 |
The ones who are crazy enough to think they can change the world are the ones who do.- Steve Jobs
A file is a collection of related records stored in a secondary storage of the computer. These informations are stored permanently. C allows programmers to read and write to the files when required.
A text file consisting of sequence of characters, numbers or contain sequence of lines. C provides library functions to access text files.
A Binary file consisting of collection of bytes.
Step 1: Before starts reading or writing into a file, programmers should declare a file pointer variable which points to a structure FILE. This helps to access file.
FILE *fptr;
The above syntax represent the FILE structure has the pointer variable *fptr. The file pointer is used to access the file.
Step 2: A file must be opened before the reading and writing operation begins. The function fopen() is the only function used to open a file.
FILE *fptr ; fptr = fopen("data.dat", "r");
The above syntax represents that the fopen() function will open the file data.dat in read mode. The function fopen checks the disk for a file(data.dat), if the file already exists, it will be opened for further read or write operation. Otherwise, it creates a new file.
Step 3: After completion of reading and writing operations, the file must be closed. C provides a special function fclose() to closing a file.
fclose(fptr);
#include <stdio.h> int main() { FILE *fptr; fptr = fopen("data.dat","r"); if(fptr == NULL) printf("ERROR: Not able to open the file "); else fclose(fptr); return 0; }
We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.
We to update you | https://www.2braces.com/c-programming/c-files | CC-MAIN-2017-51 | refinedweb | 298 | 77.74 |
2016-01-03 00:04:46 8 Comments
Inspired by this question I thought I provide my implementation. I tried to go with the spirit of the *nix tool chain - read from stdin and write to stdout. This has the added benefit of making buffering very easy (current and previous characters and the count).
All kinds of reviews welcome (best practices, error handling, weird edge cases, potential bugs or other pitfalls).
#include <stdio.h> #include <stdbool.h> #include <stdint.h> void write_char(int c) { if (EOF == putchar(c)) { if (ferror(stdout)) { perror("error writing char to stdout"); exit(EXIT_FAILURE); } } } void write_count(uint64_t count) { if (printf("%ull", count) < 0) { perror("error writing character count to stdout"); exit(EXIT_FAILURE); } } int main(int argc, char** argv) { int current_char = 0; int previous_char = 0; uint64_t current_char_count = 0; while (EOF != (current_char = getchar()) { if (current_char_count == 0 || current_char_count == UINT64_MAX || previous_char != current_char) { if (current_char_count > 0) { write_count(current_char_count); } write_char(current_char); current_char_count = 1; previous_char = current_char; } else { current_char_count += 1; } } }
Related Questions
Sponsored Content
2 Answered Questions
[SOLVED] String Compression
- 2018-11-20 20:03:57
- Exploring
- 226 View
- 1 Score
- 2 Answer
- Tags: java algorithm programming-challenge interview-questions compression
4 Answered Questions
[SOLVED] Algorithm for Run Length Encoding - String Compression
- 2015-12-31 20:59:20
- Jonathan
- 3181 View
- 12 Score
- 4 Answer
- Tags: beginner c strings compression
2 Answered Questions
[SOLVED] Simple string compression in Python
- 2016-09-17 20:07:52
- newToProgramming
- 7695 View
- 2 Score
- 2 Answer
- Tags: python strings python-3.x complexity compression
2 Answered Questions
[SOLVED] Naive string compression
- 2018-03-27 21:59:36
- CodeYogi
- 158 View
- 2 Score
- 2 Answer
- Tags: java strings programming-challenge interview-questions compression
2 Answered Questions
[SOLVED] Basic string compression implementation in C
- 2017-11-12 17:39:34
- emre can
- 1580 View
- -1 Score
- 2 Answer
- Tags: c strings compression
1 Answered Questions
[SOLVED] String compression implementation in C
- 2016-01-08 04:40:01
- CodeCrack
- 1593 View
- 1 Score
- 1 Answer
- Tags: algorithm c strings compression
2 Answered Questions
[SOLVED] Simple compression on steroids - now with decompression
- 2016-01-05 19:56:26
- ChrisWue
- 128 View
- 1 Score
- 2 Answer
- Tags: c compression
2 Answered Questions
[SOLVED] Simple compression reloaded++
- 2016-01-04 01:25:44
- ChrisWue
- 250 View
- 8 Score
- 2 Answer
- Tags: c compression
1 Answered Questions
[SOLVED] Simple LZW compression algorithm
- 2015-04-10 18:34:44
- robtwentyfour
- 16831 View
- 9 Score
- 1 Answer
- Tags: c++ c++11 compression
4 Answered Questions
[SOLVED] Simple compression algorithm
- 2014-09-04 08:18:13
- OregonTrail
- 1602 View
- 8 Score
- 4 Answer
- Tags: performance c security compression c99
@user3629249 2016-01-04 06:04:17
When compiling, always enable all the warnings, then fix those warnings.
For gcc, at a minimum, use:
-Wall -Wextra -pedantic(I also use
-std=c99 -Wconversion)
The compiler outputs several 'problem' statements:
To start: the
main()function signature of
int main(int argc, char* argv[])which in this case should be
int main( void ).
And, because of a missing
#include <stdlib.h>statement:
And this line:
has a syntax error (always check for matching numbers of open and close parens):
That error means the posted code was never compiled.
@ChrisWue 2016-01-04 21:38:37
As I've stated as comment to SirPython's answer: I accidentally copied an broken code version.
@SirPython 2016-01-03 00:33:28
Compressor number or real
When you are
write_counting, you are writing the ASCII number characters to the new file. However, when you go to decompress this file, how are you going to differentiate between the actual content in the file and the numbers that mark the occurrences of a character?
A possible solution for this might be to just write the number itself to the file (no ASCII). That way, when you encounter a number that is ASCII, you can be almost sure that the number is part of the content (that is, unless there was a letter that occurred so many times in a row that the counter rose into the
'0'-'9'range).
Two ones or twelve?
This is kind of a continuation from the top one. Let's say your compressor went to go compress this file:
Now, I am ready to decompress it. Since your compressor writes a number to show occurrences of a character, the output would be this:
How do I know if all of those numbers are part of the content?
The only fix I can think of, unfortunately, would be to follow the above tip and write
0x01instead of an ASCII number.
Misc
You are missing a brace here.
When compiling your code, I get this on this line:
This also showed a problem that two
ls are written after the number that shows how many character occurrences there were.
@ChrisWue 2016-01-03 04:56:49
Regarding your Misc bugs: must have copied accidentally an older version of the code. Sorry about that, should have checked more carefully. Good point about the number encoding, got some ideas about that. | https://tutel.me/c/codereview/questions/115680/simple+string+compression+reloaded | CC-MAIN-2019-35 | refinedweb | 837 | 53.04 |
Can you extend from a class in a separate Java file? Or do all parents need to be included in the extends file? If so, how do you associate the parent and child other than calling one from the other? How to do in eclipse?
can it be that the extends keyword have more than one (1) argument??
for example public class A extends B,C...
i want to learn programming languages completely
i dont understand your examples given
Post your Comment
The extends Keyword
The extends Keyword
The
extends
is a Java keyword, which is
used in inheritance process of Java. It specifies the superclass in a
class declaration using extends keyword
The extends keyword
The extends keyword
In this section you will learn about extends keyword in java. The
extends is a keyword in java which is used in inheritance. It is used... at the following example which illustrate the use of extends
keyword in java
Super - keyword
Super - keyword
super keyword
super is a keyword in java that plays an important role
in case of inheritance. Super keyword is used to access the members of the super
class. Java
Java final Keyword Example
Java final Keyword Example
In this section we will read about the final keyword in Java in various
context.
final keyword in Java can be used with the class name,
method name, and variable name. Whichever, the final keyword is
used
PHP Final Keyword
Final Keyword in PHP:
If you are familiar with Java then you must know the functionality of Final keyword. Final keyword prevents child classes from... of this class.
PHP Final Keyword Example:
<?php
class
A
{
final public
The abstract Keyword : Java Glossary
The abstract Keyword : Java Glossary
Abstract keyword used for method declaration declares... instantiated than that class use the abstract keyword but this
class rather
Super keyword in java
Super keyword in java
In this section we will discuss about the super keyword in java. Super is a
keyword defined in java. Super is used to refer...
"super" keyword. Here is the example to use super to call
super class
Extends Attribute of page Directive
Extends Attribute of page Directive How use language extends in page directive ?
This is used to signify the fully qualified name... Servlet.
Syntax :
<%@ page extends = "package.class"%>
<%@page import
The throw keyword example in java
Code:
class MyMadeException extends Exception{}
class ExceptionExample
{
public static void main(String[] args)
{
String test = args[0];
try
{
System.out.println ("First");
doriskyJob(test);
System.out.println ("
What is this keyword?
What is this keyword? What is this keyword
Keyword - this
Keyword - this
A keyword is a word having a particular meaning to the programming
language. Similarly, this keyword is used to represent an object constructed
from a class
what is the difference between extends and implements
what is the difference between extends and implements difference between extends and implements
The if Keyword
The
if Keyword
The if is a keyword, which is used to
perform the selection... that are executed in
case, the test condition specified by the if keyword evaluates
Page Directive attribute - extends
Page Directive attribute - extends
This tutorial contains description of extends attribute of page Directive.
extends Attribute :
This attribute... compiling this JSP page. It is rarely used.
Syntax :
<%@ page extends="
Java keyword
Java keyword Is sizeof a keyword
super keyword
super keyword super keyword explain
about implements and extends - Java Beginners
about implements and extends hello,
class A extends B implements c // this is valid statement
class A implements c extends B // this is invalid... A extends B implements C
but class A implements C extends B is invalid
plz
how to access the object of one frame on clicking a button without using this keyword
extends Frame
{
public static void main(String args[])
{
Button b1...)
{
System.exit(0);
}
});
}
}
class Myclass extends Frame implements
Dynamic keyword
Dynamic keyword hi.......
What is the dynamic keyword used for in flex?
give me the answer ASAP
Thanks Ans: Dynamic keyword... during the run-time. Just add the magic keyword dynamic to the class definition
ExtendsJordan Disko February 22, 2012 at 2:10 AM
Can you extend from a class in a separate Java file? Or do all parents need to be included in the extends file? If so, how do you associate the parent and child other than calling one from the other? How to do in eclipse?
extends keywordRob March 28, 2012 at 3:20 PM
can it be that the extends keyword have more than one (1) argument?? for example public class A extends B,C...
c,c++,javaK.sabari nathan October 26, 2012 at 12:24 PM
i want to learn programming languages completely
computer programmingJenny Angcon November 26, 2012 at 10:17 AM
i dont understand your examples given
Post your Comment | http://www.roseindia.net/discussion/17891-The-extends-Keyword.html | CC-MAIN-2015-22 | refinedweb | 799 | 55.03 |
One thing I missed a lot coming from TextMate was the ability to jump up and down the page to lines at the same indent level: →
I made a small plugin that reproduces this functionality, including extending your selection while jumping. You can find the source on github and install it using Package Control.
Feedback and suggestions are welcome!
Cool! This is very useful for prose writing, as it allows me to skip from paragraph to paragraph. (In prose writing a paragraph is a indistinguishable from a line of code, except that they occupy several "lines" due to soft wrapping, which your plugin disregards.)
Would it be possible to add a setting for taking whitespace into account along with indenting? That is, to provide an option to stop the cursor stop on the first "line" (with soft-wrap) after and before a line of whitespace. (In the same way that Ctrl+Left/Right moves from word to word, but also allows you to move to the beginning and end of the current word).
Does this make sense?
Alex
Edit: Is that font Anonymous Pro?
I'm glad you like it! I really like your suggestion, and I've implemented it for several lines at the same indent level. Unfortunately, I couldn't find a good way to take soft-wrapped lines into account. I could probably do it if you use a monospace font by checking the width of the window and dividing by the width of the characters, but that's pretty hacky. Does anyone know of a better way of finding the beginnings of soft-wrapped lines?
The font is Source Code Pro Light by Adobe.
I thought I was confusing . . . I actually like that your plugin disregards soft-wrapped lines. The addition I was asking for was some consideration for whitespace. The closest thing I can come up with is to look at how Ctrl+Left/Right works. When you are within a word, moving to the right takes you to the end of the word before (on the next press) you are taken to the end of the next word and so on.
Let me try and explain at the level of the "paragraph" (i.e., loads of soft-wrapped text):
Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
Suspendisse malesuada semper
lectus, quis adipiscing metus aliquam vitae.
Morbi commodo, scelerisque laoreet,
magna elit | vestibulum ligula,
vitae eleifend risus erat vel lorem.
Dignissim ullamcorper nulla pharetra non.
Mauris arcu vel eros hendrerit vitae semper
tortor sodales. Vestibulum vel tincidunt metus.
If the cursor is between elit and vestibulum, I would like Alt+Up to move me to commodo and then to ipsum. If I then press Alt+Down, it would move me to quis and then eleifend (approximately).
commodo
ipsum
quis
eleifend
Does this make sense? (And is it possible?)
So it actually does work that way now with separate lines. The problem is that it sees the paragraphs as one long line, so there's no way to jump to the last "line" of the paragraph. If there's a good way of identifying soft-wrapped lines, then I could definitely implement it. In the meantime, I'll try implementing it by dividing the window width by the character width.
Thanks for sharing.
Thanks for developing this plugin!
It was almost what I wanted, so I had a go and made two commands that do something similar. They are not as smart as Jump Along Indent. They only "jump to top/bottom" of the current level of indentation. The indent region is determined by using the build-in command "expand_selection to indentation".
Here is the plugin code:
class JumpToIndentTopCommand(sublime_plugin.TextCommand):
def run(self, edit):
self.view.run_command("expand_selection",{"to": "indentation"})
pos = self.view.sel()[0].a
self.view.sel().clear()
self.view.sel().add(sublime.Region(pos,pos))
class JumpToIndentBottomCommand(sublime_plugin.TextCommand):
def run(self, edit):
self.view.run_command("expand_selection",{"to": "indentation"})
pos = self.view.line(self.view.sel()[0].b-1).a
self.view.sel().clear()
self.view.sel().add(sublime.Region(pos,pos))
Like Jump Along Indent, I then bind these two commands to alt+up and alt+down .
I actually use a slightly different version of this to move one line further up. So it jumps "up" a level, which helps in language like Python: with a couple of jumps, you can easily land on the current code scope's def or class. This is close to the operation achieved by using goto symbol (ctrl+r) then jump to the current def or next def.
This is probably not perfect, I haven't used it long enough to know all the quirks in various situation. Who knows, maybe one day I will switch back and use Jump Along Indent. But maybe someone will find this useful. Or maybe someone can point out how I can improve this. | https://forum.sublimetext.com/t/jump-along-indent/11868/7 | CC-MAIN-2016-40 | refinedweb | 816 | 66.44 |
To use Ant from Eclipse, create a new project, Ch05_01 , and add a new class to it, Ch05_01 . In this class's main method, we'll just display the message "No worries.", as you see in Example 5-1.
package org.eclipsebook.ch05; public class Ch05_01 { public static void main(String[] args) { System.out.println("No worries."); } }
To work with Ant, we'll need an Ant build file, which is named build.xml by default. To create that file in this project, right-click the project and select New File. Enter the name of the new file, build.xml , in the File name box and click Finish. You use the XML in this file to tell Ant how to build your project. Although Eclipse can automate the connection to Ant, Ant needs this XML build file to understand what you want it to do, which means that we will have to master the syntax in this file.
Eclipse recognizes that build.xml is an Ant build file and marks it with an ant icon, as you see at left in Figure 5-1.
Enter this simple XML into build.xml all we're going to do here is have Ant echo a message, "Ant at work!", to the console:
<?xml version = "1.0" encoding="UTF-8" ?> <project name = "Ch05_01" default = "Main Build"> <target name = "Main Build"> <echo message = "Ant at work!" /> </target> </project>
This XML makes the target , which we've named "Main Build," into the default target . An Ant target specifies a set of tasks you want to have run, similar to a method in Java. The default target is that which is executed when no specific target is supplied to Ant. In this case, we're just going to have this default target echo a message to the console; nothing's going to be compiled.
You can see this new XML in the Ant editor in Figure 5-2. The Ant editor uses syntax highlighting, just as the JDT editor does, and you can see an outline of the build.xml document in the Outline view at right.
Save build.xml and right-click it, selecting the Run Ant item. This opens the Ch05_01 build.xml dialog you see in Figure 5-3. You can see that the default target, Main Build , is already selected.
Click the Run button in this dialog to run Ant. When you do, you'll see something like this in the Console view (note that your message was echoed here):
Buildfile: D:\eclipse211\eclipse\workspace\Ch05_01\build.xml Main Build: [echo] Ant at work! BUILD SUCCESSFUL Total time: 430 milliseconds
That's exactly what we wanted this example to do. That's a quick example to show how to interact with Ant from Eclipse, but all it does is display the message "Ant at work!" It doesn't compile anything, it doesn't create any JAR files, but it does give us a start on using Ant in Eclipse. We'll get more advanced in our next example. | https://flylib.com/books/en/1.258.1.35/1/ | CC-MAIN-2020-24 | refinedweb | 505 | 83.76 |
ReSharper replaces fully qualified names with short names in C# and VB.NET code where possible by importing namespaces.
To shorten qualified references
- Choose ReSharper | Options | Languages | C# | Namespace Imports (for C# settings) or ReSharper | Options | Languages | Visual Basic .NET | Namespace Imports (for VB.NET settings).
- You can choose to use fully qualified names always or to use short names with namespace imports. In the Reference Qualification section click Insert using directives when necessary or Use fully qualified names. Moreover you can tune replacing, select or clear check boxes.
- Choose Tools | Code Cleanup in ReSharper Options dialog box.
- Create a new profile as described in
Creating Custom Profiles. In the Selected profile settings section for the new profile select Shorten qualified references check box.
- shorten qualified references. | http://www.jetbrains.com/resharper/webhelp50/Code_Cleanup__Usage_Scenarios__Shortening_Qualified_References.html | CC-MAIN-2014-15 | refinedweb | 127 | 51.44 |
The microcontroller clock is the key to do anything, because everything is based and works due the clock signal. So understand the clock is vital to work with any microcontroller. Here you can take a look in the STM ARM Cortex-M3 clock and how to analyze the instructions time using the Keil uVision IDE simulator.
From the SMT32F103C8T6 datasheet we know:
System clock selection is performed on startup, however the internal RC 8 MHz oscillator is
selected as default CPU clock on reset.
But how can it reaches 72 Mhz if has just a 8 Mhz internal oscillator? this is done using a technique called PLL (Phase-locked Loop), which can multiply this 8 Mhz input clock and output a higher clock, achieving the 72 Mhz as maximum frequency.
Now we know that the default clock is 72 Mhz, which is the same of 13,88 nanoseconds, because frequency (hertz) = 1 / time (seconds). So let's check this in the simulator, go to project options:
Now we know that the default clock is 72 Mhz, which is the same of 13,88 nanoseconds, because frequency (hertz) = 1 / time (seconds). So let's check this in the simulator, go to project options:
Tab "Target" and set the clock as 8 Mhz:
Now we can use the nop assembly instruction, that do nothing, but uses 1 clock cycle, allowing us to see if it really spend 13,88 nanoseconds per clock cycle. The code is simple, just go to the package manager:
And select "Startup":
Now create the "main.c" file with this content:
#include <stm32f10x.h> volatile uint32_t msTicks; int main() { SystemInit(); __asm{NOP} //1 cycle ~= 13,88 nanoseconds __asm{NOP} __asm{NOP} __asm{NOP} __asm{NOP} }
Set a breakpoint (F9) at the first nop and debug the code! The video below show how to see the instruction time using the "performance analyzer":
Due the "performance analyzer" precision of 1 us, we see 13,88 nanoseconds (0,01388 us) as 0,014 us !
That's all, now try with a delay function!
About the versions
- Keil uVision 5.11.1.0
- ARM Cortex-M3 STM32F103C8T6
0 comentários : | http://www.l3oc.com/2015/05/stm-arm-cortex-m3-clock.html | CC-MAIN-2017-51 | refinedweb | 357 | 67.18 |
By Michael Fitzgerald
Book Price: $34.99 USD
£24.99 GBP
PDF Price: $24.99
Cover | Table of Contents | Colophon
$ which ruby
/usr/local/bin/ruby
$ ruby -v
$ ruby --version
ruby 1.8.6 (2007-03-13 patchlevel 0) [powerpc-darwin8.9.0]
puts "Hello, Matz!"
Hello, Matz!on your screen, followed by a newline character.
;) if you want, just like in C or Java, but you sure don't have to: a newline will do fine. (Most Ruby programmers don't use
;except when writing multiple statements on one line.)
$ irb -v
irb 0.9.5(05/04/13)
irb(main):001:0> puts "Hello, Matz! " Hello, Matz! => nil
nil, set off by
=>in the output of irb, is a value returned by the method
puts.
nilhas a special meaning in Ruby. It denotes empty and always means false.
putsprints out the string
Hello, Matz!, followed by a newline character.
LF(linefeed) character; on Microsoft Windows, it's
CR+
LF(a carriage return character followed by a linefeed).
Hello, Matz!is assigned to the name
hiand printed by
puts:
irb(main):002:0> hi = "Hello, Matz!" => "Hello, Matz! " irb(main):003:0> puts hi Hello, Matz! => nil
hithree times:
irb(main):004:0> puts hi * 3 Hello, Matz! Hello, Matz! Hello, Matz! => nil
irb(main):006:0> 10 + 10 => 20 irb(main):007:0> 4 * 5 => 20 irb(main):008:0> 100 / 5 => 20 irb(main):009:0> 50 - 30 => 20 irb(main):010:0> 80 % 60 => 20
configureand
make. We'll take advantage of them here as we install a new version of Ruby on Tiger (these steps could apply to a Linux installation as well).
-bash: ./matz.rb: Permission denied
chmodcommand by typing:
chmod 755 matz.rb
755makes the control list read
rwxr-xr-x(where
rmeans read,
wwrite, and
xexecute). This means that the file is readable and executable by everyone (owner, group, and others, in that order), but writable only by the owner. To find out more about
chmod, type
man chmodat a shell prompt.
#!), which allows the program to execute by merely invoking its name in a shell on Unix/Linux systems. However, you can achieve a similar effect to shebang by creating a file type association with the
assocand
ftypecommands on Windows.
assoccommand:
C:\Ruby Code>assoc .rb File association not found for extension .rb
C:\Ruby Code>assoc .rb=rbFile
C:\Ruby Code>assoc .rb .rb=rbFile
C:\Ruby Code>ftype rbfile File type 'rbfile' not found or no open command associated with it.
C:\Ruby Code>ftype rbfile="C:\Program Files\Ruby\bin\ruby.exe" "%1" %*
%1is a substitution variable for the file you want to run, and
%*accepts all other parameters that may appear on the command line. Test it:
C:\Ruby Code>ftype rbfile rbfile="C:\Program Files\Ruby\bin\ruby.exe" "%1" %*
PATHEXTenvironment variable. Is it there already?
C:\Ruby Code>set PATHEXT PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.tcl
C:\Ruby Code>set PATHEXT=.rb;%PATHEXT%
C:\Ruby Code>set PATHEXT PATHEXT=.rb;.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.tcl
C:\Ruby Code> matz Hello, Matz!
Objectclass and the
Kernelmodule, reserved words (keywords), comments, variables, methods, and so forth. Most topics will be dealt with elsewhere in the book in more detail. Some topics merit entire chapters, others only sections (found in ). I'll always tell you where else to look for more information on a topic. This book's most detailed discussions on methods and blocks are found in this chapter..
class Hello def howdy greeting = "Hello, Matz!" puts greeting end end class Goodbye < Hello def solong farewell = "Goodbye, Matz." puts farewell end end friendly = Goodbye.new friendly.howdy friendly.solong
$ friendly.rb Hello, Matz! Goodbye, Matz.
#) can be at the beginning of a line:
# I am a comment. Just ignore me.
name = "Floydene Wallup" # ain't that a name to beat all
# This is a comment. # This is a comment, too. # This is a comment, too. # I said that already.
=begin/
=end:
=begin This is a comment. This is a comment, too. This is a comment, too. I said that already. =end
xis assigned the value
100by the equals sign.
x = 100
xholds the value
100. But, hey, what type is it? Looks like an integer to me—how about you? And what does Ruby think?
int) on the left:
int months = 12; int year = 2007;
months = 12 year = 2007
x,
months, and
yearare clearly integers, but you didn't have to give them a type because Ruby does that for you, automatically. It's called dynamic or duck typing.
x—that is, whether it is an integer—with the
kind_of?method (this method is from the
Objectclass).
x.kind_of? Integer # => true
xbehaves like an integer! As a matter of fact, it is an instance of the
Fixnumclass, which inherits the
Integerclass.
x.class # => Fixnum
xfrom an integer to a floating point with the
to_fmethod from the
Fixnumclass (it is inherited by other classes, too).
x.to_f # => 100.0
thoreau = "If a man does not keep pace with his companions, perhaps it is because he hears a different drummer."
Stringmethods, you can access and manipulate the string
thoreau. For example, you can retrieve part of a string with the
[]method, using a
range. Let's grab characters 37 through 46:
thoreau[37..46] # => "companions"
thoreau[-8..-2] # => "drummer"
chrmethod), separating each character with a slash:
thoreau.each_byte do |c| print c.chr, "/" end # => I/f/ /a/ /m/a/n/ /d/o/e/s/ /n/o/t/ /k/e/e/p/ /p/a/c/e/ /w/i/t/h/ /h/i/s/ /c/o/m/p/a/n/i/o/n/s/,/ /p/e/r/h/a/p/s/ /i/t/ /i/s/ /b/e/c/a/u/s/e/ /h/e/ /h/e/a/r/s/ /a/ /d/i/f/f/e/r/e/n/t/ /d/r/u/m/m/e/r/./
$KCODEvariable to
'u'(for UTF-8),
'e'(for EUC),
's'(for SJIS), or
'a'or
'n'(for ASCII or
NONE).
chrmethod converts a character code (which
each_byteproduces) into an actual character. You should also know about the opposite method—the
?operator, which returns a character code from a character. I'll demonstrate that with
1001, a positive integer, is an instance of the
Fixnumclass, which is a child class of
Integer, which is a child class of
Numeric. The number
1001.0, a floating point value, is an instance of the
Floatclass, which is also a child class of
Numeric. ( shows the relationships between these classes.)
irb(main):001:0> 3 + 4 # add => 7 irb(main):002:0> 7 - 3 # subtract => 4 irb(main):003:0> 3 * 4 # multiply => 12 irb(main):004:0> 12 / 4 # divide => 3 irb(main):005:0> 12**2 # raise to a power (exponent) => 144 irb(main):006:0> 12 % 7 # modulo (remainder) => 5
irb(main):007:0> x = 12 # assignment => 12 irb(main):008:0> x += 1 # abbreviated assignment add => 13 irb(main):009:0> x -= 1 # abbreviated assignment subtract => 12 irb(main):010:0> x *= 2 # abbreviated assignment multiply => 24 irb(main):011:0> x /= 2 # abbreviated assignment divide => 12
Mathmodule that provides all kinds of math functions (in the form of class methods), like square root, cosine, tangent, and so forth. Here is an example call to the class method
sqrtfrom the
Mathmodule:
irb(main):012:0> Math.sqrt(16) => 4.0
Rationalfor doing fractions. You'll learn much more about numbers and operators in . shows all of Ruby's math operators, including operator precedence.
ifstatement that tests whether a variable has a value of zero:
value = 0 if value.zero? then puts "value is zero. Did you guess that one?" end
zero?method returns true if the value of
valueis zero, which it is, so the statement following is executed (and any other statements in the code block
if/
end). By Ruby convention, any method in Ruby that ends with a question mark returns a Boolean, either
trueor
false. This convention is not enforced, however.
caseand
while, and less familiar ones like
untiland
unless. covers all of the conditional statements you'll find in Ruby.
pacific = [ "Washington", "Oregon", "California"]
pacific. It holds three strings—the names of the three states that make up the west coast of the United States. These strings are the elements of the array. The elements of an array can be of any Ruby kind, not just strings, of course. This is only one way to define an array. There are a number of other ways you could do this, as you'll see in .
[]method.
pacific[0] # => "Washington"
0,
Washington. You can learn all about Ruby arrays in .
pacific = { "WA" => "Washington", "OR" => "Oregon", "CA" => "California" }
=>) with a key. One of the ways you can access the values in a hash is by their keys. To access the value
Oregonfrom the hash, you could use
Hash's
[]method.
pacific["OR"] # => "Oregon"
ORreturns the value
Oregon. The keys and values can be of any kind, not just strings. You can learn more about hashes in .
hello, created with the keywords
defand
end:
def hello puts "Hello, Matz!" end hello # => Hello, Matz!
hellomethod simply outputs a string with
puts. On the flip side, you can undefine a method with
undef.
undef hello # undefines the method named hello hello # try calling this method now NameError: undefined local variable or method 'hello' for main:Object from (irb):11 from :0
repeatmethod:
def repeat( word, times ) puts word * times end repeat("Hello! ", 3) # => Hello! Hello! Hello! repeat "Good-bye! ", 4 # => Good-bye! Good-bye! Good-bye! Good-bye!
repeatmethod has two arguments,
wordand
times. You can call a method that has arguments with or without parentheses around the arguments. You can even define method arguments without parentheses, but I don't usually do it that way.
+. Each line that follows is actually a valid call to the
Fixnum +method:
10 + 2 # => 12 10.+ 2 # => 12 (10).+(2) # => 12
returnstatement. In Ruby, the last value in a method is returned, with or without an explicit
returnstatement. This is a Ruby idiom. Here's how to do it in irb:
matzthat just contains a string:
rb(main):001:0> def matz irb(main):002:1> "Hello, Matz!" irb(main):003:1> end => nil
matzmethod, and you will see its output. This is available in
pacific? Here it is again:
pacific = [ "Washington", "Oregon", "California" ]
pacificto retrieve all of its elements, one at a time, with the
eachmethod. Here is one way to do it:
pacific.each do |element| puts element end
|element|) can be any name you want. The block uses it as a local variable to keep track of every element in the array, and later uses it to do something with the element. This block uses
putsto print each element in the array:
Washington Oregon California
do/
endwith a pair of braces, as is commonly done, to make things a bit tighter (by the way, braces actually have a higher precedence than
do/
end):
pacific.each { |e| puts e }
eachmethods in them, such as
Array,
Hash, and
String. But don't get the wrong idea. Iterating over data structures isn't the only way to use blocks. Let me give you a simple example using
yield, a Ruby keyword.
gimmethat contains nothing more than a
yieldstatement:
def gimme yield end
yielddoes, call
gimmealone and see what happens:
gimme LocalJumpError: no block given from (irb):11:in `gimme' from (irb):13 from :0
yieldis to execute the code block that is associated with the method. That was missing in the call to
gimme. We can avoid this error by using the
block_given?method from
Kernel. Redefine
gimmewith an
ifstatement:
def gimme if block_given? yield else puts "I'm blockless!" end end
:).
to_symor
internmethods on a string or by assigning a symbol to a symbol. To understand this better, let's take a string on a roundtrip from a string to a symbol and back to a string.
name = "Matz" name.to_sym # => :Matz :Matz.id2name # => "Matz" name == :Matz.id2name # => true
nameis magically transformed into the label of a symbol. So what?
Symbol.all_symbols
tryblocks; in Ruby, you would just use a
beginblock.
catchstatements in Java and C++ are used where Ruby has
rescuestatements. Where Java uses a
finallyclause, Ruby uses
ensure.
===) on the left margin set off a heading, and indented text is formatted as code. RDoc can generate output as HTML, XML, ri (Ruby information), or Windows help (chm) files.
ri Kernel.print
----------------------------------------------------------- Kernel#print print(obj, ...) => nil ------------------------------------------------------------------------
Objectclass include?
?, what does that signify by convention?
ifand
while, are standard fare and quite familiar to programmers, while others, like
unlessand
until, are not. Think of control structures, which contain conditional statements, as lie detector tests. In every instance, when you use a control structure with a conditional, you are asking if something is true or false. When you get the desired answer—true or false depending on how you've designed your code—the code block associated with the control is executed.
rescueand
ensure, which are used for exception handling, are not explained here. They are discussed in .
ifstatement—one of the most common structures in just about any programming language.with a colon (
:), like this:
x = 256 if x == 256: puts "x equals 256" end
xso that it won't return
truewhen fed towit | http://www.oreilly.com/catalog/9780596529864/toc.html | crawl-001 | refinedweb | 2,238 | 68.36 |
{
public boolean equals(C that) { return id(this) == id(that); }
}
But in order for table.get(c) to work you need to make the
equals method take an Object as the argument, not a
C:
public class C {
public boolean equals(Object that) {
return (that instanceof C) && id(this) == id((C)that);
}
}
Why? The code for Hashtable.get looks something like this:
public class Hashtable {
public Object get(Object key) {
Object entry;
...
if (entry.equals(key)) ...
}
}:
public class C {
public boolean equals(Object that) {
return (this == that)
|| ((that instanceof C) && this.equals((C)that));
}
public boolean equals(C that) {
return id(this) == id(that); // Or whatever is appropriate for class C
}
}
public class C2 extends C {
int newField = 0;
public boolean equals(Object that) {
if (this == that) return true;
else if (!(that instanceof C2)) return false;
else return this.newField == ((C2)that).newField) && super.equals(that);
}
}.
public class LinkedList {
Object contents;
LinkedList next = null;
public boolean equals(Object that) {
return (this == that)
|| ((that instanceof LinkedList) && this.equals((LinkedList)that));
}
public boolean equals(LinkedList that) { // Buggy!
return Util.equals(this.contents, that.contents) &&
Util.equals(this.next, that.next);
}
}
Here I have assumed there is a Util class with:
public static boolean equals(Object x, Object y) {
return (x == y) || (x != null && x.equals.)
This tip is reprinted on JavaFAQ.nu by by courtesy of
Peter Norvig I am
thankful for his important contributions to my site - 21 Infrequently Answered
Java Questions. Alexandre Patchine
RSS feed Java FAQ News | http://javafaq.nu/java-article893.html | CC-MAIN-2018-09 | refinedweb | 248 | 55.44 |
This is the mail archive of the gcc-bugs@gcc.gnu.org mailing list for the GCC project.
"austern at apple dot com" <gcc-bugzilla@gcc.gnu.org> writes: | So what to do about this? In principle, I think the answer is that | builtin_function is doing something wrong by calling | builtin_function_1 twice, once for the global namespace and once for | namespace std. If we really must define all builtins in namespace | std (what's the rationale?), then at least we should do it with a | using-declaration instead of creating two entirely separate decls. | This would help compile I believe what happened there is that it was an attempt to implement the standard mandated semantics where names in <xxx.h> appears to be using-declarations for names in <cxx> -- except that the actual implementation gets everything wrong :-/ So the idea was that we get an artificial declaration in both :: and std::. If we actually write a decl in std::, that is it; same if we write it in ::. Except that the artificial declaration in :: should have been a using-declaration for the "real" artificial declaration in std::. And attributes and whatever should apply transparently to both -- because they have extern "C" language specification. That is what failed. -- Gaby | http://gcc.gnu.org/ml/gcc-bugs/2004-11/msg03784.html | crawl-001 | refinedweb | 208 | 56.25 |
iCelGraph Struct Reference
Interface for the CEL Graph. More...
#include <tools/celgraph.h>
Inheritance diagram for iCelGraph:
Detailed Description
Interface for the CEL Graph.
Definition at line 270 of file celgraph.h.
Member Function Documentation
Adds an edge to the graph.
Adds an edge to the graph.
Adds a node to the graph.
Create a node for this graph.
The node will be added to the graph.
Gets the closest node to position.
Get Number of Nodes.
Gets the shortest path from node from to node to.
Gets the shortest path from node from to node to.
The documentation for this struct was generated from the following file:
- tools/celgraph.h
Generated for CEL: Crystal Entity Layer 1.4.1 by doxygen 1.7.1 | http://crystalspace3d.org/cel/docs/online/api-1.4.1/structiCelGraph.html | CC-MAIN-2014-10 | refinedweb | 125 | 72.12 |
My fingers have been tingling to write this article. Ever since I implemented Enhanced Ecommerce on my blog a couple of weeks ago, I’ve been getting such an impressive amount of useful data that it’s mind-boggling..
Ecommerce and content, huh?
You might be surprised at what the premise of this article is. Usually, Ecommerce plugins are used to track transactions on your web store, so what does this have to do with content? Well, I don’t have a web store on my blog, but every reader who reads an article is valuable to me. If they are valuable, there must be some way to measure their value, and perhaps use this data to benchmark against future products (i.e. articles) I want to create.
Enhanced Ecommerce gives you a bunch of useful reports, which you can use to track not only store transactions but any kind of user interaction on your site. You just have to see your site in terms of funnels. This means that you need to translate Ecommerce terminology to match the conceptual framework of your site, whether it’s a blog, a web store, a news portal, or a brand site.
On my blog, the terminology ended up something like this:
- Product: A blog article.
- Product price: The number of words in the article.
- Product impression: At minimum the title, but usually title + ingress combination of articles on various category pages, and in article sidebars.
- Product list: A page or widget which holds a number of Product impressions. For example, my home page, category pages, tag pages, and related posts lists are all considered Product lists in my Enhanced Ecommerce setup.
- Product list click: A click action on an article title or “Read more…” link in the product lists.
- Product detail view: When the article is loaded.
- Add to cart: When scrolling begins on the article. I can assume that the reader wants to “buy” it if they start scrolling.
- Checkout: The Checkout funnel in my setup is based on scroll tracking. The first step is when the reader reaches one third of the article, the second step when they scroll two thirds, and the last step is when the article end is reached.
- Purchase: Purchase occurs when the checkout funnel is passed through, and a minimum of 60 seconds has elapsed since the article was loaded. This is an arbitrary number of seconds I simply chose to weed out casual readers from actual readers.
UPDATE: Thanks to an idea from Robert Petković, I updated the collection method with Product Detail impressions and Add To Cart actions. These were missing from the first version of this article. I also changed the checkout funnel to reflect scroll depth.
How to set it up
First, here’s the Git repository link for this solution: eec-gtm.
I’ll reveal a dirty secret from the get-go: I scrape the DOM for my setup. It’s definitely not the most robust way to go, but since I’m the developer, the marketer, the owner, and the content creator on my site, I can be safe to know that any changes to the page template are totally under my own control.
The way it SHOULD work is to leverage
dataLayer. You have a number of options when doing this. You could, for example, store every single product on the page into
dataLayer when the page is rendered, and then pick the relevant objects when impressions are loaded, or when user actions like clicks take place. Another way to go is to store the products in some other global JavaScript variable, which is, perhaps, a bit easier to access, but it does pollute the global namespace which should generally be avoided.
Anyway, I scrape. I’m a scraper. I did it for science, for progress, for technology. And because I was a bit lazy and didn’t want to customise my WordPress hooks. But, in short, here’s how my setup works.
1. Product impressions
On every page which has product lists, I build the
ecommerce.impressions Array as soon as the DOM has loaded. In this Array, each object is a single article title (+ ingress) that’s visible in one of the possible product lists. Product lists on my site are:
- Main posts – the home page listing
- Category posts – if a visitor has chosen to see all posts in a given category
- Tag posts – if a visitor has chosen to see all posts tagged with a specific tag
- Search results – the list of results you get if you use internal search
- Recent posts – the “Recent posts” widget in the sidebar
- Recent comments – the “Recent comments” widget in the sidebar
- GTM Tips – the “GTM Tips” widget in the sidebar
List position is determined by the order of posts in the list. An individual product object would look something like this:
As you can see, it’s very simple.
category is the WordPress category assigned to the post (there’s only every one category on my articles),
id is a truncated version of the article title,
name is the name of the article, and
list and
position define where the impression was listed.
So for every impression, I push an object like above into the Array. I also have a Promotion view for my “Were you looking for my GTM posts?…” info box on the home page of my site, but this hasn’t proven very useful, so I might remove it.
On any given page, the Array might look something like this:
A very simple setup for a very simple purpose. I send this Array with a Non-Interaction: True Event tag, because I don’t want to delay my pageview from firing until the impression Array is built, and I don’t want impressions to affect bounce rate.
2. Product list clicks
I track product list clicks using a Link Click trigger. When someone clicks on an article title or the “Read more…” link on the product list, I push details about the clicked product into
dataLayer, together with the ‘productClick’ value for the ‘event’ key, which then triggers an Event tag.
Firing this event lets me see the effectiveness of my product lists. It gives me information about how the different lists fare in light of the entire customer journey from product impression to purchase.
3. The Checkout Flow
The checkout flow combines Product Detail impressions, Add To Cart actions, and the checkout flow itself.
A Product Detail impression is sent as a Non-interaction: True event as soon as the article is loaded. This impression can thus be interpreted as the reader quickly checking out whether or not they want to read the article.
The Add To Cart action occurs when the user starts scrolling. The payload is sent with a normal Event tag to Google Analytics. I consider scrolling to be revealing of the reader’s intention to consume the content, but it’s not a checkout yet, as they might just want to skim the first paragraph.
The checkout flow itself is pretty cool. I use the scroll tracking plugin Justin Cutroni wrote about on his site. I’ve modified it to work with Google Tag Manager, and I also customised it to work with “Purchases” as well (see next chapter).
Here’s how it works right now:
- I calculate the length of the content DIV in pixels.
- When the viewport of the user’s browser reaches one third of this length, the first checkout step is sent as a normal Google Analytics event. This step is labelled “Read one third”.
- When the browser reaches two thirds of the content length, the second checkout step is sent as a GA event. This step is labelled “Read two thirds”.
- When the browser reaches the end of the content DIV, the final checkout step is sent as a GA event. This step is labelled “Reached end of content”.
- Finally, if the user has reached Step 3 and spent a minimum of 60 seconds on the article page, the “Purchase” event is sent as well (see next chapter).
You’ll need to modify this funnel and the setup to match the type of content you write. You might want to change the dwell time from 60 seconds to something else, and you might want to add more steps to the checkout funnel (25 %, 50 %, 75 %, for example). For me, this level of granularity was enough.
That’s a sample checkout object for the second step of the funnel. As you can see, I have price as one of the properties of the article. Here’s the kicker: price is the number of words on the article. Naturally, I’ve turned it into a “.99” number to make it more realistic as an actual price :-) You’ll see the usefulness of this once I get to the reports.
4. Purchase
Like I wrote in the previous chapter, a “Purchase” event is pushed when the checkout funnel is completed, and the visitor has spent 60 seconds on the site. The purchase itself is a perfectly standard Enhanced Ecommerce Purchase object, which might look like this:
The transaction ID is basically epoch timestamp plus a string of random characters. The quantity of products in a transaction will always be 1.
The analysis
So, let’s go over my favorite reports and segments. First, there’s the Shopping Behavior report:
As you can see, this shows the interactions during the selected timeframe. In this example, the timeframe is just one day. I’ve removed the absolute numbers, but I’ll update this screenshot once I have more data. The behavior funnel is fairly logical. There’s around 20 % drop-off on each step, with a larger abandonment leading up to purchase. 15 % of people never open an article, which is interesting! This could also be a measurement error thanks to my DOM scraping, but it’s still understandable considering the amount of traffic I get on my blog.
Also, 25 % of the people who start scrolling never reach one third of the article. This is also interesting. It means that there’s something in the first paragraphs that drives the reader away.
This data should next be segmented and carefully analysed. How can I optimise the funnel further? Two immediate concerns I have is the overall low conversion rate (only 25 % of my readers end up reading an entire article while spending more than 60 seconds on the article page), and the fact that only 40 % of people who start reading end up reading the article thoroughly. This is, of course, a sign of normalcy in the blogosphere, but it’s definitely something I want to improve.
Now this is interesting! Half of my readers start in the checkout funnel, and only half of these reach the end and read for more than 60 seconds. Talk about selective reading! My content is pretty lengthy by average, so it’s interesting to see if article length is a factor here. Or maybe some people just jump straight to the comments, which is perfectly understandable. Actually, I should track this as well! Mental note.
So there’s a big disconnect between starting to read and reaching the end of content. I might have to do something about this. Like, writing more interesting articles. But it’s still respectable how many people actually take their time to read the article.
Naturally, one problem with this Checkout Funnel report is that the checkout funnel varies from article to article. Longer articles have a far higher threshold for hitting the funnel steps (since the steps are dependent on the pixel height of the content DIV), which means I should see a far higher rate for checkouts on shorter articles.
Next, we have the Product Performance report:
Oh, this is so much fun. During the week, almost six million words have been “Purchased” on my articles! This means that six million words worth of article content passed through the checkout funnel into the Purchase column. Awesome!
[UPDATE: I’m still waiting to get more data before updating this chapter with Buy-to-Detail and Cart-to-Detail rate analyses.]
If you look at Average Price, you can see that the list is topped by some of my longer articles. It’s still heart-warming to see some shorter ones on the top 10 list, delivering me “word revenue”.
Sales Performance isn’t very useful, since transactions are pretty arbitrary on my blog. I’ll jump straight to Product List Performance (sorry about the poor screenshot):
Key takeways from this report are that my sidebar widgets aren’t really useful. I should probably get rid of them as soon as I can think of something value-adding to put there instead. Well, the “Recent posts” list has a pretty high number of clicks, so I might preserve that.
[UPDATE: I’m still waiting to get more data before updating this chapter with Product Adds To Cart analysis.]
My top-performing list is naturally the home page listing. It has a very respectable CTR of 16.47 %. “Category posts” and “Tag posts” are much less popular, but even they attract clicks quite a bit.
“Search results” is doing very well, which is important. I want people to find what they were searching for. Naturally, I follow my most searched-for terms like a hawk, getting content ideas at the same time.
Since I have all this amazing data at my fingertips, I can create a bunch of awesome segments as well:
- Whales: Revenue per user > 10000 – To track readers who’ve “purchased” more than 10,000 words in their lifespan.
- Passers-by: Transactions per user = 1 – To track readers who’ve only “purchased” a single article in their lifespan.
- Skimmers: Transactions per user = 0 AND Event Action exactly matches Checkout – To track readers who’ve started the checkout flow but never completed a “purchase”.
- Loyal readers: (Include Users) Revenue per hit > 3000 – To track readers who only read my longer articles.
And many other segments as well! Now I can segment my channels to see which channels bring the most valuable readers. Note that I don’t automatically consider it more valuable to have a reader read my longer articles, which is where the whole “words as price” idea falls down. I enjoy writing short articles as well, and especially my #GTMTips posts are usually a bit shorter length-wise.
Summary
I hope this post has been inspiring. The data I’m getting into my reports is so interesting and actionable. It does require tweaking, however, so I might need to work with the checkout funnel, in order to optimise the flow of reading from article load to the end of content.
With the help of one of my blog commenters, I’ve updated the setup to include Product Detail impressions and Add to Cart actions, but it will still take a week or so to get more data, so you can expect another update to this article soon.
Let me know if you’ve tried something like this or if you have other ideas for tracking content with Enhanced Ecommerce! I’m sorry I can’t really give you a step-to-step guide at this point, but as I’ve done this with DOM scraping, I don’t really want to flaunt the solution, since I don’t consider it best practices. But they key thing in this article is to inspire you to think of your content in terms of funnels and transactions. I really love the new Enhanced Ecommerce reports, and I hope I’ve shown you how flexible they are for other uses as well than just web stores. | https://www.simoahava.com/analytics/track-content-enhanced-ecommerce/ | CC-MAIN-2017-30 | refinedweb | 2,627 | 70.23 |
Introduction
Most of us would have heard about the new buzz in the market i.e. Cryptocurrency. Many of us would have invested in their coins too. But, is investing money in such a volatile currency safe? How can we make sure that investing in these coins now would surely generate a healthy profit in the future? We can’t be sure but we can surely generate an approximate value based on the previous prices. Time series models is one way to predict them.
Source: Bitcoin
Besides Crypto Currencies, there are multiple important areas where time series forecasting is used for example : forecasting Sales, Call Volume in a Call Center, Solar activity, Ocean tides, Stock market behaviour, and many others .
Assume the Manager of a hotel wants to predict how many visitors should he expect next year to accordingly adjust the hotel’s inventories and make a reasonable guess of the hotel’s revenue. Based on the data of the previous years/months/days, (S)he can use time series forecasting and get an approximate value of the visitors. Forecasted value of visitors will help the hotel to manage the resources and plan things accordingly.
In this article, we will learn about multiple forecasting techniques and compare them by implementing on a dataset. We will go through different techniques and see how to use these methods to improve score.
Let’s get started!
Table of Contents
- Understanding the Problem Statement and Dataset
- Installing library (statsmodels)
- Method 1 – Start with a Naive Approach
- Method 2 – Simple average
- Method 3 – Moving average
- Method 4 – Single Exponential smoothing
- Method 5 – Holt’s linear trend method
- Method 6 – Holt’s Winter seasonal method
- Method 7 – ARIMA
Understanding the Problem Statement and Dataset
We are provided with a Time Series problem involving prediction of number of commuters of JetRail, a new high speed rail service by Unicorn Investors. We are provided with 2 years of data(Aug 2012-Sept 2014) and using this data we have to forecast the number of commuters for next 7 months.
Let’s start working on the dataset downloaded from the above link. In this article, I’m working with train dataset only.
import pandas as pd import numpy as np import matplotlib.pyplot as plt #Importing data df = pd.read_csv('train.csv') #Printing head df.head()
#Printing tail df.tail()#Printing tail df.tail()
As seen from the print statements above, we are given 2 years of data(2012-2014) at hourly level with the number of commuters travelling and we need to estimate the number of commuters for future.
In this article, I’m subsetting and aggregating dataset at daily basis to explain the different methods.
- Subsetting the dataset from (August 2012 – Dec 2013)
- Creating train and test file for modeling. The first 14 months (August 2012 – October 2013) are used as training data and next 2 months (Nov 2013 – Dec 2013) as testing data.
- Aggregating the dataset at daily basis
#Subsetting the dataset #Index 11856 marks the end of year 2013 df = pd.read_csv('train.csv', nrows = 11856) #Creating train and test set #Index 10392 marks the end of October 2013 train=df[0:10392] test=df[10392:] #Aggregating the dataset at daily level df.Timestamp = pd.to_datetime(df.Datetime,format='%d-%m-%Y %H:%M') df.index = df.Timestamp df = df.resample('D').mean() train.Timestamp = pd.to_datetime(train.Datetime,format='%d-%m-%Y %H:%M') train.index = train.Timestamp train = train.resample('D').mean() test.Timestamp = pd.to_datetime(test.Datetime,format='%d-%m-%Y %H:%M') test.index = test.Timestamp test = test.resample('D').mean()
Let’s visualize the data (train and test together) to know how it varies over a time period.
#Plotting data train.Count.plot(figsize=(15,8), title= 'Daily Ridership', fontsize=14) test.Count.plot(figsize=(15,8), title= 'Daily Ridership', fontsize=14) plt.show()
Installing library(statsmodels)
The library which I have used to perform Time series forecasting is statsmodels. You need to install it before applying few of the given approaches. statsmodels might already be installed in your python environment but it doesn’t support forecasting methods. We will clone it from their repository and install using the source code. Follow these steps :-
- Use pip freeze to check if it’s already installed in your environment.
- If already present, remove it using “conda remove statsmodels”
- Clone the statsmodels repository using “git clone git://github.com/statsmodels/statsmodels.git”. Initialise the Git using “git init” before cloning.
- Change the directory to statsmodels using “cd statsmodels”
- Build the setup file using “python setup.py build”
- Install it using “python setup.py install”
- Exit the bash/terminal
- Restart the bash/terminal in your environment, open python and execute “from statsmodels.tsa.api import ExponentialSmoothing” to verify.
Method 1: Start with a Naive Approach
Consider the graph given below. Let’s assume that the y-axis depicts the price of a coin and x-axis depicts the time (days).
We can infer from the graph that the price of the coin is stable from the start. Many a times we are provided with a dataset, which is stable throughout it’s time period. If we want to forecast the price for the next day, we can simply take the last day value and estimate the same value for the next day. Such forecasting technique which assumes that the next expected point is equal to the last observed point is called Naive Method.
Now we will implement the Naive method to forecast the prices for test data.
dd= np.asarray(train.Count) y_hat = test.copy() y_hat['naive'] = dd[len(dd)-1] plt.figure(figsize=(12,8)) plt.plot(train.index, train['Count'], label='Train') plt.plot(test.index,test['Count'], label='Test') plt.plot(y_hat.index,y_hat['naive'], label='Naive Forecast') plt.legend(loc='best') plt.title("Naive Forecast") plt.show()
We will now calculate RMSE to check to accuracy of our model on test data set.
from sklearn.metrics import mean_squared_error from math import sqrt rms = sqrt(mean_squared_error(test.Count, y_hat.naive)) print(rms) RMSE = 43.9164061439
We can infer from the RMSE value and the graph above, that Naive method isn’t suited for datasets with high variability. It is best suited for stable datasets. We can still improve our score by adopting different techniques. Now we will look at another technique and try to improve our score.
Method 2: – Simple Average
Consider the graph given below. Let’s assume that the y-axis depicts the price of a coin and x-axis depicts the time(days).
We can infer from the graph that the price of the coin is increasing and decreasing randomly by a small margin, such that the average remains constant. Many a times we are provided with a dataset, which though varies by a small margin throughout it’s time period, but the average at each time period remains constant. In such a case we can forecast the price of the next day somewhere similar to the average of all the past days.
Such forecasting technique which forecasts the expected value equal to the average of all previously observed points is called Simple Average technique.
We take all the values previously known, calculate the average and take it as the next value. Of course it won’t be it exact, but somewhat close. As a forecasting method, there are actually situations where this technique works the best.
y_hat_avg = test.copy() y_hat_avg['avg_forecast'] = train['Count'].mean() plt.figure(figsize=(12,8)) plt.plot(train['Count'], label='Train') plt.plot(test['Count'], label='Test') plt.plot(y_hat_avg['avg_forecast'], label='Average Forecast') plt.legend(loc='best') plt.show()
We will now calculate RMSE to check to accuracy of our model.
rms = sqrt(mean_squared_error(test.Count, y_hat_avg.avg_forecast)) print(rms) RMSE = 109.545990803
We can see that this model didn’t improve our score. Hence we can infer from the score that this method works best when the average at each time period remains constant. Though the score of Naive method is better than Average method, but this does not mean that the Naive method is better than Average method on all datasets. We should move step by step to each model and confirm whether it improves our model or not.
Method 3 – Moving Average
Consider the graph given below. Let’s assume that the y-axis depicts the price of a coin and x-axis depicts the time(days).
We can infer from the graph that the prices of the coin increased some time periods ago by a big margin but now they are stable. Many a times we are provided with a dataset, in which the prices/sales of the object increased/decreased sharply some time periods ago. In order to use the previous Average method, we have to use the mean of all the previous data, but using all the previous data doesn’t sound right.
Using the prices of the initial period would highly affect the forecast for the next period. Therefore as an improvement over simple average, we will take the average of the prices for last few time periods only. Obviously the thinking here is that only the recent values matter. Such forecasting technique which uses window of time period for calculating the average is called Moving Average technique. Calculation of the moving average involves what is sometimes called a “sliding window” of size n.
Using a simple moving average model, we forecast the next value(s) in a time series based on the average of a fixed finite number ‘p’ of the previous values. Thus, for all i > p
A moving average can actually be quite effective, especially if you pick the right p for the series.
y_hat_avg = test.copy() y_hat_avg['moving_avg_forecast'] = train['Count'].rolling(60).mean().iloc[-1] plt.figure(figsize=(16,8)) plt.plot(train['Count'], label='Train') plt.plot(test['Count'], label='Test') plt.plot(y_hat_avg['moving_avg_forecast'], label='Moving Average Forecast') plt.legend(loc='best') plt.show()
We chose the data of last 2 months only. We will now calculate RMSE to check to accuracy of our model.
rms = sqrt(mean_squared_error(test.Count, y_hat_avg.moving_avg_forecast)) print(rms)
RMSE = 46.7284072511
We can see that Naive method outperforms both Average method and Moving Average method for this dataset. Now we will look at Simple Exponential Smoothing method and see how it performs.
An advancement over Moving average method is Weighted moving average method. In the Moving average method as seen above, we equally weigh the past ‘n’ observations. But we might encounter situations where each of the observation from the past ‘n’ impacts the forecast in a different way. Such a technique which weighs the past observations differently is called Weighted Moving Average technique.
A weighted moving average is a moving average where within the sliding window values are given different weights, typically so that more recent points matter more. Ins
tead of selecting a window size, it requires a list of weights (which should add up to 1). For example if we pick [0.40, 0.25, 0.20, 0.15] as weights, we would be giving 40%, 25%, 20% and 15% to the last 4 points respectively.
Method 4 – Simple Exponential Smoothing
After we have understood the above methods, we can note that both Simple average and Weighted moving average lie on completely opposite ends. We would need something between these two extremes approaches which takes into account all the data while weighing the data points differently. For example it may be sensible to attach larger weights to more recent observations than to observations from the distant past. The technique which works on this principle is called Simple exponential smoothing. Forecasts are calculated using weighted averages where the weights decrease exponentially as observations come from further in the past, the smallest weights are associated with the oldest observations:
where 0≤ α ≤1 is the smoothing parameter.
The one-step-ahead forecast for time T+1 is a weighted average of all the observations in the series y1,…,yT. The rate at which the weights decrease is controlled by the parameter α.
If you stare at it just long enough, you will see that the expected value ŷx is the sum of two products: α⋅yt and (1−α)⋅ŷ t-1.
Hence, it can also be written as :
So essentially we’ve got a weighted moving average with two weights: α and 1−α.
As we can see, 1−α is multiplied by the previous expected value ŷ x−1 which makes the expression recursive. And this is why this method is called Exponential. The forecast at time t+1 is equal to a weighted average between the most recent observation yt and the most recent forecast ŷ t|t−1.
from statsmodels.tsa.api import ExponentialSmoothing, SimpleExpSmoothing, Holt y_hat_avg = test.copy() fit2 = SimpleExpSmoothing(np.asarray(train['Count'])).fit(smoothing_level=0.6,optimized=False) y_hat_avg['SES'] = fit2.forecast(len(test)) plt.figure(figsize=(16,8)) plt.plot(train['Count'], label='Train') plt.plot(test['Count'], label='Test') plt.plot(y_hat_avg['SES'], label='SES') plt.legend(loc='best') plt.show()
We will now calculate RMSE to check to accuracy of our model.
rms = sqrt(mean_squared_error(test.Count, y_hat_avg.SES)) print(rms) RMSE = 43.3576252252
We can see that implementing Simple exponential model with alpha as 0.6 generates a better model till now. We can tune the parameter using the validation set to generate even a better Simple exponential model.
Method 5 – Holt’s Linear Trend method
We have now learnt several methods to forecast but we can see that these models don’t work well on data with high variations. Consider that the price of the bitcoin is increasing.
If we use any of the above methods, it won’t take into account this trend. Trend is the general pattern of prices that we observe over a period of time. In this case we can see that there is an increasing trend.
Although each one of these methods can be applied to the trend as well. E.g. the Naive method would assume that trend between last two points is going to stay the same, or we could average all slopes between all points to get an average trend, use a moving trend average or apply exponential smoothing.
But we need a method that can map the trend accurately without any assumptions. Such a method that takes into account the trend of the dataset is called Holt’s Linear Trend method.
Each Time series dataset can be decomposed into it’s componenets which are Trend, Seasonality and Residual. Any dataset that follows a trend can use Holt’s linear trend method for forecasting.
import statsmodels.api as sm sm.tsa.seasonal_decompose(train.Count).plot() result = sm.tsa.stattools.adfuller(train.Count) plt.show()
We can see from the graphs obtained that this dataset follows an increasing trend. Hence we can use Holt’s linear trend to forecast the future prices.
Holt extended simple exponential smoothing to allow forecasting of data with a trend. It is nothing more than exponential smoothing applied to both level(the average value in the series) and trend. To express this in mathematical notation we now need three equations: one for level, one for the trend and one to combine the level and trend to get the expected forecast ŷ
The values we predicted in the above algorithms are called Level. In the above three equations, you can notice that we have added level and trend to generate the forecast equation.
As with simple exponential smoothing, the level equation here shows that it is a weighted average of observation and the within-sample one-step-ahead forecast The trend equation shows that it is a weighted average of the estimated trend at time t based on ℓ(t)−ℓ(t−1) and b(t−1), the previous estimate of the trend.
We will add these equations to generate Forecast equation. We can also generate a multiplicative forecast equation by multiplying trend and level instead of adding it. When the trend increases or decreases linearly, additive equation is used whereas when the trend increases of decreases exponentially, multiplicative equation is used.Practice shows that multiplicative is a more stable predictor, the additive method however is simpler to understand.
y_hat_avg = test.copy() fit1 = Holt(np.asarray(train['Count'])).fit(smoothing_level = 0.3,smoothing_slope = 0.1) y_hat_avg['Holt_linear'] = fit1.forecast(len(test)) plt.figure(figsize=(16,8)) plt.plot(train['Count'], label='Train') plt.plot(test['Count'], label='Test') plt.plot(y_hat_avg['Holt_linear'], label='Holt_linear') plt.legend(loc='best') plt.show()
We will now calculate RMSE to check to accuracy of our model.
rms = sqrt(mean_squared_error(test.Count, y_hat_avg.Holt_linear)) print(rms)
RMSE = 43.0562596115
We can see that this method maps the trend accurately and hence provides a better solution when compared with above models. We can still tune the parameters to get even a better model.
Method 6 – Holt-Winters Method
So let’s introduce a new term which will be used in this algorithm. Consider a hotel located on a hill station. It experiences high visits during the summer season whereas the visitors during the rest of the year are comparatively very less. Hence the profit earned by the owner will be far better in summer season than in any other season. This pattern will repeat itself every year. Such a repetition is called Seasonality. Datasets which show a similar set of pattern after fixed intervals of a time period suffer from seasonality.
The above mentioned models don’t take into account the seasonality of the dataset while forecasting. Hence we need a method that takes into account both trend and seasonality to forecast future prices. One such algorithm that we can use in such a scenario is Holt’s Winter method. The idea behind triple exponential smoothing(Holt’s Winter) is to apply exponential smoothing to the seasonal components in addition to level and trend.
Using Holt’s winter method will be the best option among the rest of the models beacuse of the seasonality factor. The Holt-Winters seasonal method comprises the forecast equation and three smoothing equations — one for the level ℓt, one for trend bt and one for the seasonal component denoted by st, with smoothing parameters α, β and γ.
where s is the length of the seasonal cycle, for 0 ≤ α ≤ 1, 0 ≤ β ≤ 1 and 0 ≤ γ ≤ 1.
The level equation shows a weighted average between the seasonally adjusted observation and the non-seasonal forecast for time t. The trend equation is identical to Holt’s linear method. The seasonal equation shows a weighted average between the current seasonal index, and the seasonal index of the same season last year (i.e., s time periods ago).
In this method also, we can implement both additive and multiplicative technique. The additive method is preferred when the seasonal variations are roughly constant through the series, while the multiplicative method is preferred when the seasonal variations are changing proportional to the level of the series.
y_hat_avg = test.copy() fit1 = ExponentialSmoothing(np.asarray(train['Count']) ,seasonal_periods=7 ,trend='add', seasonal='add',).fit() y_hat_avg['Holt_Winter'] = fit1.forecast(len(test)) plt.figure(figsize=(16,8)) plt.plot( train['Count'], label='Train') plt.plot(test['Count'], label='Test') plt.plot(y_hat_avg['Holt_Winter'], label='Holt_Winter') plt.legend(loc='best') plt.show()
We will now calculate RMSE to check to accuracy of our model.
rms = sqrt(mean_squared_error(test.Count, y_hat_avg.Holt_Winter)) print(rms) RMSE = 23.9614925662
We can see from the graph that mapping correct trend and seasonality provides a far better solution. We chose seasonal_period = 7 as data repeats itself weekly. Other parameters can be tuned as per the dataset. I have used default parameters while building this model. You can tune the parameters to achieve a better model.
Method 7 – ARIMA
Another common Time series model that is very popular among the Data scientists is ARIMA. It stand for Autoregressive Integrated Moving average. While exponential smoothing models were based on a description of trend and seasonality in the data, ARIMA models aim to describe the correlations in the data with each other. An improvement over ARIMA is Seasonal ARIMA. It takes into account the seasonality of dataset just like Holt’ Winter method. You can study more about ARIMA and Seasonal ARIMA models and it’s pre-processing from these articles (1) and (2).
y_hat_avg = test.copy() fit1 = sm.tsa.statespace.SARIMAX(train.Count, order=(2, 1, 4),seasonal_order=(0,1,1,7)).fit() y_hat_avg['SARIMA'] = fit1.predict(start="2013-11-1", end="2013-12-31", dynamic=True) plt.figure(figsize=(16,8)) plt.plot( train['Count'], label='Train') plt.plot(test['Count'], label='Test') plt.plot(y_hat_avg['SARIMA'], label='SARIMA') plt.legend(loc='best') plt.show()
We will now calculate RMSE to check to accuracy of our model.
rms = sqrt(mean_squared_error(test.Count, y_hat_avg.SARIMA)) print(rms) RMSE = 26.035582877
We can see that using Seasonal ARIMA generates a similar solution as of Holt’s Winter. We chose the parameters as per the ACF and PACF graphs. You can learn more about them from the links provided above. If you face any difficulty finding the parameters of ARIMA model, you can use auto.arima implemented in R language. A substitute of auto.arima in Python can be viewed here.
We can compare these models on the basis of their RMSE scores.
End Notes.
One lesson to learn from these steps is that each of these models can outperform others on a particular dataset. Therefore it doesn’t mean that one model which performs best on one type of dataset will perform the same for all others too.
You can also explore forecast package built for Time series modelling in R language. You may also explore Double seasonality models from forecast package. Using double seasonality model on this dataset will generate even a better model and hence a better score.
Did you find this article helpful? Please share your opinions / thoughts in the comments section below.
47 Comments | https://www.analyticsvidhya.com/blog/2018/02/time-series-forecasting-methods/?replytocom=151255 | CC-MAIN-2018-22 | refinedweb | 3,680 | 57.67 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.