DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Latest Articles - DZone

article thumbnail
Freight Management System on NetBeans
Lynden is a family of transportation and logistics companies specialized in shipping to Alaska and other locations worldwide. Over land, on the water, in the air - or in any combination - Lynden has been helping customers solve transportation problems for over a century. The Lynden Freight Management System is a NetBeans Platform application which serves a dual purpose as both a planning and freight tracking tool. The Planning module allows terminal managers to see all freight that is currently inbound to their location as well as freight that is scheduled to depart from their location so they can make the most efficient use of their dock space and resources as possible. The Trace module allows customer service personnel to search for customer account information, view the tracking history of any given freight item in the system as well as display any documents related to the shipment, such as bills of lading or delivery receipts. NetBeans Platform Lynden has benefited from the NetBeans Platform as it allows developers to focus on the business logic of our applications rather than the underlying "plumbing". We are able to leverage built-in support for event handling, enable/disable functionality on UI controls, dockable windows, and automatic updates for our application with minimal work compared to rolling our own framework. We chose to go the desktop application route as we have a number of existing desktop applications here that this application will likely need to interface with at some point, as well as a commercial set of rich UI components that we have been using for some time now. For the initial deployment, we will be pushing the installer out to employee PCs via the Landesk remote desktop administration tool. Future updates to various modules within the application will be done via the update center functionality built into the NetBeans Platform. Screenshots
November 19, 2011
by Rob Terpilowski
· 11,877 Views · 3 Likes
article thumbnail
Another approach to mocking properties in Python
mock is a library for testing in python. it allows you to replace parts of your system under test with mock objects. the main feature of mock is that it's simple to use, but mock also makes possible more complex mocking scenarios. this is my philosophy of api design as it happens: simple things should be simple but complex things should be possible . several of these more complex scenarios are shown in the further examples section of the documentation. i've just updated one of these, the example of mocking properties. properties in python are descriptors . when they are fetched from the class of an object they trigger code that is then executed. the code that is executed is the method that you have wrapped as the property getter. note that there is a special rule for attribute lookup on certain types of descriptors, which include properties. even if an instance attribute exists, the class attribute will still be used instead. this is an exception to the normal attribute lookup rule that instance attributes are fetched in preference to class attributes. this is important because it means that when you want to mock a property you have to do it on the class and can't simply stick an attribute onto an object. if you're using mock 0.7, with its support for magic methods , we can patch the property name and add a __get__ method to our mock. the presence of the __get__ method makes it a descriptor, so we can use it as a property: >>> from mock import mock, patch >>> class foo(object): ... @property ... def fish(self): ... return 'fish' ... >>> with patch.object(foo, 'fish') as mock_fish: ... mock_fish.__get__ = mock(return_value='mocked fish') ... foo = foo() ... print foo.fish ... mocked fish >>> mock_fish.__get__.assert_called_with(mock_fish, foo, foo) in this example mock_fish replaces the property and the mock we put in place of __get__ becomes the mocked getter method. as we're patching on the class this affects all instances of foo . there's no point in using magicmock for this. magicmock normallly makes using the python protocol methods simpler by preconfiguring them. as you can see from the example above, mocking __get__ is supported but it isn't hooked up by default. it wouldn't be helpful if mocking any method on a class replaced it with a mock that acted as a descriptor, so if you want a mock to behave as a descriptor then you have to configure __get__ , __set__ and __delete__ yourself. here's an alternative approach that works with all recent-ish versions of mock: >>> from mock import mock, patch >>> class propertymock(mock): ... def __get__(self, instance, owner): ... return self() ... >>> prop_mock = propertymock() >>> with patch.object(foo, 'fish', prop_mock): ... foo = foo() ... prop_mock.return_value = 'mocked fish' ... print foo.fish ... mocked fish >>> prop_mock.assert_called_with() as an added bonus, both of these examples work even if the foo instance is created outside of the patch block. so long as the code using the property is executed whilst the patch is in place the attribute lookup will find our mocked version. source: http://www.voidspace.org.uk/python/weblog/arch_d7_2011_06_04.shtml
November 18, 2011
by Michael Foord
· 28,733 Views
article thumbnail
Tackling the Circular Dependency in Java...
Let me first define what we mean by circular dependency in OOAD terms vis-a-vis Java. Suppose we have a class called A which has class B’s Object. (in UML terms A HAS B). at the same time we class B is also composed of Object of class A (in UML terms B HAS A). obviously this represents circular dependency because while creating the object of A, the compiler must know the size of B... on the other hand while creating object of B, the compiler must know the size of A. this is something like egg vs. chicken problem... this may be possible in real life situation as well. for example suppose a multi storied building has a lift. so in the UML terms, the building HAS lift... but at the same time, suppose, while constructing the lift object, we need to give it the information about the building object to access various functionalities of the Building class... for example, suppose the speed of the lift is set depending on the number of floors of the Building... hence while constructing the Lift object it must access the functionalities of the Building object which will give the number of floors the building has got...hence in UML terms the lift HAS building... so this is a sure case of circular dependency... in real java code it will look something as follows: public class Building { private Lift lift; private int floor; public Building(){ lift = new Lift(); setFloor(15); } public int getFloor(){ return floor; } public void setFloor(int floor){ this.floor = floor; } }//end of class building //class Lift public class Lift { private Building building; private int Speed; public Lift(){ building = new Building(); setSpeed(); } public void setSpeed(){ if (building.getFloor()>20){ //one set of functionalities //may be the the speed of the lift will be more this.Speed = 10; } else { //different set of functionalities //may be the speed of the lift will be less this.Speed = 5; } } public int getSpeed(){ return Speed; } }//end of class Lift As it becomes clear from the above code, that while creating the Building object it will create the Lift object, and while creating the Lift object, it will try to create a Building object to access some of its functionalities... So, ultimately it will go out of memory and we get a StackOverflow runtime exception... So how do we handle this problem in Java? We actually tackle this problem by declaring an IBuildingProxy interface and by deriving our Building class from that... the lift class, instead of Having Building object, it Has IBuildingProxy... the source code of the solution looks like the following... public interface IBuildingProxy { int getFloor(); void setFloor(int floor); } public class Building implements IBuildingProxy{ private Lift lift; private int floor; public Building(){ lift = new Lift(this); setFloor(15); } public int getFloor(){ return floor; } public void setFloor(int floor){ this.floor = floor; } } public class Lift { private IBuildingProxy building; private int Speed; public Lift(Building b){ this.building = b; setSpeed(); } private void setSpeed(){ if (building.getFloor()>20){ / /one set of functionalities //may be the the speed of the lift will be more this.Speed = 10; } else { //different set of functionalities //may be the speed of the lift will be less this.Speed = 5; } } public int getSpeed(){ return Speed; } } public class CircularDependencyTest { public static void main(String[] args){ Building b = new Building(); Lift l = new Lift(b); } } So whats the principle behind such work around... It will be clear soon... As it becomes clear from the code that Building HAS Lift... That is not a problem... Now when it comes to solve the part that Lift HAS Building, instead of the Building object, we have created an IBuildingProxy interface and we pass it to the Lift class... what it essentially means, that the building class knows the memory requirement to initialize the Lift object, and as the Lift class HAS just a proxy interface of the Building, it does not have to care for the Building's memory requirement... and that solves the problem... Hope this discussion becomes helpful for Java learners...
November 17, 2011
by Somenath Mukhopadhyay
· 32,603 Views · 2 Likes
article thumbnail
Use the WinDbg Engine in Visual Studio User-Mode Debugging
in our c++ debugging course , there are several scenarios which require windbg and cannot be completed in visual studio. they all rely on advanced extension commands available in windbg. some examples: tracing opened and closed handles with the !htrace command viewing native heap information with the !heap command loading and executing code in the debuggee process with the sdbgext extension commands !loaddll , !remotecall inspecting handles to synchronization objects with the !handle command the sheer power of windbg built-in commands and extensions makes it a viable replacement to visual studio when doing hard-core debugging. however, the user interface – the tool windows, the source editor, setting up breakpoints, stepping through source, inspecting variables – are no match to the rich visual studio environment. the good news is that as of visual studio 11, we’ll be able to use the windbg debugging engine (“windows debugger”) inside visual studio, combining the powerful commands with the convenient interface. just use the “windows user mode debugger” transport in the tools | attach to process dialog. this also applies to dumps – you can open dumps with the visual studio “minidump summary” dialog, or you can use the file | open crash dump menu item, the same way as for kernel dumps. (click the screenshot to enlarge) that’s really all there’s to it – after attaching, you have the windbg shell inside visual studio, in the debugger immediate window which we’ve already seen. the call stack, threads, locals debugger windows are fully functional, and you can combine visual analysis of the source code with running advanced extension commands in the shell. for example, here’s a thread that is waiting for a mutex: (click the screenshot to enlarge) which thread owns this mutex? the !handle command comes in handy: (click the screenshot to enlarge) …and we’ve got the owner information. visual studio 11 is going to change the way we’re doing crash analysis and live debugging of advanced scenarios. i bet plenty of my past and future students are going to be very happy about being able to use visual studio instead of learning the ropes of another tool, which has quite the reputation for being user-unfriendly :-) if you’re doing any .net debugging, you’re probably wondering if this means better integration for sos in visual studio. unfortunately, right now the answer is no. with some effort – going through the visual studio tools | attach to process dialog – you can attach the windbg engine to a .net process. however, the engine does not recognize .net any better than standalone windbg, so you don’t have managed call stacks, local variables, and source code support within the ide. but if all you wanted is to run a couple of sos commands without leaving vs, you certainly can. another caveat is that currently you need to install the wdk on top of visual studio 11 to get the debugger integration. i’m guessing – or rather, hoping – that in the release version it will suffice to install debugging tools for windows. i have been recently posting short updates and links on twitter as well as on this blog. you can follow me: @goldshtn
November 15, 2011
by Sasha Goldshtein
· 12,160 Views
article thumbnail
How You Clear Your HTML5 Canvas Matters
The performance difference between two above methods for clearing an HTML5 canvas can be measured in orders of magnitude or more.
November 15, 2011
by Simon Sarris
· 39,919 Views · 3 Likes
article thumbnail
A Really Simple But Powerful Rule Engine
I have the requirement to use a rule engine. I want something light weight and fairly simple, yet powerful. While there are products out there which are super good, I don't want something with the big learning overhead. And, I fancied writing my own! Here are my few basic requirements: Use some kind of expression language to write the rules, It should be possible to store rules in a database, Rules need a priority, so that only the best can be fired, It should also be possible to fire all matching rules, Rules should evaluate against one input which can be an object like a tree, containing all the information which rules need to evaluate against Predefined actions which are programmed in the system should be executed when certains rules fire. So to help clarify those requirements, imagine the following examples: 1) In some forum system, the administrator needs to be able to configure when emails are sent. Here, I would write some rules like "when the config flag called sendUserEmail is set to true, send an email to the user" and "when the config flag called sendAdministratorEmail is true and the user has posted less than 5 postings, send an email to the administrator". 2) A tarif system needs to be configurable, so that the best tarif can be offered to customers. For that, I could write rules like these: "when the person is younger than 26 the Youth tarif is applicable", "when the person is older than 59, the Senior tarif is applicable", and "when the person is neither a youth, nor a senior, then they should be given the Default tarif, unless they have had an account for more than 24 months, in which case they should be offered the Loyalty tarif". 3) A train ticket can be considered to be a product. Depending upon the travel request, different products are suitable. A rule here, could be something like: "if the travel distance is more than 100km and first class is desired, then product A is to be sold." Finally, a more complex example, involving some iteration of the input, rather than just property evaluation: 4) Timetable software needs to deterimine when students can leave school. A rule for that might read: "If a class contains any student under age 10, the entire class gets to leave early. Otherwise, they leave at the normal time." So, with those requirements in mind, I went to look for an expression language. I started with the unified expression language specified in JSP 2.1. Using the jasper jar used in Tomcat and Apache Commons EL jar, I got something up and running very quickly. Then I discovered the MVEL library from Codehaus.org, which incidentally is used in Drools (the leading Java rule engine?) and it worked even better. It offers far more functionality as far as I can tell. So, I designed my rule engine to work like this: 1) An engine is configured with some rules. 2) A rule has these attributes: - namespace: an engine may contain many rules, but only some may be relevant to a particular call and this namespace can be used for filtering - name: a unique name within a namespace - expression: an MVEL expression for the rule - outcome: a string which the engine might use if this rules expression evaluates to true - priority: an integer. The bigger the value, the higher the priority. - description: a useful description to aid the management of rules. 3) The engine is given an input object and evaluates all rules (optionally within a namespace) and either: a) returns all rules which evaluate to true, b) returns the outcome (string) from the rule with the highest priority, out of all rules evaluating to true, c) execute an action (defined within the application) which is associated with the outcome of the rule with the highest priority, out of all rules evaluating to true. 4) "Action"s are instances of classes which the application programmer can supply. An action is given a name. When the engine is asked to execute an action based on the rules, the name of the action matching the "winning" rule's outcome is executed. 5) A rule can be built up of "sub-rules". A subrule is only ever used as a building block on which to base more complex rules. When evaluating rules, the engine will never select a subrule to be the best (highest priority) "winning" rule, i.e. one evaluating to true. Subrules make it easier to build complex rules, as I shall show shortly. So, time for some code! First, let's look at the code for the tarif system: Rule r1 = new Rule("YouthTarif", "input.person.age < 26", "YT2011", 3, "ch.maxant.someapp.tarifs", null); Rule r2 = new Rule("SeniorTarif", "input.person.age > 59", "ST2011", 3, "ch.maxant.someapp.tarifs", null); Rule r3 = new Rule("DefaultTarif", "!#YouthTarif && !#SeniorTarif", "DT2011", 3, "ch.maxant.someapp.tarifs", null); Rule r4 = new Rule("LoyaltyTarif", "#DefaultTarif && input.account.ageInMonths > 24", "LT2011", 4, "ch.maxant.someapp.tarifs", null); List rules = Arrays.asList(r1, r2, r3, r4); Engine engine = new Engine(rules, true); TarifRequest request = new TarifRequest(); request.setPerson(new Person("p")); request.setAccount(new Account()); request.getPerson().setAge(24); request.getAccount().setAgeInMonths(5);String tarif = engine.getBestOutcome(request); So, in the above code, I have added 4 rules to the engine, and told the engine to throw an exception if any rule cannot be pre-compiled. Then, I created a TarifRequest, which is the input object. That object is passed into the engine, when I ask the engine to give me the best outcome. In this case, the best outcome is the string "YT2011", the name of the most suitable tarif for the customer I added to the tarif request. How does it all work? When the engine is given the rules, it does some validation on them, and pre-compiles the rules (to improve overall performance). Notice how the first two rules refer to an object called "input"? That is the object passed into the "getBestOutcome" method on the engine. The engine passes the input object to the MVEL class together with each rules expression. Anytime an expression evaluates to "true", the rule is put to the side as a candidate to be the winner. At the end, the candidates are sorted in order of priority, and the outcome field of the rule with the highest priority is returned by the engine. Notice how the third and fourth rules contain the '#' character. That is not standard MVEL expression language. The engine examines all rules when they are passed to it, and it replaces any token starting with a hash symbol, with the expression found in the rule named the same as the token. It wraps the expression in brackets. The logger outputs the full rule after reference rules have been resolved and replaced, just in case you want to check the rule. In the above business case, we were only interested in the best tarif for the customer. Equally, we might have been interested in a list of possible tarifs, so that we could offer the customer a choice. In that case, we could have called the "getMatchingRules" method on the engine, which would have returned all rules, sorted by priority. The tarif names are (in this case) the "outcome" field of the rules. In the above example, I wanted to receive any of the four outcomes, from the four rules. Sometimes however, you might want to build complex rules based on building blocks, but you might never want those building blocks to be a winning outcome. The train trip example from above can be used to show what I mean here: Rule rule1 = new SubRule("longdistance", "input.distance > 100", "ch.maxant.produkte", null); Rule rule2 = new SubRule("firstclass", "input.map[\"travelClass\"] == 1", "ch.maxant.produkte", null); Rule rule3 = new Rule("productA", "#longdistance && #firstclass", "productA", 3, "ch.maxant.produkte", null); List rules = Arrays.asList(rule1, rule2, rule3); Engine e = new Engine(rules, true); TravelRequest request = new TravelRequest(150); request.put("travelClass", 1); List rs = e.getMatchingRules(request); In the above code, I build rule3 from two subrules. But I never want the outcomes of those building blocks to be output from the engine. So I create them as SubRules. SubRules don't have an outcome field or priority. They are simply used to build up more complex rules. After the engine has used the sub-rules to replace all tokens beginning in a hash during initialisation, it discards the SubRules - they are not evaluated. The TravelRequest above takes a distance in the constructor, and contains a map of additional parameters. MVEL let's you easily access map values using the syntax shown in rule 2. Next, consider the business case of wanting to configure an forum system. The code below introduces actions. Actions are created by the application programmer and supplied to the engine. The engine takes the outcomes (as described in the first example), and searches for actions with the same names as those outcomes, and calls the "execute" method on those actions (they all implement the IAction interface). This functionality is useful when a system must be capable of predefined things, but the choice of what to do needs to be highly configurable and independent of deployment. Rule r1 = new Rule("SendEmailToUser", "input.config.sendUserEmail == true", "SendEmailToUser", 1, "ch.maxant.someapp.config", null); Rule r2 = new Rule("SendEmailToModerator", "input.config.sendAdministratorEmail == true and input.user.numberOfPostings < 5", "SendEmailToModerator", 2, "ch.maxant.someapp.config", null); List rules = Arrays.asList(r1, r2); final List log = new ArrayList(); Action a1 = new Action("SendEmailToUser") { @Override public Void execute(ForumSetup input) { log.add("Sending email to user!"); return null; } }; Action a2 = new Action("SendEmailToModerator") { @Override public Void execute(ForumSetup input) { log.add("Sending email to moderator!"); return null; } }; Engine engine = new Engine(rules, true); ForumSetup setup = new ForumSetup(); setup.getConfig().setSendUserEmail(true); setup.getConfig().setSendAdministratorEmail(true); setup.getUser().setNumberOfPostings(2); engine.executeAllActions(setup, Arrays.asList(a1, a2)); In the code above, the actions are passed to the engine when we call the "executeAllActions" method. In this case, both actions are executed, because the setup object causes both rules to evaluate to true. Note that the actions are executed in the order of highest priority rule first. Each action is only ever executed once - it's name is noted after execution and it will not be executed again, until the engines "execute*Action*" method is called again. Also, if you only want the action associated with the best outcome to be executed, call the "executeBestAction" method instead of "executeAllActions". Finally, let's consider the classroom example. String expression = "for(student : input.students){" + "if(student.age < 10) return true;" + "}" + "return false;"; Rule r1 = new Rule("containsStudentUnder10", expression , "leaveEarly", 1, "ch.maxant.rules", "If a class contains a student under 10 years of age, then the class may go home early"); Rule r2 = new Rule("default", "true" , "leaveOnTime", 0, "ch.maxant.rules", "this is the default"); Classroom classroom = new Classroom(); classroom.getStudents().add(new Person(12)); classroom.getStudents().add(new Person(10)); classroom.getStudents().add(new Person(8)); Engine e = new Engine(Arrays.asList(r1, r2), true); String outcome = e.getBestOutcome(classroom); The outcome above is "leaveEarly", because the classroom contains one student whose age is less than 10. MVEL let's you write some pretty comprehensive expressions, and is really a programming language in it's own right. The engine simply requires a rule to return true, if the rule is to be considered a candidate for firing. There are more examples in the JUnit tests contained in the source code. So, the requirements are fulfiled, except for "It should be possible to store rules in a database". While this library doesn't support reading and writing rules to / from a database, rules are String based. So it wouldn't be hard to create some JDBC or JPA code which reads rules out of a database and populates Rule objects and passes them to the Engine. I haven't added this to the library, because normally these things as well as the management of rules is something quite project specific. And because my library will never be as cool or popular as Drools, I'm not sure it would be worth my while to add such functionality. I've put the rule engine into an OSGi library with the LGPL licence and it can be downloaded from my tools site. This library depends on MVEL, which can be downloaded here (I used version 2.0.19). If you like it, let me know! From http://blog.maxant.co.uk/pebble/2011/11/12/1321129560000.html
November 15, 2011
by Ant Kutschera
· 145,257 Views · 7 Likes
article thumbnail
PHP: Don’t Call the Destructor Explicitly
“PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++”[1] says the documentation for destructors, but let’s see the following class. class A { public function __construct() { echo 'building an object'; } public function __destruct() { echo 'destroying the object'; } } $obj = new A(); Well, as you can not call the constructor explicitly: $obj->__construct(); So we should not call the destructor explicitly: $obj->__destruct(); The problem is that I’ve seen this many times, but it’s a pity that this won’t destroy the object and it is still a valid PHP code. PHP destructors cannot be called explicitly! Constructors and destructors in PHP are part of the so called magic methods. Here’s what the doc page says about them. The function names __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state() and __clone() are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them. To be more precise let’s take a look of the definition of destructors. PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence. What if I Call the Destructor Explicitly? Let’s see some examples! class A { public function __destruct() { echo 'destroying the object'; } } $obj = new A(); // prints hello world echo 'hello world'; // PHP interpreter stops the script execution and prints // 'destroying the object' This is actually a normal behavior. At the end of the script the interpreter frees the memory. Actually every object has a built-in destructor, just like it has built-in constructor. So even we don’t define it explicitly, the object has its destructor. Usually this destructor is executed at the end of the script, or whenever the object isn’t needed anymore. This can happen, for instance, at the end of a function body. Now if we call the destructor explicitly, which as I said I’ve seen many times, here’s what happens. class A { public function __destruct() { echo 'destroying the object'; } } $obj = new A(); // this is valid and it prints 'destroying the object' // BUT IT DOES NOT DESTROY THE OBJECT $obj->__destruct(); // prints hello world echo 'hello world'; // HERE PHP ACTUALLY DESTROYS THE $obj OBJECT // ... and again prints 'destroying the object' As you can see calling the destructor explicitly doesn’t destroy the object. So the question is … How to Destroy an Object Before the Script Stops? Well, to destroy an object you can assign a NULL value to it. class A { public function __destruct() { echo 'destroying the object'; } } $obj = new A(); // prints 'destroying the object' $obj = null; // prints 'hello world' echo 'hello world'; // the script stop its execution Caution Be aware that if you don’t clone the object $obj, and simply assign it to another variable, then $obj = null will be pointless. Let’s see the following example. class A { public function printMsg() { echo 'I still exist'; } public function __destruct() { echo 'destroying the object'; } } $obj = new A(); // $newObj is pointing to $obj $newObj = $obj; // this doesn't destroy $newObj // as it appears both $obj and $newObj point to the same memory // so PHP doesn't free this memory $obj = null; // prints 'i still exist' $newObj->printMsg(); // prints 'hello world' echo 'hello world'; // now the scripts destroys the "object", which in this // case is $newObj and prints 'destroying the object' This example shows us that actually assigning NULL to an object doesn’t quite destroy it if there are another objects pointing to the same memory. class A { public function printMsg() { echo 'I still exist'; } public function __destruct() { echo 'destroying the object'; } } $b = new A(); $d = $c = $b; $b = null; $c->printMsg(); $d->printMsg(); // prints 'destroying the object' ONLY ONCE In this last example there are two interesting things to note. First $b = null doesn’t call the destructor, and at the end of the script there’s only one implicit call of the destructor, although there are two objects. Conclusion The important thing to note is that you shouldn’t call the destructor of an object explicitly! Not because it will throw an fatal error, but simply because it won’t destroy the object. [1] PHP: Constructors and Destructors Related posts: Some Notes on the Object-oriented Model of PHP Construct a Sorted PHP Linked List Object Cloning and Passing by Reference in PHP Source: http://www.stoimen.com/blog/2011/11/14/php-dont-call-the-destructor-explicitly/
November 15, 2011
by Stoimen Popov
· 18,285 Views · 1 Like
article thumbnail
Sound Synthesis with Numpy
Physically, sound is an oscillation of a mechanical medium that makes the surrounding air also oscillate and transport the sound as a compression wave. Mathematically, the oscillations can be described as where t is the time, and f the frequency of the oscillation. Each musical note vibrates at a particular frequency and to generate a tone we have to generate an oscillation with the appropriate frequency. The following table shows the complete musical scale between middle A and A-880, in the first column we have the tone and in the second the frequency that we have to use to generate the tone: Tone Freq A 440 B flat 466 B 494 C 523 C sharp 554 D 587 D sharp 622 E 659 F 698 F sharp 740 G 784 A flat 831 A 880 Sound on a computer is a sequence of numbers and we are going to see how to generate an array that represents a musical tone with numpy. The following function is able to generate a note using the formula above: from numpy import linspace,sin,pi,int16 # tone synthesis def note(freq, len, amp=1, rate=44100): t = linspace(0,len,len*rate) data = sin(2*pi*freq*t)*amp return data.astype(int16) # two byte integers And we can use this function to generate an A tone of 2 seconds with 44100 samples per second in this way: from scipy.io.wavfile import write from pylab import plot,show,axis # A tone, 2 seconds, 44100 samples per second tone = note(440,2,amp=10000) write('440hzAtone.wav',44100,tone) # writing the sound to a file plot(linspace(0,2,2*44100),tone) axis([0,0.4,15000,-15000]) show() The script put the sound into a wav file and we can play it with an external player. This plot shows a part of the signal generated by the script: Blog Source: http://glowingpython.blogspot.com/2011/09/sound-synthesis.html Article Type: How-to
November 14, 2011
by Giuseppe Vettigli
· 15,571 Views
article thumbnail
What Is CDI, How Does It Relate to @EJB And Spring?
A brief overview of dependency injection in Java EE, the difference between @Resource/@EJB and @Inject, and how does that all relate to Spring – mostly in the form of links. Context Dependency Injection (CDI, JSR 299) is a part of Java EE 6 Web Profile and itself builds on Dependency Injection for Java (JSR 330), which introduces @Inject, @Named etc. While JSR 330 is for DI only and is implemented e.g. by Guice and Spring, CDI adds various EE stuff such as @RequestScoped, interceptors/decorators, producers, eventing and a base for integration with JSF, EJBs etc. Java EE components such as EJBs have been redefined to build on top of CDI (=> @Stateless is now a CDI managed bean with additional services). A key part of CDI aside of its DI capabilities is its awarness of bean contexts and the management of bean lifecycle and dependencies within those contexts (such as @RequestScoped or @ConversationScoped). CDI is extensible – you can define new context scopes, drop-in interceptors and decorators, make other beans (e.g. from Spring) available for CDI,… . Resources to check: Contexts and Dependency Injection in Java EE 6 by Adam Bien – a very good explanation of the basics of CDI and how it differs from DI in Java EE 5 (hint: context awarness) Slideshow with a good overview of CDI and all it offers About CDI extensibility and SPIs (e.g. Seam 3 is basically a set of portable CDI extensions) Guice and Spring do not implement CDI (3/2011) – and Spring perhaps isn’t motivated to do so (it supports JSR 330, CDI would be too much work) DZone CDI Refcard may be handy CDI 1.0 vs. Spring 3.1 feature comparsion: bean definition & dependency injection: “in the area that I compared in this article [= DI], there is only little critical difference in the two technologies” (though Spring more fine-tunable) Java EE 6 (CDI / EJB 3.1) XOR Spring Core Reloaded: New projects should preferably start with pure Java EE including CDI and add Spring utilities such as JDBC/JMS when needed Oracle: CDI in the Java EE 6 Ecosystem – 62 pages slideshow, the stuff is explained more than in the previously mentioned slideshow Note: CDI 1.1 (JSR 346, Java EE 7) should have a standard way of bootstrapping it in non-EE environment (i.e. SE) From http://theholyjava.wordpress.com/2011/11/09/what-is-cdi-how-does-it-relate-to-ejb-and-spring/
November 12, 2011
by Jakub Holý
· 14,938 Views · 1 Like
article thumbnail
Hibernate by Example - Part 2 (DetachedCriteria)
So last time we helped out justice league to effectively manager their super heroes. Today we focus on how The Avengers will be using Hibernate's Detached Criteria to find out their enemies with respect to each superhero so as to protect their super heroes. You can download the working example from here. In this example we take only two entities into consideration. The Avenger & The Villain. We build a relationship between the two using a join table. Let us have a look at the domain mappings used in this example. package com.avengers.domain; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.OneToMany; import javax.persistence.Table; import org.hibernate.annotations.Type; /** * The domain class representing each member of the avengers * * @author Dinuka.Arseculeratne * */ @Entity @Table(name = "Avengers") public class Avenger implements Serializable { /** * The primary key of the Avenger table */ @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "avenger_id") private Long avengerId; /** * The name of the avenger member */ @Column(name = "avenger_name") private String avengerName; /** * A flag which holds whether the avenger's powers are awesome */ @Type(type = "yes_no") @Column(name = "is_awesome") private boolean isAwesome; /** * The list of enemies the avenger has */ @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinTable(name = "AVENGERS_AND_VILLAINS", joinColumns = { @JoinColumn(name = "avenger_id") }, inverseJoinColumns = { @JoinColumn(name = "villain_id") }) private List enemyList = new ArrayList(); public Long getAvengerId() { return avengerId; } public void setAvengerId(Long avengerId) { this.avengerId = avengerId; } public String getAvengerName() { return avengerName; } public void setAvengerName(String avengerName) { this.avengerName = avengerName; } public boolean isAwesome() { return isAwesome; } public void setAwesome(boolean isAwesome) { this.isAwesome = isAwesome; } public List getEnemyList() { return enemyList; } public void addEnemy(Villain enemy) { enemyList.add(enemy); } @Override public String toString() { return "Avenger [avengerId=" + avengerId + ", avengerName=" + avengerName + ", isAwesome=" + isAwesome + ", enemyList=" + enemyList + "]"; } } This class maps an avenger. I have used minimal fields in order to keep this example as simple and short as possible. And the Villain domain looks as follows; package com.avengers.domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.Type; /** * This class represents the Villain forces against the avengers * * @author Dinuka.Arseculeratne * */ @Entity @Table(name = "Villains") public class Villain implements Serializable { /** * The primary key of the Enemy table */ @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "villain_id") private Long villaiId; /** * The name of the enemy */ @Column(name = "villain_name") private String villainName; /** * A flag which checks whether the villain is super awesome */ @Type(type = "yes_no") @Column(name = "is_awesome") private boolean isAwesome; public Long getVillaidId() { return villaiId; } public void setVillaidId(Long villaidId) { this.villaiId = villaidId; } public String getVillainName() { return villainName; } public void setVillainName(String villainName) { this.villainName = villainName; } public boolean isAwesome() { return isAwesome; } public void setAwesome(boolean isAwesome) { this.isAwesome = isAwesome; } @Override public String toString() { return "Villain [villaiId=" + villaiId + ", villainName=" + villainName + ", isAwesome=" + isAwesome + "]"; } } Ok now that we have defined our domains, let us see how data retrieval happens with DetachedCriteria. I have used DetachedCriteria here because The Avengers were very specific and said they do not want anything to do with the Hibernate session, so hence i used DetachedCriteria which does not require a hibernate session to be present. Our primary objective is to retrieve The Avenger to whom a villain belongs to. Note that this assumes the same villain cannot be a villain to more than one superhero. So moving on i give below the method that retrieves an avenger based on the villain name passed. public Avenger retrieveAvengerByVillainName(String villainName) { Avenger avenger = null; /** * Selected a detached criteria so we do not need a session to run it * within. */ DetachedCriteria criteria = DetachedCriteria.forClass(Avenger.class); /** * Here we are doing an inner join with the Villain table in order to do * a name comparison with the villainName passed in as a method * parameter */ DetachedCriteria villainCriteria = criteria.createCriteria("enemyList"); villainCriteria.add(Restrictions.eq("villainName", villainName)); villainCriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); @SuppressWarnings("unchecked") List avengerList = getHibernateTemplate().findByCriteria( criteria); if (!avengerList.isEmpty()) { avenger = avengerList.get(0); getHibernateTemplate().initialize(avenger.getEnemyList()); } return avenger; } In this method what we do is first we create a criteria for our master class which in this case is Avenger.class. Then we need to do a join with the Villain table and hence we create a sub criteria from our main criteria with the name of the list we defined within the Avenger domain class. Then it is a matter of equaling the property of the Villain domain to the villain name passed in. The power of the Criteria API is such that you can create dynamic queries with ease which would be a hassle if we were to use pure HQL which would require substantial string concatenations in order to achieve the same. A sample test class called AvengerTest.java is given with the attachment which you can find at the top of the most. Note that you need to remove the comment on avenger-context.xml in order to create the tables needed for this example. So that is about it. The Avengers can be risk averse now that they have a system by which they can relate any super villain to a super hero within their league. As always your comments and suggestions are always welcome and appreciated. Thank you for taking the time to read!!!! From http://dinukaroshan.blogspot.com/2011/11/hibernate-by-example-part-2.html
November 11, 2011
by Dinuka Arseculeratne
· 63,275 Views
article thumbnail
ASP.NET MVC: Converting business objects to select list items
Some of our business classes are used to fill dropdown boxes or select lists. And often you have some base class for all your business classes. In this posting I will show you how to use base business class to write extension method that converts collection of business objects to ASP.NET MVC select list items without writing a lot of code. BusinessBase, BaseEntity and other base classes I prefer to have some base class for all my business classes so I can easily use them regardless of their type in contexts I need. NB! Some guys say that it is good idea to have base class for all your business classes and they also suggest you to have mappings done same way in database. Other guys say that it is good to have base class but you don’t have to have one master table in database that contains identities of all your business objects. It is up to you how and what you prefer to do but whatever you do – think and analyze first, please. :) To keep things maximally simple I will use very primitive base class in this example. This class has only Id property and that’s it. public class BaseEntity { public virtual long Id { get; set; } } Now we have Id in base class and we have one more question to solve – how to better visualize our business objects? To users ID is not enough, they want something more informative. We can define some abstract property that all classes must implement. But there is also another option we can use – overriding ToString() method in our business classes. public class Product : BaseEntity { public virtual string SKU { get; set; } public virtual string Name { get; set; } public override string ToString() { if (string.IsNullOrEmpty(Name)) return base.ToString(); return Name; } } Although you can add more functionality and properties to your base class we are at point where we have what we needed: identity and human readable presentation of business objects. Writing list items converter Now we can write method that creates list items for us. public static class BaseEntityExtensions { public static IEnumerable ToSelectListItems (this IList baseEntities) where T : BaseEntity { return ToSelectListItems((IEnumerator) baseEntities.GetEnumerator()); } public static IEnumerable ToSelectListItems (this IEnumerator baseEntities) { var items = new HashSet(); while (baseEntities.MoveNext()) { var item = new SelectListItem(); var entity = baseEntities.Current; item.Value = entity.Id.ToString(); item.Text = entity.ToString(); items.Add(item); } return items; } } You can see here to overloads of same method. One works with List and the other with IEnumerator. Although mostly my repositories return IList when querying data there are always situations where I can use more abstract types and interfaces. Using extension methods in code In your code you can use ToSelectListItems() extension methods like shown on following code fragment. ... var model = new MyFormModel(); model.Statuses = _myRepository.ListStatuses().ToSelectListItems(); ... You can call this method on all your business classes that extend your base entity. Wanna have some fun with this code? Write overload for extension method that accepts selected item ID.
November 11, 2011
by Gunnar Peipman
· 13,760 Views
article thumbnail
Groovy Goodness: Find Non-Null Results After Transformation in a Collection
Since Groovy 1.8.1 we can use the findResults method and pass a closure to transform elements in a collection and get all non-null elements after transformation. We also have the findResult method to return the first non-null transformed element, but with findResults we get all non-null elements. def stuff = ['Groovy', 'Griffon', 'Gradle', 'Spock', 'Grails', 'GContracts'] def stuffResult = stuff.findResults { it.size() == 6 ? "$it has 6 characters" : null } assert stuffResult == ['Groovy has 6 characters', 'Gradle has 6 characters', 'Grails has 6 characters'] def map = [what: 'Finish blog post', priority: 1, when: new Date()] def mapResult = map.findResults { it.value instanceof String ? "Key $it.key is of type String" : null } assert mapResult == ['Key what is of type String'] From http://mrhaki.blogspot.com/2011/11/groovy-goodness-find-non-null-results.html
November 10, 2011
by Hubert Klein Ikkink
· 6,886 Views
article thumbnail
Securing a RESTful Web Service with Spring Security 3.1, part 3
1. Overview This is the third of a series of articles about setting up a secure RESTful Web Service using Spring 3.1 and Spring Security 3.1 with Java based configuration. This article will focus on the security configuration using Spring Security 3.1, assuming some understanding of Spring Security basics and focusing on the specifics of securing the RESTful web service. The REST with Spring series: Part 1 – Bootstrapping a web application with Spring 3.1 and Java based Configuration Part 2 – Building a RESTful Web Service with Spring 3.1 and Java based Configuration Part 4 – RESTful Web Service Discoverability Part 5 – REST Service Discoverability with Spring Part 6 – Basic and Digest authentication for a RESTful Service with Spring Security 3.1 Part 7 – REST Pagination in Spring Part 8 – Authentication against a RESTful Service with Spring Security Part 9 – ETags for REST with Spring 2. Introducing Spring Security in the web.xml The architecture of Spring Security is based entirely on servlet filters and, as such, comes before Spring MVC in regards to the processing of HTTP requests. Keeping this in mind, to begin with, a filter needs to be declared in the web.xml of the application: springSecurityFilterChain org.springframework.web.filter.DelegatingFilterProxy springSecurityFilterChain /* The filter must necessarily be named ‘springSecurityFilterChain’ to match the default bean created by Spring Security in the container. Note that the defined filter is not the actual class implementing the security logic but a DelegatingFilterProxy with the purpose of delegating the Filter’s methods to an internal bean. This is done so that the target bean can still benefit from the Spring context lifecycle and flexibility. The URL pattern used to configure the Filter is /* even though the entire web service is mapped to /api/* so that the security configuration has the option to secure other possible mappings as well, if required. 3. The security configuration Most of the configuration is done using the security namespace – for this to be enabled, the schema locations must be defined and pointed to the new 3.1 versions. The namespace is designed so that it expresses the common uses of Spring Security while still providing hooks to the underlying beans. 3.1. The basics The element is the main container element for HTTP security configuration. In the current implementation, it only secured a single mapping: /api/admin/**. Note that the mapping is relative to the root context of the web application, not to the rest servlet; this is because the entire security configuration lives in the root Spring context and not in the child context of the servlet. 3.2. The entry point In a standard web application, the authentication process may be automatically triggered when the client tries to access a secured resource without being authenticated – this is usually done by redirecting to a login page so that the user can enter credentials. However, for a RESTful Web Service this behavior doesn’t make much sense – authentication should only be done by a request to the correct URI and all other requests should simply fail with a 401 UNAUTHORIZED status code if the user is not authenticated. Spring Security handles this automatic triggering of the authentication process with the concept of an entry point; the entry point is a required part of the configuration, and can be injected via the entry-point-ref attribute of the element. Keeping in mind that this functionality doesn’t make sense in the context of the RESTful web service, the new custom entry point is defined: @Component( "restAuthenticationEntryPoint" ) public final class RestAuthenticationEntryPoint implements AuthenticationEntryPoint{ @Override public final void commence ( HttpServletRequest request, HttpServletResponse response, AuthenticationException authException ) throws IOException{ response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized" ); } } 3.3. The login There are multiple ways to do authentication for a RESTful Web Service – one of the default Spring Security provides is form login – which uses an authentication processing filter – org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter. Since the element doesn’t automatically create this particular filter by default, it needs to be explicitly specified in the configuration, using the element at the position FORM_LOGIN_FILTER; the only required dependency for this bean is the authentication manager. Note that for a standard web application, the auto-configattribute of the element is shorthand syntax for some useful security configuration. While this may be appropriate for some very simple configurations, it doesn’t fit and should not be used for a REST API. 3.4. Authentication should return 200 instead of 301 By default, form login will answer a successful authentication request with a 301 MOVED PERMANENTLY status code; this makes sense in the context of an actual login form which needs to redirect after login. For a RESTful web service however, the desired response for a successful authentication should be 200 OK. This is done by injecting a custom authentication success handler in the form login filter, to replace the default one. The new handler implements the exact same login as the default org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler with one notable difference – the redirect logic is removed: // Use the DefaultSavedRequest URL // final String targetUrl = savedRequest.getRedirectUrl(); // this.logger.debug( "Redirecting to DefaultSavedRequest Url: " + targetUrl ); // this.getRedirectStrategy().sendRedirect( request, response, targetUrl ); 3.5. The authentication manager and provider The authentication process uses an in-memory provider to perform authentication – this is meant to simplify the configuration as a production implementation of these artifacts is outside the scope of this post. 4. Maven and other trouble In addition to the pom.xml from the first post, as well as the one from the second post, the Spring Security maven dependencies need to be added: org.springframework.security spring-security-web ${spring-security.version} org.springframework.security spring-security-config ${spring-security.version} org.springframework spring-tx ${spring.version} org.springframework spring-aop ${spring.version} 3.2.2.RELEASE 3.1.3.RELEASE Notice that the version of the security dependencies is no longer 3.1.0.BUILD-SNAPSHOT as for the standard Spring framework, but 3.1.0.CI-SNAPSHOT. What is more, the security artifacts define dependencies to the 3.0.x versions of Spring, more specifically spring-security-web depends on spring-aop and on spring-tx version 3.0.x instead of the expected 3.1.x. To understand why this is a problem, we need to understand how the Maven conflict resolution algorithm works – in case of conflict, Maven will chose which jar to include based on the distance between the particular dependency and the root of the tree. In our case, the conflicts are the spring-aop and spring-tx jars, appearing once with version 3.0.6 and once with 3.1.0. In the case of spring-aop, it appears once as a level 1 dependency of both spring-security-web and spring-security-config with version 3.0.6 , and once as a level 2 dependency of spring-webmvc with the version 3.1.0; since the 3.0.6 versioned jar is closer to the root, it will be the one chosen by the conflict resolution mechanism. Now that we understand why it is that Maven will deploy the 3.0.6 version of the jars with the application and not the intended 3.1.0 version, we need to address the issue. The solution is to add the two dependencies, with the intended 3.1.0 versions, directly into the pom – this will shorten the distance between them and the root to 0 and will force Maven to use them first. 5. Conclusion This post covered the basic security configuration and implementation for a RESTful service using Spring Security 3.1, discussing the web.xml, the security configuration, the HTTP status codes for the authentication process and the Maven resolution of the security artifacts. In the next articles I will focus on a Java based configuration for Spring Security, integration testing of the secure API using the rest-assured library and HTTP basic authentication. In the meantime, check out the github project. If you read this far, you should follow me on twitter here. Original at Securing a RESTful Web Service with Spring Security 3.1 from the REST with Spring series.
November 9, 2011
by Eugen Paraschiv
· 112,778 Views · 2 Likes
article thumbnail
Dependency Injection for Dummies
Dependency injection is a very simple concept: if you have an object that interacts with other objects the responsibility of finding a reference to those objects at run time is moved outside of the object itself. What does it mean for an object to "interact" with other objects? Generally it means invoking methods or reading properties from those objects. So if we have a class A that invokes method Calculate on class B, we can say that A interacts with B. In the following example we show class A interacting with class B. We can equally say that A depends on class B to fulfill a responsibility. In this case, it not only invokes its method Calculate but it also creates a new instance of that class. class A { private B _b; public A { _b = new B(); } public int SomeMethod() { return (_b.Calculate() * 2); } } In the following example, on the other side, the responsibility of getting a reference to an implementation of a class of type B is moved outside of A: class A { private _b = B; public A(B b) { _b = b; } public int SomeMethod() { return _(b.Calculate * 2); } } In this case we say that a dependency (B) has been injected into A, via the constructor. Of course, you can also inject dependencies via a property (or even a regular method), like in the following example: class A { private _b = B; public B B { get { return _b; } set { _b = value; } } public int SomeMethod() { if (_b != null) return _b.RetrieveValue() * 2;} else // HANDLE THIS ERROR CASE return -1; } } So this is all there is about dependency injection. Everything else just builds on this core concept. Like for example Inversion Of Control (IoC) tools which helps you wiring together your objects at run time, injecting all dependencies as needed. So what exactly is Inversion of Control and how does it relate to Dependency Injection (DI)? I like to associate IoC to the Hollywood Principle: "Don't call us, we'll call you". IoC is a design principle where reusable generic code controls the execution of problem-specific code: it is a characteristic of many frameworks, where the application is built extending or customizing a common skeleton; you put your own classes at specific points and the framework will call you when needed. You can use an IoC container as a framework to perform Dependency Injection on your behalf: you tell the container which are the concrete implementation classes for your dependencies and the container will make sure that your constructors or setters will be called with the right objects. Therefore, IoC containers are just a convenience to simplify how dependency injection is handled. But even if you don't use one you could still manually perform dependency injection. (If you want to have a look at how an IoC container works you can jump to my mini tutorial on Ninject). Why is the concept of dependency injection important? Because by applying it, you simplify your design (separating the responsibility of using an object from the responsibility of using the object) and your code becomes much easier to test, since you can mock out the dependencies substituting them with fake (stub) objects. But that is the subject for another post.
November 8, 2011
by Stefano Ricciardi
· 11,272 Views · 28 Likes
article thumbnail
How to Load Image that is set as Embedded Resource in BuildAction in Windows Phone
In one of my previous posts, I explained how to load the Image that is Set as Resource in Build Action . In this blog post, I will provide you a sample that loads the image which is set as “Embedded Resource” in Windows Phone using the Assembly’s GetManifestResourceStream. Use the GetManifestResourceStream method in the Assembly object by passing the image name. Make sure that the image is set to the Embedded Resource and when passing the image name pass the image name along with the Namespace as shown in the below sample code where PhoneApp3 is the ProjectName and StartScreen.jpg is the file name. Set the BitMapImage’s source to the stream and assign this to the Source property of the Image. private void button1_Click_1(object sender, RoutedEventArgs e) { Assembly CurrentAssembly; CurrentAssembly = Assembly.GetExecutingAssembly(); Stream EmbeddedResourceStream = CurrentAssembly.GetManifestResourceStream(“PhoneApp3.StartScreen.jpg”); BitmapImage bitMapImage = new BitmapImage(); bitMapImage.SetSource(EmbeddedResourceStream); image1.Source = bitMapImage; }
November 7, 2011
by Senthil Kumar
· 11,900 Views
article thumbnail
Selectable Shapes Part 2: Resizable, Movable Shapes on HTML5 Canvas
In the first tutorial I showed how to create a basic data structure for shapes on an HTML5 canvas and how to make them selectable, draggable, and movable. In this second part we’ll be reorganizing the code a little bit and adding selection handles so we can resize our Canvas objects. The finished canvas will look like this: Click to select a box. Click on a selection handle to resize. Double click to add new boxes. This article’s code is written primarily to be easy to understand. It isn’t optimized for performance because a little bit of the drawing is set up so that more complex shapes can easily be added in the future. In this tutorial we will add: Code for drawing the eight boxes that make up the selection handles Some small adjustments to the draw code Code to be run on every mouse move event Code for changing the mouse cursor when it is over a selection handle Code for resizing Drawing the selection handles The eight selection handles are unique in that each one allows you to resize an object in a different way. For instance clicking on the top-middle one will only let you make it taller or shorter, but the top-right one will allow you to make it taller, shorter, as well as more wide or narrow. Like all decidedly unique things, we’ll want to keep track of them. // New, holds the 8 tiny boxes that will be our selection handles // the selection handles will be in this order: // 0 1 2 // 3 4 // 5 6 7 var selectionHandles = []; Previously we had the variables mySelColor and mySelWidth for the selection’s color and width. Now we also add variables for selection box color and size: var mySelBoxColor = 'darkred'; // New for selection boxes var mySelBoxSize = 6; Draw’s new home Draw is still its own function but most of the code has been moved out of it. We’re going to make our Box class start to look a little more classy by letting boxes draw themselves. If you haven’t seen this syntax before, it adds the draw function to all instances of the Box class, creating a someBox.draw() we can call on boxes. To clear up confusion, our old draw loop will be renamed mainDraw. // New methods on the Box class Box.prototype = { // we used to have a solo draw function // but now each box is responsible for its own drawing // draw() will call this with the normal canvas // myDown will call this with the ghost canvas with 'black' draw: function(context, optionalColor) { // ... (draw code) ... } // end draw } This draw code is lifted from the old draw method but with a few additions for the selection handles. We check to see if the current box is selected, and if it is, we draw the selection outline as well as the eight selection boxes, their places based on the selected object’s bounds. In the Init() function we need to add the selectionHandles[] initialization as well as a new event. In the past, myMove was only activated if you pressed down with the mouse, and became deactivated as soon as the mouse was released. Now we need myMove to be active all the time. // new code in init() canvas.onmousemove = myMove; // set up the selection handle boxes for (var i = 0; i < 8; i ++) { var rect = new Box; selectionHandles.push(rect); } Our new main draw loop is now very slimmed down: function mainDraw() { if (canvasValid == false) { clear(ctx); // draw all boxes var l = boxes.length; for (var i = 0; i < l; i++) { boxes[i].draw(ctx); // we used to call drawshape, but now each box draws itself } canvasValid = true; } } Doing this reorganization isn’t too important now, but it will be useful later on if we have many different types of objects draw themselves. After all, rectangles and (for instance) lines are not drawn in the same way, so if we can put all the custom drawing code in the object’s own class we can keep things better organized. myMove revisited Before I talk about myMove lets take a look at two new variables added to the top of our code that signal whether or not a box is being dragged and if so, from which selection handle. var isResizeDrag = false; var expectResize = -1; // New, will save the # of the selection handle if the mouse is over one. isResizeDrag seems simple enough, it works almost identically to isDrag. expectResize will be a number between 0 and 7 to indicate which selection handle is currently active. If none is active (the default), we’ll set it to -1. In most programs that have selection handles (such as the edges of your browser) it is nice to have the mouse cursor change to show that an action can be performed. To do this we are going to have to ask where the mouse is located all the time and see if it is over one of our eight selection handles. Remember that above we made myMove active all of the time and Now we have to add code to it: // Happens when the mouse is moving inside the canvas function myMove(e){ if (isDrag) { getMouse(e); mySel.x = mx - offsetx; mySel.y = my - offsety; // something is changing position so we better invalidate the canvas! invalidate(); } else if (isResizeDrag) { // ... new code to talk about later. } getMouse(e); // if there's a selection see if we grabbed one of the selection handles if (mySel !== null && !isResizeDrag) { for (var i = 0; i < 8; i++) { // 0 1 2 // 3 4 // 5 6 7 var cur = selectionHandles[i]; // we dont need to use the ghost context because // selection handles will always be rectangles if (mx >= cur.x && mx <= cur.x + mySelBoxSize && my >= cur.y && my <= cur.y + mySelBoxSize) { // we found one! expectResize = i; invalidate(); switch (i) { case 0: this.style.cursor='nw-resize'; break; case 1: this.style.cursor='n-resize'; break; case 2: this.style.cursor='ne-resize'; break; case 3: this.style.cursor='w-resize'; break; case 4: this.style.cursor='e-resize'; break; case 5: this.style.cursor='sw-resize'; break; case 6: this.style.cursor='s-resize'; break; case 7: this.style.cursor='se-resize'; break; } return; } } // not over a selection box, return to normal isResizeDrag = false; expectResize = -1; this.style.cursor='auto'; } So if there is something selected and we are not already dragging, we will execute some code to see if the mouse position is over one of the selection boxes. If it is, give the mouse cursor the correct arrow. If the mouse isn’t over a selection box, make sure we change it back to the normal pointer. You’ll also notice that at the start, after “if (isDrag)” we have a new test, “else if (isResizeDrag).” isResizeDrag becomes true if two conditions are met: expectResize is set to one of the selection handle numbers (is not -1) we have pressed down the mouse In other words, it only happens if the mouse is over a selection handle and has been pressed. We add a tiny bit of code to myDown to make this work. // Happens when the mouse is clicked in the canvas function myDown(e){ getMouse(e); //we are over a selection box if (expectResize !== -1) { isResizeDrag = true; return; } // ... the rest of myDown } Anyway, getting back to myMove. We are looking for the “else if (isResizeDrag)” to see what happens when this is true. function myMove(e){ if (isDrag) { // ... } else if (isResizeDrag) { // time ro resize! var oldx = mySel.x; var oldy = mySel.y; // 0 1 2 // 3 4 // 5 6 7 switch (expectResize) { case 0: mySel.x = mx; mySel.y = my; mySel.w += oldx - mx; mySel.h += oldy - my; break; case 1: mySel.y = my; mySel.h += oldy - my; break; case 2: mySel.y = my; mySel.w = mx - oldx; mySel.h += oldy - my; break; case 3: mySel.x = mx; mySel.w += oldx - mx; break; case 4: mySel.w = mx - oldx; break; case 5: mySel.x = mx; mySel.w += oldx - mx; mySel.h = my - oldy; break; case 6: mySel.h = my - oldy; break; case 7: mySel.w = mx - oldx; mySel.h = my - oldy; break; } invalidate(); } // ... rest of myMove } We see a bunch of arithmetic dealing with precisely how each handle will resize the box. Handle #6 is middle-bottom, so it only resizes the height of the box. Handle #1, on the other hand, is the middle top. It has to resize both the Y-axis co-ordinate as well as the height. If #1 only changed the Y-axis, then dragging it upwards would just look like the entire box is being dragged upwards. If it just resized the height, the top of the box would stay in the same position and we certainly don’t want that if the top is what we intended to move! That’s pretty much everything. Try it out yourself above or see the demo and download the full source on this page. So that wasn’t too bad. A few long chunks were added but not because of complexity, just because each of the eight selection handles is uniquely placed and does a unique resizing task. If you would like to see this code enhanced in future posts (or have any fixes), let me know how in the comments.
November 7, 2011
by Simon Sarris
· 11,034 Views
article thumbnail
Using JSR-250's @PostConstruct Annotation to Replace Spring's InitializingBean
JSR-250 aka Common Annotations for the Java Platform was introduced as part of Java EE 5 an is usually used to annotated EJB3s. What’s not so well known is that Spring has supported three of the annotations since version 2.5. The annotations supported are: @PostContruct - This annotation is applied to a method to indicate that it should be invoked after all dependency injection is complete. @PreDestroy - This is applied to a method to indicate that it should be invoked before the bean is removed from the Spring context, i.e. just before it’s destroyed. @Resource - This duplicates the functionality of @Autowired combined with @Qualifier as you get the additional benefit of being able to name which bean you’re injecting, without the need for two annotations. This blog takes a quick look at the first annotation in the list @PostConstruct, demonstrating how it’s applied and comparing it to the equivalent InitializingBean interface. InitializingBean has one method, afterPropertiesSet(), and it does what it says on the tin. The afterPropertiesSet() method is called after Spring has completed wiring things together. The code snippet below demonstrates how InitializingBean is implemented. public class ImplementInitializingBean implements InitializingBean { private boolean result; public String businessMethod() { System.out.println("Inside - ImplementInitializingBean"); return "InitializingBeanResult"; } /** * This is part of the InitializingBean interface - called after the bean has been set-up. Use this method to check that the * bean has been set-up correctly. Also so use it to configure external resources such as databases etc. */ @Override public void afterPropertiesSet() throws Exception { result = true; System.out.println("In aferPropertiesSet() - check the set-up of the bean."); } public boolean getResult() { return result; } } Annotations are supposed to make life easier, but do they in this case? Firstly to use the @PostConstruct annotation you need to include the following dependencies your POM file: org.springframework spring-web ${spring.version} org.springframework spring-webmvc ${spring.version} javax.servlet servlet-api 2.5 provided You also need to tell Spring to use annotations by adding the following to your Spring config file: Having setup the environment, you can now use the @PostConstruct annotation. @Component public class ImplementPostConstruct implements MyPostConstructExample { private boolean result; @Override public String businessMethod() { System.out.println("Inside - ImplementPostConstruct"); return "ImplementPostConstruct"; } /** * @PostConstruct means that this is called after the bean has been set-up. * Use this method to check that the bean has been set-up * correctly. Also so use it to configure external resources * such as databases etc. */ @PostConstruct public void postConstruct() { result = true; System.out .println("In postConstruct() - check the set-up of the bean."); } @Override public boolean getResult() { return result; } } This is tested using the JUnit Test below: @Test public void postConstructTest() { instance1 = ctx.getBean(ImplementPostConstruct.class); String result = instance1.businessMethod(); assertEquals("ImplementPostConstruct", result); boolean var = instance1.getResult(); assertTrue(var); } The two clumps of code above do the same thing with postConstruct() being called at the same time asafterPropertiesSet(). It's easy to see that annotations look neater, but they are also more difficult to setup? I'll let you be the judge of that. Finally, one last thing to note, the JSR-250 annotations provide useful core functionality, but are part of Spring's MVC project warranting a possible superfluous dependency on the javax.servlet-api jar, so perhaps a little refactoring may be a good idea at some point. From http://www.captaindebug.com/2011/11/using-jsr-250s-postconstruct-annotation.html
November 6, 2011
by Roger Hughes
· 45,053 Views · 1 Like
article thumbnail
Creating a backup in Team Foundation Server 2010 using the Power Tools
over the last few years the product team has been putting their finishing touches on a backup module for the team foundation server administration console. why you might ask do you need another way to backup? surely you can just backup the bits? well, you could, but as tfs has a lot of moving parts it can get very complicated to creating a backup . required permissions identify databases create tables in databases create a stored procedure for marking tables create a stored procedure for marking all tables at once create a stored procedure to automatically mark tables create a scheduled job to run the table-marking procedure create a maintenance plan for full backups create a maintenance plan for differential backups create a maintenance plan for transaction backups back up additional lab management components -from “back up team foundation server” on msdn there are a heck of a lot of databases that, depending on your environment, might be spread over your entire network. figure: deployment topologies (where is my data?) from msdn so, how is this problem solved. well the tfs team have create a tool to create all of the backups and all of the job as well as managing the backup location for you. this sounds fantastic, but how about in practice. was it really that easy? well….not really…here is the extra stuff i found out: your account must own the share owning the folder does not cut it (see error #1- tf254027). sql must be running under a domain account or network service sql must also have permission to the share, and the validation will get confused if you use “localsystem” instead of network service or a domain account (see error #2- tf254027) the account running sql must have permission to create spn’s the account that is used for sql must be able to both see and create service principal names in active directory (see error #3: terminating your tfs server). once you learn how to google without keywords and read your servers mind you will have a nice backup system going… error #1- tf254027 i initially got an error because the accounts did not really have full control over the target location. this is a problem with the share. although i have full permission for \\fileserver1\share\tfsbackups it is just a folder under the \\fileserver1\share\ location and i do not have permission to change the sharing settings there. figure: tf254027 is caused by permission issues [info @16:36:34.342] granting account root_company\tfssqlbox$ permission on folder \\fileserver1\share\tfsbackups [info @16:36:34.348] system.unauthorizedaccessexception: attempted to perform an unauthorized operation. at system.security.accesscontrol.win32.setsecurityinfo(resourcetype type, string name, safehandle handle, securityinfos securityinformation, securityidentifier owner, securityidentifier group, genericacl sacl, genericacl dacl) at system.security.accesscontrol.nativeobjectsecurity.persist(string name, safehandle handle, accesscontrolsections includesections, object exceptioncontext) at system.security.accesscontrol.filesystemsecurity.persist(string fullpath) at microsoft.teamfoundation.powertools.admin.helpers.filehelper.grantfolderpermission(string account, string path) [info @16:36:34.350] granting account root_company\tfs.services permission on folder \\fileserver1\share\tfsbackups [info @16:36:34.352] system.unauthorizedaccessexception: attempted to perform an unauthorized operation. at system.security.accesscontrol.win32.setsecurityinfo(resourcetype type, string name, safehandle handle, securityinfos securityinformation, securityidentifier owner, securityidentifier group, genericacl sacl, genericacl dacl) at system.security.accesscontrol.nativeobjectsecurity.persist(string name, safehandle handle, accesscontrolsections includesections, object exceptioncontext) at system.security.accesscontrol.filesystemsecurity.persist(string fullpath) at microsoft.teamfoundation.powertools.admin.helpers.filehelper.grantfolderpermission(string account, string path) [error @16:36:34.352] granting permission to account root_company\tfssqlbox$ on path \\fileserver1\share\tfsbackups failed figure: the log files get to the root of the problem, but not the reason after much messing around i have found that you can’t use a sub-folder of a share that you do not have permission for. you require permission to the share itself to apply permissions. error #2- tf254027 lets try this again with a share that we control. i will create a backup share on the tfs server and at least then i control then permissions. figure: the next error looks the same, but it is subtly different [info @18:12:05.813] "verify: grant backup plan permissions\root\verifybackuppathpermissionsgrantedsuccessfully(verifybackuppathpermissionsgrantedsuccessfully): exiting verification with state completed and result success" [info @18:12:05.813] verify: grant backup plan permissions\root\verifydummybackupcreation(verifytestbackupcreatedsuccessfully): starting verification [info @18:12:05.813] verify test backup created successfully [info @18:12:05.813] starting creating backup test validation [error @18:12:06.132] microsoft.sqlserver.management.smo.failedoperationexception: backup failed for server 'sqlserver1'. ---> microsoft.sqlserver.management.common.executionfailureexception: an exception occurred while executing a transact-sql statement or batch. ---> system.data.sqlclient.sqlexception: cannot open backup device '\\tfsserver1\tfsbackup\temp_20111104111205.bak'. operating system error 5(access is denied.). backup database is terminating abnormally. at microsoft.sqlserver.management.common.connectionmanager.executetsql(executetsqlaction action, object execobject, dataset filldataset, boolean catchexception) at microsoft.sqlserver.management.common.serverconnection.executenonquery(string sqlcommand, executiontypes executiontype) --- end of inner exception stack trace --- at microsoft.sqlserver.management.common.serverconnection.executenonquery(string sqlcommand, executiontypes executiontype) at microsoft.sqlserver.management.common.serverconnection.executenonquery(stringcollection sqlcommands, executiontypes executiontype) at microsoft.sqlserver.management.smo.executionmanager.executenonquery(stringcollection queries) at microsoft.sqlserver.management.smo.backuprestorebase.executesql(server server, stringcollection queries) at microsoft.sqlserver.management.smo.backup.sqlbackup(server srv) --- end of inner exception stack trace --- at microsoft.sqlserver.management.smo.backup.sqlbackup(server srv) at microsoft.teamfoundation.powertools.admin.helpers.backupfactory.testbackupcreation(string path) [error @18:12:06.184] !verify error!: account root_comapny\martin.hinshelwood failed to create backups using path \\tfsserver1\tfsbackup [info @18:12:06.184] "verify: grant backup plan permissions\root\verifydummybackupcreation(verifytestbackupcreatedsuccessfully): exiting verification with state completed and result error" [info @18:12:06.184] !verify result!: 5 completed, 0 skipped: 4 success, 1 errors, 0 warnings [info @18:12:06.197] verify: backup tasks verifications(vcontainer): starting verification [info @18:12:06.197] a generic container node that does not contribute to results [info @18:12:06.197] "verify: backup tasks verifications(vcontainer): exiting verification with state ignore and result ignore" [info @18:12:06.197] verify: backup tasks verifications\root(vcontainer): starting verification [info @18:12:06.197] a generic container node that does not contribute to results [info @18:12:06.197] "verify: backup tasks verifications\root(vcontainer): exiting verification with state ignore and result ignore" [info @18:12:06.197] verify: backup tasks verifications\root\verifydummybackupcreation(verifytestbackupcreatedsuccessfully): starting verification [info @18:12:06.197] verify test backup created successfully [info @18:12:06.197] starting creating backup test validation [error @18:12:06.389] microsoft.sqlserver.management.smo.failedoperationexception: backup failed for server sqlserver1'. ---> microsoft.sqlserver.management.common.executionfailureexception: an exception occurred while executing a transact-sql statement or batch. ---> system.data.sqlclient.sqlexception: cannot open backup device '\\tfsserver1\tfsbackup\temp_20111104111206.bak'. operating system error 5(access is denied.). backup database is terminating abnormally. at microsoft.sqlserver.management.common.connectionmanager.executetsql(executetsqlaction action, object execobject, dataset filldataset, boolean catchexception) at microsoft.sqlserver.management.common.serverconnection.executenonquery(string sqlcommand, executiontypes executiontype) --- end of inner exception stack trace --- at microsoft.sqlserver.management.common.serverconnection.executenonquery(string sqlcommand, executiontypes executiontype) at microsoft.sqlserver.management.common.serverconnection.executenonquery(stringcollection sqlcommands, executiontypes executiontype) at microsoft.sqlserver.management.smo.executionmanager.executenonquery(stringcollection queries) at microsoft.sqlserver.management.smo.backuprestorebase.executesql(server server, stringcollection queries) at microsoft.sqlserver.management.smo.backup.sqlbackup(server srv) --- end of inner exception stack trace --- at microsoft.sqlserver.management.smo.backup.sqlbackup(server srv) at microsoft.teamfoundation.powertools.admin.helpers.backupfactory.testbackupcreation(string path) figure: this time the error is lying and is from sql not locally as it implies it looks like the problem is that sql server can’t write to that folder, but i can and the machine account can. lets try this from the sql server itself, and with a native backup. figure: sql server can’t write to that location dam… so even a native sql backup can’t write to this location. title: microsoft sql server management studio ------------------------------ backup failed for server 'sqlserver1'. (microsoft.sqlserver.smoextended) for help, click: http://go.microsoft.com/fwlink?prodname=microsoft+sql+server&prodver=10.50.2500.0+((kj_pcu_main).110617-0038+)&evtsrc=microsoft.sqlserver.management.smo.exceptiontemplates.failedoperationexceptiontext&evtid=backup+server&linkid=20476 ------------------------------ additional information: system.data.sqlclient.sqlerror: cannot open backup device '\\tfsserver1\tfsbackup\moo.bak'. operating system error 5(access is denied.). (microsoft.sqlserver.smo) for help, click: http://go.microsoft.com/fwlink?prodname=microsoft+sql+server&prodver=10.50.2500.0+((kj_pcu_main).110617-0038+)&linkid=20476 ------------------------------ buttons: ok ------------------------------ figure: sql server errors suck even more as it turns out, sql server is running under “localserivce” which is not authenticating against our share. so we need to change the service that tfs runs under. error #3: terminating your tfs server as we should always use the sql server configuration manager to change these things i fired it up and since i already have a domain account for running tfs under i decided to use that one. figure: this is easy when you apply it will ask you to restart sql, but it should be all complete. lets check tfs and make sure that everything is running… figure: omg! what just happened! oh shit: i think i just broke tfs. why can’t tfs connect? lets try the sql management studio and see. figure: what is a sspi? this does not look good… after i have hastily changed the service account back to the original value and made use that his fixed tfs i wanted to also figure out why it broke. usually i would just ask shad (one of my extremely technical colleagues) but alas he is on his honeymoon. some googling turned up an spn issue. the account that sql runs under must be able to both read and write service principal names for itself in active directory. this can be set, but only be a domain admin. dynamically set spn’s for sql service accounts so lets go with network service instead. if we change the account that sql server runs under to “network service” then i can add permission for “root_company\sqlserver1$” to my share and get it working. yes, servers have ad accounts as well.
November 5, 2011
by Martin Hinshelwood
· 10,114 Views
article thumbnail
Groovy: Creating an Interface Stub and Intercepting All Calls to It
It’s sometimes useful for unit testing to be able to create a simple no-op stub of an interface the class under test depends upon and to intercept all calls to the stub, for example to remember all the calls and parameters so that you can later verify that they’ve been invoked as expected. Often you’d use something like Mockito and its verify method but if you’re writing unit tests in Groovy as I recommend then there is a simpler and in a way a more powerful alternative. Solution 1 – When Calling the Stub From a Groovy Object @Before public void setUp() { this.collectedCalls = [] // The following works when a method on the listener is called from Groovy but not from Java: this.listener = {} as PageNodeListener listener.metaClass.invokeMethod = { name, args -> collectedCalls << new Call(method: name, args: args) // Call is a simple structure class } } @Test public void listener_stub_should_report_all_calls_to_it() throws Exception { listener.fileEntered("fileName.dummy") assert collectedCalls.find { it.equals(new Call(method: "fileEntered", args: ["fileName.dummy"]))} } Notes: 5: {} as PageNodeListener uses Groovy’s closure coercion – basically it creates an implementation of the interface which uses the (empty) closure whenever any method is called (we could capture its arguments but not the method name via {Object[] args -> /*...*/} as PageNodeListener) 6-7: We then specify an interceptor method that should be invoked whenever any method is called on the instance Groovy makes it very easy to create beans like Call with equals, toString etc. Beware that using a coerced closure as an interface implementation works only for methods that are either void or can return null (which is the return value of an empty closure, when invoked). Other methods will throw an NPE: def list = {} as java.util.List list.clear() // OK, void list.get(0) // OK, returns null list.isEmpty() // NullPointerException at $Proxy4.isEmpty Solution 2 – When Calling the Stub From a Java Object The solution 1 is small and elegant but for me it hasn’t worked when the stub was invoked by a Java object (a clarification of why that happened would be welcome). Fortunately Christoph Metzendorf proposed a solution at StackOverflow (adjusted): @Before public void setUp() { this.collectedCalls = [] PageNodeListener listener = createListenerLoggingCallsInto(collectedCalls) this.parser = new MyFaces21ValidatingFaceletsParser(TEST_WEBROOT, listener) } def createListenerLoggingCallsInto(collectedCalls) { def map = [:] PageNodeListener.class.methods.each() { method -> map."$method.name" = { Object[] args -> collectedCalls << new Call(method.name, args) } } return map.asType(PageNodeListener.class) } @Test public void should_notify_about_file_entered() throws Exception { parser.validateExpressionsInView(toUrl("empty.xhtml"), "/empty.xhtml") assert collectedCalls.find { it.equals(new Call(method: "fileEntered", args: ["/empty.xhtml"]))} } Notes: 12-13: We create a map containing {method name} -> {closure} for each of the interface’s method 17: The map is then coerced to the interface (the same as someMap as PageNodeListener). Notice that if it didn’t contain an entry for a method then it would throw a NullPointerException if the method was invoked on the stub. Notice that this version is more flexible than the Groovy-only one because we have full access to java.lang.reflect.Method when we create the map and thus can adjust the return value of the method closure w.r.t. what is expected. Thus it’s possible to stub any interface, even if it has methods returning primitive types. Conclusion This is a nice and simple way to stub an interface with methods that are void or return non-primitive values and collect all calls to the stub for a verification. If your requirements differ then you might be better of with a different type of mocking in Groovy or with a true mocking library. Additional Information Groovy version: 1.8.2, Java: 6.0. See the full source code in the JSF EL Validator’s NotifyingCompilationManagerTest.groovy. From http://theholyjava.wordpress.com/2011/11/02/groovy-creating-interface-stub-and-intercepting-all-calls-to-it/
November 4, 2011
by Jakub Holý
· 6,653 Views
article thumbnail
The sampling theorem explained with numpy
The sampling theorem states that a continuous signal x(t) bandlimited to B Hz can be recovered from its samples x[n] = x(n*T), where n is an integer, if T is greater than or equal to 1/(2B) without loss of any information. And we call 2B the Nyquist rate. Sampling at a rate below the Nyquist rate is called undersampling, it leads to the aliasing effect. Let's observe the aliasing effect with the following Python script: from numpy import linspace,cos,pi,ceil,floor,arange from pylab import plot,show,axis # sampling a signal badlimited to 40 Hz # with a sampling rate of 800 Hz f = 40; # Hz tmin = -0.3; tmax = 0.3; t = linspace(tmin, tmax, 400); x = cos(2*pi*t) + cos(2*pi*f*t); # signal sampling plot(t, x) # sampling the signal with a sampling rate of 80 Hz # in this case, we are using the Nyquist rate. T = 1/80.0; nmin = ceil(tmin / T); nmax = floor(tmax / T); n = arange(nmin,nmax); x1 = cos(2*pi*n*T) + cos(2*pi*f*n*T); plot(n*T, x1, 'bo') # sampling the signal with a sampling rate of 35 Hz # note that 35 Hz is under the Nyquist rate. T = 1/35.0; nmin = ceil(tmin / T); nmax = floor(tmax / T); n = arange(nmin,nmax); x2 = cos(2*pi*n*T) + cos(2*pi*f*n*T); plot(n*T, x2, '-r.',markersize=8) axis([-0.3, 0.3, -1.5, 2.3]) show() The following figure is the result: The blue curve is the original signal, the blue dots are the samples obtained with the Nyquist rate and the red dots are the samples obtainde with 35 Hz. It's easy to see that the blue samples are enough to recover the blue curve, while the red ones are not enough to capture the oscillations of the signal.
November 2, 2011
by Giuseppe Vettigli
· 7,583 Views
  • Previous
  • ...
  • 1597
  • 1598
  • 1599
  • 1600
  • 1601
  • 1602
  • 1603
  • 1604
  • 1605
  • 1606
  • ...
  • Next
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook
×