Search Results

Search found 18 results on 1 pages for 'romeo'.

Page 1/1 | 1 

  • Optimizing collision engine bottleneck

    - by Vittorio Romeo
    Foreword: I'm aware that optimizing this bottleneck is not a necessity - the engine is already very fast. I, however, for fun and educational purposes, would love to find a way to make the engine even faster. I'm creating a general-purpose C++ 2D collision detection/response engine, with an emphasis on flexibility and speed. Here's a very basic diagram of its architecture: Basically, the main class is World, which owns (manages memory) of a ResolverBase*, a SpatialBase* and a vector<Body*>. SpatialBase is a pure virtual class which deals with broad-phase collision detection. ResolverBase is a pure virtual class which deals with collision resolution. The bodies communicate to the World::SpatialBase* with SpatialInfo objects, owned by the bodies themselves. There currenly is one spatial class: Grid : SpatialBase, which is a basic fixed 2D grid. It has it's own info class, GridInfo : SpatialInfo. Here's how its architecture looks: The Grid class owns a 2D array of Cell*. The Cell class contains two collection of (not owned) Body*: a vector<Body*> which contains all the bodies that are in the cell, and a map<int, vector<Body*>> which contains all the bodies that are in the cell, divided in groups. Bodies, in fact, have a groupId int that is used for collision groups. GridInfo objects also contain non-owning pointers to the cells the body is in. As I previously said, the engine is based on groups. Body::getGroups() returns a vector<int> of all the groups the body is part of. Body::getGroupsToCheck() returns a vector<int> of all the groups the body has to check collision against. Bodies can occupy more than a single cell. GridInfo always stores non-owning pointers to the occupied cells. After the bodies move, collision detection happens. We assume that all bodies are axis-aligned bounding boxes. How broad-phase collision detection works: Part 1: spatial info update For each Body body: Top-leftmost occupied cell and bottom-rightmost occupied cells are calculated. If they differ from the previous cells, body.gridInfo.cells is cleared, and filled with all the cells the body occupies (2D for loop from the top-leftmost cell to the bottom-rightmost cell). body is now guaranteed to know what cells it occupies. For a performance boost, it stores a pointer to every map<int, vector<Body*>> of every cell it occupies where the int is a group of body->getGroupsToCheck(). These pointers get stored in gridInfo->queries, which is simply a vector<map<int, vector<Body*>>*>. body is now guaranteed to have a pointer to every vector<Body*> of bodies of groups it needs to check collision against. These pointers are stored in gridInfo->queries. Part 2: actual collision checks For each Body body: body clears and fills a vector<Body*> bodiesToCheck, which contains all the bodies it needs to check against. Duplicates are avoided (bodies can belong to more than one group) by checking if bodiesToCheck already contains the body we're trying to add. const vector<Body*>& GridInfo::getBodiesToCheck() { bodiesToCheck.clear(); for(const auto& q : queries) for(const auto& b : *q) if(!contains(bodiesToCheck, b)) bodiesToCheck.push_back(b); return bodiesToCheck; } The GridInfo::getBodiesToCheck() method IS THE BOTTLENECK. The bodiesToCheck vector must be filled for every body update because bodies could have moved meanwhile. It also needs to prevent duplicate collision checks. The contains function simply checks if the vector already contains a body with std::find. Collision is checked and resolved for every body in bodiesToCheck. That's it. So, I've been trying to optimize this broad-phase collision detection for quite a while now. Every time I try something else than the current architecture/setup, something doesn't go as planned or I make assumption about the simulation that later are proven to be false. My question is: how can I optimize the broad-phase of my collision engine maintaining the grouped bodies approach? Is there some kind of magic C++ optimization that can be applied here? Can the architecture be redesigned in order to allow for more performance? Actual implementation: SSVSCollsion Body.h, Body.cpp World.h, World.cpp Grid.h, Grid.cpp Cell.h, Cell.cpp GridInfo.h, GridInfo.cpp

    Read the article

  • Box2D how to implement a camera?

    - by Romeo
    By now i have this Camera class. package GameObjects; import main.Main; import org.jbox2d.common.Vec2; public class Camera { public int x; public int y; public int sx; public int sy; public static final float PIXEL_TO_METER = 50f; private float yFlip = -1.0f; public Camera() { x = 0; y = 0; sx = x + Main.APPWIDTH; sy = y + Main.APPHEIGHT; } public Camera(int x, int y) { this.x = x; this.y = y; sx = x + Main.APPWIDTH; sy = y + Main.APPHEIGHT; } public void update() { sx = x + Main.APPWIDTH; sy = y + Main.APPHEIGHT; } public void moveCam(int mx, int my) { if(mx >= 0 && mx <= 80) { this.x -= 2; } else if(mx <= Main.APPWIDTH && mx >= Main.APPWIDTH - 80) { this.x += 2; } if(my >= 0 && my <= 80) { this.y += 2; } else if(my <= Main.APPHEIGHT && my >= Main.APPHEIGHT - 80) { this.y -= 2; } this.update(); } public float meterToPixel(float meter) { return meter * PIXEL_TO_METER; } public float pixelToMeter(float pixel) { return pixel / PIXEL_TO_METER; } public Vec2 screenToWorld(Vec2 screenV) { return new Vec2(screenV.x + this.x, yFlip * screenV.y + this.y); } public Vec2 worldToScreen(Vec2 worldV) { return new Vec2(worldV.x - this.x, yFlip * worldV.y - this.y); } } I need to know how to modify the screenToWorld and worldToScreen functions to include the PIXEL_TO_METER scaling.

    Read the article

  • How do I implement smooth movement in a Box2D platform game?

    - by Romeo
    I have implemented a character in JBox2D which moves with the help of a wheel rotating at the bottom of it. The movement is the best result I've had 'till now but it's a little glitchy when the character stands on the edge. So I am thinking should I use five smaller wheels instead of a big wheel. The wheel/wheels will not be visible in the finished product, now they are drawn for debugging. Here is a video. Is there a better way to do this using JBox2D?

    Read the article

  • Slick & NiftyGUI. Nifty initialize exception

    - by Romeo
    I found my self into trouble when trying to run a Slick game with a Nifty Game State. This is the code: @Override protected void initGameAndGUI(GameContainer container, StateBasedGame game) throws SlickException { initNifty(container, game); } If i run this i get: java.lang.IllegalStateException: The NiftyGUI was already initialized. Its illegal to do so twice. If i delete the call to initNifty() i get another exception:java.lang.IllegalStateException: NiftyGUI was not initialized.

    Read the article

  • How to modify VBO data

    - by Romeo
    I am learning LWJGL so i can start working on my game. In order to learn LWJGL I got the idea to implement the map builder so I can get comfortable with graphics programming. Now, for the map creation tool I need to draw new elements or draw the old one's with different coordinates. Let me explain this: My game will be a 2D scroller. The map will be consisting of multiple rectangles ( 2 strip triangles). When I click my left-mouse button i want to start the rectangle and when I release it I want to stop the rectangle bottom-right at that position. As I want to use VBOs I want to know how to modify data inside the VBO based on user input. Should i have a copy of a vertex array and then add the whole array to the VBO at each user input? How is usually implemented the VBO update?

    Read the article

  • Rules for Naming

    - by PointsToShare
    © 2011 By: Dov Trietsch. All rights reserved Naming Documents (or is it “Document, Naming”?) Tis but thy name that is my enemy; Thou art thyself, though not a Montague. What's Montague? It is nor hand, nor foot, Nor arm, nor face, nor any other part Belonging to a man. O, be some other name! What's in a name? That which we call a rose By any other name would smell as sweet; So Romeo would, were he not Romeo call'd, Retain that dear perfection which he owes Without that title. Romeo, doff thy name And for that name which is no part of thee Take all myself.  Shakespeare – Romeo and Juliet Act II, Scene 2 We normally only use the bold portion of the famous Shakespearean quote above, but it is really out of context. As the play unfolds, we learn that a name is all too powerful. Indeed it is because of their names that the doomed lovers die. There might be life and death in a name (BTW, when I wrote this monogram, I was in Hatfield, PA. Remember the Hatfields and the McCoys?) This is a bit extreme, but in the field of Knowledge Management (KM) names are of the utmost importance as well. When I write an article about managing SharePoint sites, how should I name it? “Managing a site” or “Site, managing”? Nine times out of ten I’d opt for the latter. Almost everything we do is “Managing” so to make life easier for a person looking for meaningful content, we title our articles starting with the differentiator rather than the common factor. As a rule of thumb, we start the name with the noun rather than the verb. It is not what we do that is the primary key; it is what we do it to. So, answer this – is it a “rule of thumb” or a “thumb rule?” This is tough. A lot of what we do when naming is a judgment call. Both thumb and rule are nouns, albeit concrete and abstract (more about this later), but to most people “thumb rule” is meaningless while “rule of thumb” is an idiom. The difference between knowledge and information is that knowledge is meaningful information placed in context. Thus I elect the “rule of thumb”. It is the more meaningful title. Abstract and Concrete are relative terms. Many nouns (and verbs) that are abstract to a commoner, are concrete to a practitioner of one profession or another and may even have different concrete meanings in different professional jargons. Think about “running”. To an executive it means running a business, to a marathoner its meaning is much more literal. Generally speaking, we store and disseminate knowledge within a practice more than we do it in general. Even dictionaries encyclopedias define terms as they apply to different audiences. The rule of thumb is to put the more concrete first, but within the audience’s jargon. Even the title of this monogram is a question. Do I name it “Naming Documents” or “Documents, Naming”? Well, my own rule of thumb (“Here he goes again!?”) states that the latter is better because it starts with a noun, but this is a document about naming more than it about documents. The rules of naming also apply to graphs and charts, excel spreadsheets, and so on. Thus, I vote for the former.  A better title could have been “Naming Objects” only the word “Object” is a bit too abstract. How about just “Naming” or “Naming, rules of”? You get the drift. One of the ways to resolve all of this is to store the documents in Knowledge-Bases, which may become the subjects of a future punditry. Knowledge bases use keywords to describe their content.  Use a Metadata store for the keywords to at least attempt some common grounds. Here is another general rule (rule of thumb?!!) – put at least the one keyword in the title. Use subtitles. Here is an example: Migrating documents – Screening, cleaning, and organizing our knowledge. The main keyword is “documents”, next is “migrating”, other keywords also appear in the subtitle. They are “screening”, “cleaning”, and “organizing”. Any questions? Send me an amply named document by email: [email protected]

    Read the article

  • vbscript help needed [migrated]

    - by Romeo
    I am trying to move a group of files with in a group of folders named recup_dir.1 through recup_dir.535 into a single folder so that all the files will be out of the folders and just in the single folder. I know I will need to use a loop to move the files and probably concatenation to go from recup_dir.1 to recup_dir.535 but I just am not that skilled in programming please help!! I just want it to automate the copying and moving of the files rather than do it manually.

    Read the article

  • Box2D platformer movement. Should i mess with velocity?

    - by Romeo
    I have a platformer game in which I implemented the movement using a wheel attached to the hero. For jumping I use this: player.body.applyLinearImpulse(new Vec2(0, 30000000), player.body.getPosition()); The problem is that the xVelocity doesn't remain the same during the jump so it isn't looking natural. Is there any way to modify only the x velocity of the body so that before jumping I store it in a variable and after jumping I apply it to the body? I hope you understand what I am trying to say.

    Read the article

  • Box2D platformer movement. Are joints a good idea?

    - by Romeo
    So i smashed my brains trying to make my character move. As i wanted later in the game to add explosions and bullets it wasn't a good idea to mess with the velocity and the forces/impulses didn't work as i expected so something stuck in my mind: Is it a good idea to put at his bottom a wheel(circle) which is invisible to the player that will do the movement by rotation? I will attach this to my main body with a revolute joint but i don't really know how to make the main body and wheel body to don't collide one with each other since funny things can happen. What is your oppinion?

    Read the article

  • JBox2D applyLinearImpulse doesn't work

    - by Romeo
    So i have this line of code: if(input.isKeyDown(Input.KEY_W)&&canJump()) { body.applyLinearImpulse(new Vec2(0, 30), cam.screenToWorld(body.getPosition())); System.out.println("I can jump!"); } My problem is that the console display I can jump! but the body doesn't do that. Can you explain to me if i do something wrong? Some more code. This function creates my 'hero' the one supposed to jump. private Body setDynamic(float width, float height, float x, float y) { PolygonShape shape = new PolygonShape(); shape.setAsBox(width/2, height/2); BodyDef bd = new BodyDef(); bd.allowSleep = true; bd.position = new Vec2(cam.screenToWorld(new Vec2(x + width / 2, y + height / 2))); bd.type = BodyType.DYNAMIC; bd.userData = new BodyInfo(width, height); Body body = world.createBody(bd); body.createFixture(shape, 10); return body; } And this is the main update loop: if(input.isKeyDown(Input.KEY_A)) { body.setLinearVelocity(new Vec2(-10*delta, body.getLinearVelocity().y)); } else if (input.isKeyDown(Input.KEY_D)) { body.setLinearVelocity(new Vec2(10*delta, body.getLinearVelocity().y)); } else { body.setLinearVelocity(new Vec2(0, body.getLinearVelocity().y)); } if(input.isKeyDown(Input.KEY_W)&&canJump()) { body.applyLinearImpulse(new Vec2(0, 30), body.getPosition()); System.out.println("I can jump!"); } world.step(delta * 0.001f, 10, 5); }

    Read the article

  • UISplitViewController, animating views

    - by Romeo Robles
    Hello, I'm trying to animate my detail view controller to transition with a page curl (up/down). I'm trying to achieve a similar effect as the Notes application on the iPad, this transition was also reproduced by CulturedCode in their Things application for iPad. My problem is that the animation is clipped to the bounds of the Detail View Controller, it doesn't animate into the Master View Controller, therefore limiting the effect. I see that Apple and CulturedCode managed to make this happen, but I'm stumped. I've tried the following solutions: self.splitViewController.view.clipToBounds = False; self.view.clipToBounds = False; self.tableView.clipToBounds = False; The only other solution I can think of is discarding the UISplitViewController altogether and creating my own VC programmatically that will mimic the UISVC behavior so that both of the views (former separate view controllers) will share the same Super View. Thank you in advance, any advice will help. RR.

    Read the article

  • Ajax call in a jQuery plugin not working properly

    - by Saneef
    I'm trying to create a jQuery plugin, inside I need to do an AJAX call to load an xml. jQuery.fn.imagetags = function(options) { s = jQuery.extend({ height:null, width:null, url:false, callback:null, title:null, }, options); return this.each(function(){ obj = $(this); //Initialising the placeholder $holder = $('<div />') .width(s.width).height(s.height) .addClass('jimageholder') .css({ position: 'relative', }); obj.wrap($holder); $.ajax({ type: "GET", url: s.url, dataType: "xml", success:function(data){ initGrids(obj,data,s.callback,s.title); } , error: function(data) { alert("Error loading Grid data."); }, }); function initGrids(obj, data,callback,gridtitle){ if (!data) { alert("Error loading Grid data"); } $("gridlist gridset",data).each(function(){ var gridsetname = $(this).children("setname").text(); var gridsetcolor = ""; if ($(this).children("color").text() != "") { gridsetcolor = $(this).children("color").text(); } $(this).children("grid").each(function(){ var gridcolor = gridsetcolor; //This colour will override colour set for the grid set if ($(this).children("color").text() != "") { gridcolor = $(this).children("color").text(); } //addGrid(gridsetname,id,x,y,height,width) addGrid( obj, gridsetname, $(this).children("id").text(), $(this).children("x").text(), $(this).children("y").text(), $(this).children("height").text(), $(this).children("width").text(), gridcolor, gridtitle ); }); }); } function addGrid(obj,gridsetname,id,x,y,height,width,color,gridtitle){ //To compensate for the 2px border height-=4; width-=4; $grid = $('<div />') .addClass(gridsetname) .attr("id",id) .addClass('gridtag') .imagetagsResetHighlight() .css({ "bottom":y+"px", "left":x+"px", "height":height+"px", "width":width+"px", }); if(gridtitle != null){ $grid.attr("title",gridtitle); } if(color != ""){ $grid.css({ "border-color":color, }); } obj.after($grid); } }); } The above plugin I bind with 2 DOM objects and loads two seperate XML files but the callback function is run only on the last DOM object using both loaded XML files. How can I fix this, so that the callback is applied on the corresponding DOMs. Is the above ajax call is correct? Sample usage: <script type="text/javascript"> $(function(){ $(".romeo img").imagetags({ height:500, width:497, url: "sample-data.xml", title: "Testing...", callback:function(id){ console.log(id); }, }); }); </script> <div class="padding-10 min-item background-color-black"> <div class="romeo"><img src="images/samplecontent/test_500x497.gif" alt="Image"> </div> </div> <script type="text/javascript"> $(function(){ $(".romeo2 img").imagetags({ height:500, width:497, url: "sample-data2.xml", title: "Testing...", callback:function(id){ console.log(id); }, }); }); </script> <div class="padding-10 min-item background-color-black"> <div class="romeo2"><img src="images/samplecontent/test2_500x497.gif" alt="Image"> </div> </div> Here is the sample XML data: <?xml version="1.0" encoding="utf-8"?> <gridlist> <gridset> <setname>gridset4</setname> <color>#00FF00</color> <grid> <color>#FF77FF</color> <id>grid2-324</id> <x>300</x> <y>300</y> <height>60</height> <width>60</width> </grid> </gridset> <gridset> <setname>gridset3</setname> <color>#00FF00</color> <grid> <color>#FF77FF</color> <id>grid2-212</id> <x>300</x> <y>300</y> <height>100</height> <width>100</width> </grid> <grid> <color>#FF77FF</color> <id>grid2-1212</id> <x>200</x> <y>10</y> <height>200</height> <width>10</width> </grid> </gridset> </gridlist>

    Read the article

  • extra padding/Margin in Firefox+CHrome None in IE

    - by Adi
    There is 20px margin/padding below the catmenuconatiner (second navigation bar). This is only showing in firefox and chrome not in IE 6+ Here is the page: www.fish-and-web.blogspot.com Another problem related to the same issue is between the comments. The comment boxes have 15px margin between them. Again, this is only showing in Firefox and Chrome not in IE6+ Here is the comment page: http://fish-and-web.blogspot.com/2010/05/alfa-romeo-9c_24.html It'd be great if someone comes along and guide me in the right direction. I have been working on this for hours and I just cannot get it to work. Just so you know that the page is hosted on blogger. Thank you.

    Read the article

  • Pythonic mapping of an array (Beginner)

    - by scott_karana
    Hey StackOverflow, I've got a question related to a beginner Python snippet I've written to introduce myself to the language. It's an admittedly trivial early effort, but I'm still wondering how I could have written it more elegantly. The program outputs NATO phoenetic readable versions of an argument, such "H2O" - "Hotel 2 Oscar", or (lacking an argument) just outputs the whole alphabet. I mainly use it for calling in MAC addresses and IQNs, but it's useful for other phone support too. Here's the body of the relevant portion of the program: #!/usr/bin/env python import sys nato = { "a": 'Alfa', "b": 'Bravo', "c": 'Charlie', "d": 'Delta', "e": 'Echo', "f": 'Foxtrot', "g": 'Golf', "h": 'Hotel', "i": 'India', "j": 'Juliet', "k": 'Kilo', "l": 'Lima', "m": 'Mike', "n": 'November', "o": 'Oscar', "p": 'Papa', "q": 'Quebec', "r": 'Romeo', "s": 'Sierra', "t": 'Tango', "u": 'Uniform', "v": 'Victor', "w": 'Whiskey', "x": 'Xray', "y": 'Yankee', "z": 'Zulu', } if len(sys.argv) < 2: for n in nato.keys(): print nato[n] else: # if sys.argv[1] == "-i" # TODO for char in sys.argv[1].lower(): if char in nato: print nato[char], else: print char, As I mentioned, I just want to see suggestions for a more elegant way to code this. My first guess was to use a list comprehension along the lines of [nato[x] for x in sys.argv[1].lower() if x in nato], but that doesn't allow me to output any non-alphabetic characters. My next guess was to use map, but I couldn't format any lambdas that didn't suffer from the same corner case. Any suggestions? Maybe something with first-class functions? Messing with Array's guts? This seems like it could almost be a Code Golf question, but I feel like I'm just overthinking :)

    Read the article

  • Regex issue with comma's telling me there are 6 args, instead of intended 4

    - by Azher
    I have a scenario outline table that looks like the following: Scenario Outline: Verify Full ad details Given I am on the xxx classified home page And I have entered <headline> in the search field & clicked on search When I click on full details Then I should see <headline> <year> <mileage> <price> displaying correctly and successfully Examples: |headline |year |mileage |price | |alfa romeo 166 |2005 |73,000 |6,990 | When I run my scenario it spits out that I have 6 args. But what I thought, I should only have 4 args: headline, year, mileage and price. I am thinking that it is taking the comma's and what is before and after it as two seperate args. Is there any way that I can make cucumber think that there are only 4 args with the example below? I have looked at messing around with regex but I dont seem to be getting anywhere. Any help would be greatly appreciated.

    Read the article

  • International Radio Operators Alphabet in F# &amp; Silverlight &ndash; Part 1

    - by MarkPearl
    So I have been delving into F# more and more and thought the best way to learn the language is to write something useful. I have been meaning to get some more Silverlight knowledge (up to now I have mainly been doing WPF) so I came up with a really simple project that I can actually use at work. Simply put – I often get support calls from clients wanting new activation codes. One of our main app’s was written in VB6 and had its own “security” where it would require about a 45 character sequence for it to be activated. The catch being that each time you reopen the program it would require a different character sequence, which meant that when we activate clients systems we have to do it live! This involves us either referring them to a website, or reading the characters to them over the phone and since nobody in the office knows the IROA off by heart we would come up with some interesting words to represent characters… 9 times out of 10 the client would type in the wrong character and we would have to start all over again… with this app I am hoping to reduce the errors of reading characters over the phone by treating it like a ham radio. My “Silverlight” application will allow for the user to input a series of characters and the system will then generate the equivalent IROA words… very basic stuff e.g. Character Input – abc Words Generated – Alpha Bravo Charlie After listening to Anders Hejlsberg on Dot Net Rocks Show 541 he mentioned that he felt many applications could make use of F# but in an almost silo basis – meaning that you would write modules that leant themselves to Functional Programming in F# and then incorporate it into a solution where the front end may be in C# or where you would have some other sort of glue. I buy into this kind of approach, so in this project I will use F# to do my very intensive “Business Logic” and will use Silverlight/C# to do the front end. F# Business Layer I am no expert at this, so I am sure to get some feedback on way I could improve my algorithm. My approach was really simple. I would need a function that would convert a single character to a string – i.e. ‘A’ –> “Alpha” and then I would need a function that would take a string of characters, convert them into a sequence of characters, and then apply my converter to return a sequence of words… make sense? Lets start with the CharToString function let CharToString (element:char) = match element.ToString().ToLower() with | "1" -> "1" | "5" -> "5" | "9" -> "9" | "2" -> "2" | "6" -> "6" | "0" -> "0" | "3" -> "3" | "7" -> "7" | "4" -> "4" | "8" -> "8" | "a" -> "Alpha" | "b" -> "Bravo" | "c" -> "Charlie" | "d" -> "Delta" | "e" -> "Echo" | "f" -> "Foxtrot" | "g" -> "Golf" | "h" -> "Hotel" | "i" -> "India" | "j" -> "Juliet" | "k" -> "Kilo" | "l" -> "Lima" | "m" -> "Mike" | "n" -> "November" | "o" -> "Oscar" | "p" -> "Papa" | "q" -> "Quebec" | "r" -> "Romeo" | "s" -> "Sierra" | "t" -> "Tango" | "u" -> "Uniform" | "v" -> "Victor" | "w" -> "Whiskey" | "x" -> "XRay" | "y" -> "Yankee" | "z" -> "Zulu" | element -> "Unknown" Quite simple, an element is passed in, this element is them converted to a lowercase single character string and then matched up with the equivalent word. If by some chance a character is not recognized, “Unknown” will be returned… I know need a function that can take a string and can parse each character of the string and generate a new sequence with the converted words… let ConvertCharsToStrings (s:string) = s |> Seq.toArray |> Seq.map(fun elem -> CharToString(elem)) Here… the Seq.toArray converts the string to a sequence of characters. I then searched for some way to parse through every element in the sequence. Originally I tried Seq.iter, but I think my understanding of what iter does was incorrect. Eventually I found Seq.map, which applies a function to every element in a sequence and then creates a new collection with the adjusted processed element. It turned out to be exactly what I needed… To test that everything worked I created one more function that parsed through every element in a sequence and printed it. AT this point I realized the the Seq.iter would be ideal for this… So my testing code is below… let PrintStrings items = items |> Seq.iter(fun x -> Console.Write(x.ToString() + " ")) let newSeq = ConvertCharsToStrings("acdefg123") PrintStrings newSeq Console.ReadLine()   Pretty basic stuff I guess… I hope my approach was right? In Part 2 I will look into doing a simple Silverlight Frontend, referencing the projects together and deploying….

    Read the article

  • Getting Started with Amazon Web Services in NetBeans IDE

    - by Geertjan
    When you need to connect to Amazon Web Services, NetBeans IDE gives you a nice start. You can drag and drop the "itemSearch" service into a Java source file and then various Amazon files are generated for you. From there, you need to do a little bit of work because the request to Amazon needs to be signed before it can be used. Here are some references and places that got me started: http://associates-amazon.s3.amazonaws.com/signed-requests/helper/index.html http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSGettingStartedGuide/AWSCredentials.html https://affiliate-program.amazon.com/gp/flex/advertising/api/sign-in.html You definitely need to sign up to the Amazon Associates program and also register/create an Access Key ID, which will also get you a Secret Key, as well. Here's a simple Main class that I created that hooks into the generated RestConnection/RestResponse code created by NetBeans IDE: public static void main(String[] args) {    try {        String searchIndex = "Books";        String keywords = "Romeo and Juliet";        RestResponse result = AmazonAssociatesService.itemSearch(searchIndex, keywords);        String dataAsString = result.getDataAsString();        int start = dataAsString.indexOf("<Author>")+8;        int end = dataAsString.indexOf("</Author>");        System.out.println(dataAsString.substring(start,end));    } catch (Exception ex) {        ex.printStackTrace();    }} Then I deleted the generated properties file and the authenticator and changed the generated AmazonAssociatesService.java file to the following: public class AmazonAssociatesService {    private static void sleep(long millis) {        try {            Thread.sleep(millis);        } catch (Throwable th) {        }    }    public static RestResponse itemSearch(String searchIndex, String keywords) throws IOException {        SignedRequestsHelper helper;        RestConnection conn = null;        Map queryMap = new HashMap();        queryMap.put("Service", "AWSECommerceService");        queryMap.put("AssociateTag", "myAssociateTag");        queryMap.put("AWSAccessKeyId", "myAccessKeyId");        queryMap.put("Operation", "ItemSearch");        queryMap.put("SearchIndex", searchIndex);        queryMap.put("Keywords", keywords);        try {            helper = SignedRequestsHelper.getInstance(                    "ecs.amazonaws.com",                    "myAccessKeyId",                    "mySecretKey");            String sign = helper.sign(queryMap);            conn = new RestConnection(sign);        } catch (IllegalArgumentException | UnsupportedEncodingException | NoSuchAlgorithmException | InvalidKeyException ex) {        }        sleep(1000);        return conn.get(null);    }} Finally, I copied this class into my application, which you can see is referred to above: http://code.google.com/p/amazon-product-advertising-api-sample/source/browse/src/com/amazon/advertising/api/sample/SignedRequestsHelper.java Here's the completed app, mostly generated via the drag/drop shown at the start, but slightly edited as shown above: That's all, now everything works as you'd expect.

    Read the article

  • How do you get Matlab to write the BOM (byte order markers) for UTF-16 text files?

    - by Richard Povinelli
    I am creating UTF16 text files with Matlab, which I am later reading in using Java. In Matlab, I open a file called fileName and write to it as follows: fid = fopen(fileName, 'w','n','UTF16-LE'); fprintf(fid,"Some stuff."); In Java, I can read the text file using the following code: FileInputStream fileInputStream = new FileInputStream(fileName); Scanner scanner = new Scanner(fileInputStream, "UTF-16LE"); String s = scanner.nextLine(); Here is the hex output: Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 00000000 73 00 6F 00 6D 00 65 00 20 00 73 00 74 00 75 00 66 00 66 00 s.o.m.e. .s.t.u.f.f. The above approach works fine. But, I want to be able to write out the file using UTF16 with a BOM to give me more flexibility so that I don't have to worry about big or little endian. In Matlab, I've coded: fid = fopen(fileName, 'w','n','UTF16'); fprintf(fid,"Some stuff."); In Java, I change the code to: FileInputStream fileInputStream = new FileInputStream(fileName); Scanner scanner = new Scanner(fileInputStream, "UTF-16"); String s = scanner.nextLine(); In this case, the string s is garbled, because Matlab is not writing the BOM. I can get the Java code to work just fine if I add the BOM manually. With the added BOM, the following file works fine. Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 14 15 00000000 FF FE 73 00 6F 00 6D 00 65 00 20 00 73 00 74 00 75 00 66 00 66 00 ÿþs.o.m.e. .s.t.u.f.f. How can I get Matlab to write out the BOM? I know I could write the BOM out separately, but I'd rather have Matlab do it automatically. Addendum I selected the answer below from Amro because it exactly solves the question I posed. One key discovery for me was the difference between the Unicode Standard and a UTF (Unicode transformation format) (see http://unicode.org/faq/utf_bom.html). The Unicode Standard provides unique identifiers (code points) for characters. UTFs provide mappings of every code point "to a unique byte sequence." Since all but a handful of the characters I am using are in the first 128 code points, I'm going to switch to using UTF-8 as Romeo suggests. UTF-8 is supported by Matlab (The warning shown below won't need to be suppressed.) and Java, and for my application will generate smaller text files. I suppress the Matlab warning Warning: The encoding 'UTF-16LE' is not supported. with warning off MATLAB:iofun:UnsupportedEncoding;

    Read the article

1