Search Results

Search found 634 results on 26 pages for 'orange peel'.

Page 23/26 | < Previous Page | 19 20 21 22 23 24 25 26  | Next Page >

  • Why keylistener is not working here?

    - by swift
    i have implemented keylistener interface and implemented all the needed methods but when i press the key nothing happens here, why? package swing; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.Point; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLayeredPane; import javax.swing.JPanel; import javax.swing.JTextArea; class Paper extends JPanel implements MouseListener,MouseMotionListener,ActionListener,KeyListener { static BufferedImage image; String shape; Color color=Color.black; Point start; Point end; Point mp; Button elipse=new Button("elipse"); int x[]=new int[50]; int y[]=new int[50]; Button rectangle=new Button("rect"); Button line=new Button("line"); Button roundrect=new Button("roundrect"); Button polygon=new Button("poly"); Button text=new Button("text"); ImageIcon erasericon=new ImageIcon("images/eraser.gif"); JButton erase=new JButton(erasericon); JButton[] colourbutton=new JButton[9]; String selected; Point label; String key; int ex,ey;//eraser //DatagramSocket dataSocket; JButton button = new JButton("test"); JLayeredPane layerpane; Point p=new Point(); int w,h; public Paper() { JFrame frame=new JFrame("Whiteboard"); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(640, 480); frame.setBackground(Color.black); layerpane=frame.getLayeredPane(); setWidth(539,444); setBounds(69,0,555,444); layerpane.add(this,new Integer(2)); layerpane.add(this.addButtons(),new Integer(0)); setLayout(null); setOpaque(false); addMouseListener(this); addMouseMotionListener(this); setFocusable(true); addKeyListener(this); System.out.println(isFocusable()); setBorder(BorderFactory.createLineBorder(Color.black)); } public void paintComponent(Graphics g) { try { super.paintComponent(g); g.drawImage(image, 0, 0, this); Graphics2D g2 = (Graphics2D)g; if(color!=null) g2.setPaint(color); if(start!=null && end!=null) { if(selected==("elipse")) g2.drawOval(start.x, start.y,(end.x-start.x),(end.y-start.y)); else if(selected==("rect")) g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y)); else if(selected==("rrect")) g2.drawRoundRect(start.x, start.y, (end.x-start.x),(end.y-start.y),11,11); else if(selected==("line")) g2.drawLine(start.x,start.y,end.x,end.y); else if(selected==("poly")) g2.drawPolygon(x,y,2); } } catch(Exception e) {} } //Function to draw the shape on image public void draw() { Graphics2D g2 = image.createGraphics(); g2.setPaint(color); if(start!=null && end!=null) { if(selected=="line") g2.drawLine(start.x, start.y, end.x, end.y); else if(selected=="elipse") g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y)); else if(selected=="rect") g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y)); else if(selected==("rrect")) g2.drawRoundRect(start.x, start.y, (end.x-start.x),(end.y-start.y),11,11); else if(selected==("poly")) g2.drawPolygon(x,y,2); } if(label!=null) { JTextArea textarea=new JTextArea(); if(selected==("text")) { textarea.setBounds(label.x, label.y, 50, 50); textarea.setMaximumSize(new Dimension(100,100)); textarea.setBackground(new Color(237,237,237)); add(textarea); g2.drawString("key",label.x,label.y); } } start=null; repaint(); g2.dispose(); } public void text() { System.out.println(label); } //Function which provides the erase functionality public void erase() { Graphics2D pic=(Graphics2D) image.getGraphics(); Color erasecolor=new Color(237,237,237); pic.setPaint(erasecolor); if(start!=null) pic.fillRect(start.x, start.y, 10, 10); } //To set the size of the image public void setWidth(int x,int y) { System.out.println("("+x+","+y+")"); w=x; h=y; image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); } //Function to add buttons into the panel, calling this function returns a panel public JPanel addButtons() { JPanel buttonpanel=new JPanel(); buttonpanel.setMaximumSize(new Dimension(70,70)); JPanel shape=new JPanel(); JPanel colourbox=new JPanel(); shape.setLayout(new GridLayout(4,2)); shape.setMaximumSize(new Dimension(70,140)); colourbox.setLayout(new GridLayout(3,3)); colourbox.setMaximumSize(new Dimension(70,70)); buttonpanel.setLayout(new BoxLayout(buttonpanel,BoxLayout.Y_AXIS)); elipse.addActionListener(this); elipse.setToolTipText("Elipse"); rectangle.addActionListener(this); rectangle.setToolTipText("Rectangle"); line.addActionListener( this); line.setToolTipText("Line"); erase.addActionListener(this); erase.setToolTipText("Eraser"); roundrect.addActionListener(this); roundrect.setToolTipText("Round rect"); polygon.addActionListener(this); polygon.setToolTipText("Polygon"); text.addActionListener(this); text.setToolTipText("Text"); shape.add(elipse); shape.add(rectangle); shape.add(line); shape.add(erase); shape.add(roundrect); shape.add(polygon); shape.add(text); buttonpanel.add(shape); for(int i=0;i<9;i++) { colourbutton[i]=new JButton(); colourbox.add(colourbutton[i]); if(i==0) colourbutton[0].setBackground(Color.black); else if(i==1) colourbutton[1].setBackground(Color.white); else if(i==2) colourbutton[2].setBackground(Color.red); else if(i==3) colourbutton[3].setBackground(Color.orange); else if(i==4) colourbutton[4].setBackground(Color.blue); else if(i==5) colourbutton[5].setBackground(Color.green); else if(i==6) colourbutton[6].setBackground(Color.pink); else if(i==7) colourbutton[7].setBackground(Color.magenta); else if(i==8) colourbutton[8].setBackground(Color.cyan); colourbutton[i].addActionListener(this); } buttonpanel.add(colourbox); buttonpanel.setBounds(0, 0, 70, 210); return buttonpanel; } public void mouseClicked(MouseEvent e) { if(selected=="text") { label=new Point(); label=e.getPoint(); draw(); } } @Override public void mouseEntered(MouseEvent arg0) { } public void mouseExited(MouseEvent arg0) { } public void mousePressed(MouseEvent e) { if(selected=="line"||selected=="erase"||selected=="text") { start=e.getPoint(); } else if(selected=="elipse"||selected=="rect"||selected=="rrect") { mp = e.getPoint(); } else if(selected=="poly") { x[0]=e.getX(); y[0]=e.getY(); } } public void mouseReleased(MouseEvent e) { if(start!=null) { if(selected=="line") { end=e.getPoint(); } else if(selected=="elipse"||selected=="rect"||selected=="rrect") { end.x = Math.max(mp.x,e.getX()); end.y = Math.max(mp.y,e.getY()); } else if(selected=="poly") { x[1]=e.getX(); y[1]=e.getY(); } draw(); } } public void mouseDragged(MouseEvent e) { if(end==null) end = new Point(); if(start==null) start = new Point(); if(selected=="line") { end=e.getPoint(); } else if(selected=="erase") { start=e.getPoint(); erase(); } else if(selected=="elipse"||selected=="rect"||selected=="rrect") { start.x = Math.min(mp.x,e.getX()); start.y = Math.min(mp.y,e.getY()); end.x = Math.max(mp.x,e.getX()); end.y = Math.max(mp.y,e.getY()); } else if(selected=="poly") { x[1]=e.getX(); y[1]=e.getY(); } repaint(); } public void mouseMoved(MouseEvent arg0) {} public void actionPerformed(ActionEvent e) { if(e.getSource()==elipse) selected="elipse"; else if(e.getSource()==line) selected="line"; else if(e.getSource()==rectangle) selected="rect"; else if(e.getSource()==erase) { selected="erase"; System.out.println(selected); erase(); } else if(e.getSource()==roundrect) selected="rrect"; else if(e.getSource()==polygon) selected="poly"; else if(e.getSource()==text) selected="text"; if(e.getSource()==colourbutton[0]) color=Color.black; else if(e.getSource()==colourbutton[1]) color=Color.white; else if(e.getSource()==colourbutton[2]) color=Color.red; else if(e.getSource()==colourbutton[3]) color=Color.orange; else if(e.getSource()==colourbutton[4]) color=Color.blue; else if(e.getSource()==colourbutton[5]) color=Color.green; else if(e.getSource()==colourbutton[6]) color=Color.pink; else if(e.getSource()==colourbutton[7]) color=Color.magenta; else if(e.getSource()==colourbutton[8]) color=Color.cyan; } @Override public void keyPressed(KeyEvent e) { System.out.println("pressed"); } @Override public void keyReleased(KeyEvent e) { System.out.println("key released"); } @Override public void keyTyped(KeyEvent e) { System.out.println("Typed"); } public static void main(String[] a) { new Paper(); } } class Button extends JButton { String name; public Button(String name) { this.name=name; } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //g2.setStroke(new BasicStroke(1.2f)); if (name == "line") g.drawLine(5,5,30,30); if (name == "elipse") g.drawOval(5,7,25,20); if (name== "rect") g.drawRect(5,5,25,23); if (name== "roundrect") g.drawRoundRect(5,5,25,23,10,10); int a[]=new int[]{20,9,20,23,20}; int b[]=new int[]{9,23,25,20,9}; if (name== "poly") g.drawPolyline(a, b, 5); if (name== "text") g.drawString("Text",5, 22); } }

    Read the article

  • Blending the Sketchflow Action

    - by GeekAgilistMercenary
    Started a new Sketchflow Prototype in Expression Blend recently and documented each of the steps.  This blog entry covers some of those steps, which are the basic elements of any prototype.  I will have more information regarding design, prototype creation, and the process of the initial phases for development in the future.  For now, I hope you enjoy this short walk through.  Also, be sure to check out my last quick entry on Sketchflow. I started off with a Sketchflow Project, just like I did in my previous entry (more specifics in that entry about how to manipulate and build out the Sketchflow Map). Once I created the project I setup the following Sketchflow Map. The CoreNavigation is a ComponentScreen setup solely for the page navigation at the top of the screen.  The XAML markup in case you want to create a Component Screen with the same design is included below. <UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" xmlns:pb="clr-namespace:Microsoft.Expression.Prototyping.Behavior;assembly=Microsoft.Expression.Prototyping.Interactivity" x:Class="RapidPrototypeSketchScreens.CoreNavigation" d:DesignWidth="624" d:DesignHeight="49" Height="49" Width="624">   <Grid x:Name="LayoutRoot"> <TextBlock HorizontalAlignment="Stretch" Margin="307,3,0,0" Style="{StaticResource TitleCenter-Sketch}" Text="Aütøchart Scorecards" TextWrapping="Wrap"> <i:Interaction.Triggers> <i:EventTrigger EventName="MouseLeftButtonDown"> <pb:NavigateToScreenAction TargetScreen="RapidPrototypeSketchScreens.Screen_1"/> </i:EventTrigger> </i:Interaction.Triggers> </TextBlock> <Button HorizontalAlignment="Left" Margin="164,8,0,11" Style="{StaticResource Button-Sketch}" Width="144" Content="Scorecard"> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <pb:NavigateToScreenAction TargetScreen="RapidPrototypeSketchScreens.Screen_1_2"/> </i:EventTrigger> </i:Interaction.Triggers> </Button> <Button HorizontalAlignment="Left" Margin="8,8,0,11" Style="{StaticResource Button-Sketch}" Width="152" Content="Standard Reports"> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <pb:NavigateToScreenAction TargetScreen="RapidPrototypeSketchScreens.Screen_1_1"/> </i:EventTrigger> </i:Interaction.Triggers> </Button> </Grid> </UserControl> Now that the CoreNavigation Component Screen is done I built out each of the others.  In each of those screens I included the CoreNavigation Screen (all those little green lines in the image) as the top navigation.  In order to do that, as I created each of the pages I would hover over the CoreNavigation Object in the Sketchflow Map.  When the utilities drawer (the small menu that pops down under a node when you hover over it) shows click on the third little icon and drag it onto the page node you want a navigation screen on. Once I created all the screens I setup the navigation by opening up each screen and right clicking on the objects that needed to point to somewhere else in the prototype. Once I was done with the main page, my Home Navigation Page, it looked something like this in the Expression Blend Designer. I fleshed out each of the additional screens.  Once I was done I wanted to try out the deployment package.  The way to deploy a Sketchflow Prototype is to merely click on File –> Package SketchFlow Project and a prompt will appear.  In the prompt enter what you want the package to be called. I like to see the files generated afterwards too, so I checked the box to see that.  When Expression Blend is done generating everything you’ll have a directory like the one shown below, with all the needed files for deployment. Now these files can be copied or moved to any location for viewing.  One can even copy them (such as via FTP) to a server location to share with others.  Once they are deployed and you run the "TestPage.html" the other features of the Sketchflow Package are available. In the image below I have tagged a few sections to show the Sketchflow Player Features.  To the top left is the navigation, which provides a clearly defined area of movement in a list.  To the center right is the actual prototype application.  I have placed lists of things and made edits.  On the left hand side is the highlight feature, which is available in the Feedback section of the lower left.  On the right hand list I underlined the Autochart with an orange marker, and marked out two list items with a red marker. In the lower left hand side in the Feedback section is also an area to type in your feedback.  This can be useful for time based feedback, when you post this somewhere and want people to provide subsequent follow up feedback. Overall lots of great features, that enable some fairly rapid prototyping with customers.  Once one is familiar with the steps and parts of this Sketchflow Prototype Capabilities it is easy to step through an application without even stopping.  It really is that easy.  So get hold of Expression Blend 3 and get ramped up on Sketchflow, it will pay off in the design phases to do so! Original Entry

    Read the article

  • Parallelism in .NET – Part 12, More on Task Decomposition

    - by Reed
    Many tasks can be decomposed using a Data Decomposition approach, but often, this is not appropriate.  Frequently, decomposing the problem into distinctive tasks that must be performed is a more natural abstraction. However, as I mentioned in Part 1, Task Decomposition tends to be a bit more difficult than data decomposition, and can require a bit more effort.  Before we being parallelizing our algorithm based on the tasks being performed, we need to decompose our problem, and take special care of certain considerations such as ordering and grouping of tasks. Up to this point in this series, I’ve focused on parallelization techniques which are most appropriate when a problem space can be decomposed by data.  Using PLINQ and the Parallel class, I’ve shown how problem spaces where there is a collection of data, and each element needs to be processed, can potentially be parallelized. However, there are many other routines where this is not appropriate.  Often, instead of working on a collection of data, there is a single piece of data which must be processed using an algorithm or series of algorithms.  Here, there is no collection of data, but there may still be opportunities for parallelism. As I mentioned before, in cases like this, the approach is to look at your overall routine, and decompose your problem space based on tasks.  The idea here is to look for discrete “tasks,” individual pieces of work which can be conceptually thought of as a single operation. Let’s revisit the example I used in Part 1, an application startup path.  Say we want our program, at startup, to do a bunch of individual actions, or “tasks”.  The following is our list of duties we must perform right at startup: Display a splash screen Request a license from our license manager Check for an update to the software from our web server If an update is available, download it Setup our menu structure based on our current license Open and display our main, welcome Window Hide the splash screen The first step in Task Decomposition is breaking up the problem space into discrete tasks. This, naturally, can be abstracted as seven discrete tasks.  In the serial version of our program, if we were to diagram this, the general process would appear as: These tasks, obviously, provide some opportunities for parallelism.  Before we can parallelize this routine, we need to analyze these tasks, and find any dependencies between tasks.  In this case, our dependencies include: The splash screen must be displayed first, and as quickly as possible. We can’t download an update before we see whether one exists. Our menu structure depends on our license, so we must check for the license before setting up the menus. Since our welcome screen will notify the user of an update, we can’t show it until we’ve downloaded the update. Since our welcome screen includes menus that are customized based off the licensing, we can’t display it until we’ve received a license. We can’t hide the splash until our welcome screen is displayed. By listing our dependencies, we start to see the natural ordering that must occur for the tasks to be processed correctly. The second step in Task Decomposition is determining the dependencies between tasks, and ordering tasks based on their dependencies. Looking at these tasks, and looking at all the dependencies, we quickly see that even a simple decomposition such as this one can get quite complicated.  In order to simplify the problem of defining the dependencies, it’s often a useful practice to group our tasks into larger, discrete tasks.  The goal when grouping tasks is that you want to make each task “group” have as few dependencies as possible to other tasks or groups, and then work out the dependencies within that group.  Typically, this works best when any external dependency is based on the “last” task within the group when it’s ordered, although that is not a firm requirement.  This process is often called Grouping Tasks.  In our case, we can easily group together tasks, effectively turning this into four discrete task groups: 1. Show our splash screen – This needs to be left as its own task.  First, multiple things depend on this task, mainly because we want this to start before any other action, and start as quickly as possible. 2. Check for Update and Download the Update if it Exists - These two tasks logically group together.  We know we only download an update if the update exists, so that naturally follows.  This task has one dependency as an input, and other tasks only rely on the final task within this group. 3. Request a License, and then Setup the Menus – Here, we can group these two tasks together.  Although we mentioned that our welcome screen depends on the license returned, it also depends on setting up the menu, which is the final task here.  Setting up our menus cannot happen until after our license is requested.  By grouping these together, we further reduce our problem space. 4. Display welcome and hide splash - Finally, we can display our welcome window and hide our splash screen.  This task group depends on all three previous task groups – it cannot happen until all three of the previous groups have completed. By grouping the tasks together, we reduce our problem space, and can naturally see a pattern for how this process can be parallelized.  The diagram below shows one approach: The orange boxes show each task group, with each task represented within.  We can, now, effectively take these tasks, and run a large portion of this process in parallel, including the portions which may be the most time consuming.  We’ve now created two parallel paths which our process execution can follow, hopefully speeding up the application startup time dramatically. The main point to remember here is that, when decomposing your problem space by tasks, you need to: Define each discrete action as an individual Task Discover dependencies between your tasks Group tasks based on their dependencies Order the tasks and groups of tasks

    Read the article

  • Knockoutjs - stringify to handling observables and custom events

    - by Renso
    Goal: Once you viewmodel has been built and populated with data, at some point it goal of it all is to persist the data to the database (or some other media). Regardless of where you want to save it, your client-side viewmodel needs to be converted to a JSON string and sent back to the server. Environment considerations: jQuery 1.4.3+ Knockoutjs version 1.1.2   How to: So let’s set the stage, you are using Knockoutjs and you have a viewmodel with some Knockout dependencies. You want to make sure it is in the proper JSON format and via ajax post it to the server for persistence.   First order of business is to deal with the viewmodel (JSON) object. To most the JSON stringifier sounds familiar. The JSON stringifier converts JavaScript data structures into JSON text. JSON does not support cyclic data structures, so be careful to not give cyclical structures to the JSON stringifier. You may ask, is this the best way to do it? What about those observables and other Knockout properties that I don’t want to persist or want their actual value persisted and not their function, etc. Not sure if you were aware, but KO already has a method; ko.utils.stringifyJson() - it's mostly just a wrapper around JSON.stringify. (which is native in some browsers, and can be made available by referencing json2.js in others). What does it do that the regular stringify does not is that it automatically converts observable, dependentObservable, or observableArray to their underlying value to JSON. Hold on! There is a new feature in this version of Knockout, the ko.toJSON. It is part of the core library and it will clone the view model’s object graph, so you don’t mess it up after you have stringified  it and unwrap all its observables. It's smart enough to avoid reference cycles. Since you are using the MVVM pattern it would assume you are not trying to reference DOM nodes from your view. Wait a minute. I can already see this info on the http://knockoutjs.com/examples/contactsEditor.html website, why mention it all here? First of this is a much nicer blog, no orange ? At this time, you may want to have a look at the blog and see what I am talking about. See the save event, how they stringify the view model’s contacts only? That’s cool but what if your view model is a representation of your object you want to persist, meaning it has no property that represents the json object you want to persist, it is the view model itself. The example in http://knockoutjs.com/examples/contactsEditor.html assumes you have a list of contacts you may want to persist. In the example here, you want to persist the view model itself. The viewmodel here looks something like this:     var myViewmodel = {         accountName: ko.observable(""),         accountType: ko.observable("Active")     };     myViewmodel.isItActive = ko.dependentObservable(function () {         return myViewmodel.accountType() == "Active";     });     myViewmodel.clickToSaveMe = function() {         SaveTheAccount();     }; Here is the function in charge of saving the account: Function SaveTheAccount() {     $.ajax({         data: ko.toJSON(viewmodel),         url: $('#ajaxSaveAccountUrl').val(),         type: "POST",         dataType: "json",         async: false,         success: function (result) {             if (result && result.Success == true) {                 $('#accountMessage').html('<span class="fadeMyContainerSlowly">The account has been saved</span>').show();                 FadeContainerAwaySlowly();             }         },         error: function (xmlHttpRequest, textStatus, errorThrown) {             alert('An error occurred: ' + errorThrown);         }     }); //ajax }; Try run this and your browser will eventually freeze up or crash. Firebug will tell you that you have a repetitive call to the first function call in your model that keeps firing infinitely.  What is happening is that Knockout serializes the view model to a JSON string by traversing the object graph and firing off the functions, again-and-again. Not sure why it does that, but it does. So what is the work around: Nullify your function calls and then post it:         var lightweightModel = viewmodel.clickToSaveMe = null;         data: ko.toJSON(lightweightModel), So then I traced the JSON string on the server and found it having issues with primitive types. C#, by the way. So I changed ko.toJSON(model) to ko.toJS(model), and that solved my problem. Of course you could just create a property on the viewmodel for the account itself, so you only have to serialize the property and not the entire viewmodel. If that is an option then that would be the way to go. If your view model contains other properties in the view model that you also want to post then that would not be an option and then you’ll know what to watch out for. Hope this helps.

    Read the article

  • SQL Saturday #44 Huntington Beach Recap

    What a great day. It was long and tiring, but rewarding in so many ways. On Sunday morning, I was driving home and I decided to take the Pacific Coast Highway from Huntington Beach.  It was a great chance to exhale and just enjoy the sun and smells of the beach (I really love SoCal sometimes). And for future reference for all you speakers, the beach and ocean are only 5 minutes from the SQL Saturday location.  I just could help noticing also the shocking number of high priced cars on the road (4 Bentleys, 3 Ferraris, 1 Aston Martins, 3 Maserati, 1 Rolls Royce, and 2 Lamborghinis).  It made me think about this: Price of all those cars: $ 150,000+.  Impacting the ability of people to learn: Priceless.  We have positively impacted the education, knowledge, capabilities of not only our attendees, but also all of their companies and people they might help as well.  That is just staggering and something to be immensely proud of. To all of my fellow community leaders, I salute you. So lets talk about the event Overall We had over 220 people register for the event and had 180+ people attend the event. I was shooting for the magical 200 number, but I guess it just gives us more motivation to make it even bigger and better next time. We had a few snags along the way, but what event doesnt, but I think everything turned out great. I did not hear any negative comments and heard lots of positive comments along with people asking when the next one is going to be (More on that later). Location- Golden West College We could not have asked for a better partner for the event. Herb Cohen from Golden West College was the wizard behind the curtains. From the beginning, he was our advocate to the GWC Board and was instrumental in getting our event approved. The day off, Herb was a HUGE help getting any and all logistics that we needed taken care of. In the craziness of the early morning registration crush it was a big help knowing that he and Bret Stateham (Blog | Twitter) were taking care of testing projectors in all the rooms. Anything we needed he was there and was even proactive in getting some things that I had not even thought of (i.e. a dumpster for all of our garbage). I cannot thank Herb enough along with other members of the GWC staff including Minnie Higgins of the Career and Technical Education Division office, Jack Taylor, public safety, and Ron Pryor, Tech Services Support. And last, but not least, the Wireless on campus was absolutely FANTASTIC! Some lessons learned Unless you are a glutton for punishment, as I no doubt am, you most certainly want to give yourself more than six weeks to plan the event. I am lucky that I have a very understanding wife and had a wonderful set of co-coordinators helping me out. A big thanks goes out to Phil, Marlon (Blog | Twitter), Nitin (Twitter), Thomas (Blog | Twitter), Bret (Blog | Twitter), Ben, and Laurie. Thankfully, the sponsor and speaker community was hugely supportive and we were able to fill out the entire event with speakers and sponsors. I have to say that there is not a lot that I would change after this years event. There are obviously going to be some things that we can do better or differently next time, but overall I think it was a great event and I was more than happy with the response we received from the community. Sponsors We obviously could not have put together our event without our sponsors. So certainly have to show them some love. Platinum Sponsors Quest Software http://www.quest.com My Space http://www.myspace.com/ Gold Strategy Companion http://www.strategycompanion.com Silver Fusion-IO http://www.fusionio.com Bronze WestClinTech http://westclintech.com Professional Association For SQL Server http://www.sqlpass.org Attunity http://www.attunity.com Sharepoint 360 http://www.sharepoint360.com Some additional Thanks Andy Warren (Blog | Twitter) Always there to answer my question and help out when I had some issues or questions with the website. The amount of work that he and everyone else put into SQL Saturday is very amazing. What a great gift to the community! Einstein Bros. Bagels They were our Breakfast Vendor and arrived perfectly on time with yummy bagels, sweets and most importantly coffee. Luccis Deli (http://www.luccisdeli.com) Luccis was out Lunch Vendor. They were great to work with and the food was excellent. They worked with us to give us a great price. Heard lots of great comments about the lunches. Definitely not your ordinary box lunch. Moving Forward Unfortunately, the work does not end after the event. We have a few things to clear up such as surveys, sponsor stuff, presentations uploaded to the website, expense reimbursement, stuff like that. Hopefully, all that should be cleared up within the next couple weeks. After that as a group we are going to get together and decide what our next steps are. We definitely want to keep some of the momentum that we are building as a SQL Community and channel that into future SQL Saturdays and other types of community events. In the meantime, for additional training be sure to check out your local User Group and PASS. San Diego SQL Server Users Group ( http://www.sdsqlug.org/home/index.cfm ) Orange County SQL Server Users Group ( http://www.sqloc.com/ ) L.A. SQL Server Users Group ( http://www.sql.la/ ) SQL PASS ( http://www.sqlpass.org/ ) 24 Hours of PASS ( http://www.sqlpass.org/24hours/2010/ ) So stay tuned, there will be more events to come in SoCal!!Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • What is the most efficient way to convert to binary and back in C#?

    - by Saad Imran.
    I'm trying to write a general purpose socket server for a game I'm working on. I know I could very well use already built servers like SmartFox and Photon, but I wan't to go through the pain of creating one myself for learning purposes. I've come up with a BSON inspired protocol to convert the the basic data types, their arrays, and a special GSObject to binary and arrange them in a way so that it can be put back together into object form on the client end. At the core, the conversion methods utilize the .Net BitConverter class to convert the basic data types to binary. Anyways, the problem is performance, if I loop 50,000 times and convert my GSObject to binary each time it takes about 5500ms (the resulting byte[] is just 192 bytes per conversion). I think think this would be way too slow for an MMO that sends 5-10 position updates per second with a 1000 concurrent users. Yes, I know it's unlikely that a game will have a 1000 users on at the same time, but like I said earlier this is supposed to be a learning process for me, I want to go out of my way and build something that scales well and can handle at least a few thousand users. So yea, if anyone's aware of other conversion techniques or sees where I'm loosing performance I would appreciate the help. GSBitConverter.cs This is the main conversion class, it adds extension methods to main datatypes to convert to the binary format. It uses the BitConverter class to convert the base types. I've shown only the code to convert integer and integer arrays, but the rest of the method are pretty much replicas of those two, they just overload the type. public static class GSBitConverter { public static byte[] ToGSBinary(this short value) { return BitConverter.GetBytes(value); } public static byte[] ToGSBinary(this IEnumerable<short> value) { List<byte> bytes = new List<byte>(); short length = (short)value.Count(); bytes.AddRange(length.ToGSBinary()); for (int i = 0; i < length; i++) bytes.AddRange(value.ElementAt(i).ToGSBinary()); return bytes.ToArray(); } public static byte[] ToGSBinary(this bool value); public static byte[] ToGSBinary(this IEnumerable<bool> value); public static byte[] ToGSBinary(this IEnumerable<byte> value); public static byte[] ToGSBinary(this int value); public static byte[] ToGSBinary(this IEnumerable<int> value); public static byte[] ToGSBinary(this long value); public static byte[] ToGSBinary(this IEnumerable<long> value); public static byte[] ToGSBinary(this float value); public static byte[] ToGSBinary(this IEnumerable<float> value); public static byte[] ToGSBinary(this double value); public static byte[] ToGSBinary(this IEnumerable<double> value); public static byte[] ToGSBinary(this string value); public static byte[] ToGSBinary(this IEnumerable<string> value); public static string GetHexDump(this IEnumerable<byte> value); } Program.cs Here's the the object that I'm converting to binary in a loop. class Program { static void Main(string[] args) { GSObject obj = new GSObject(); obj.AttachShort("smallInt", 15); obj.AttachInt("medInt", 120700); obj.AttachLong("bigInt", 10900800700); obj.AttachDouble("doubleVal", Math.PI); obj.AttachStringArray("muppetNames", new string[] { "Kermit", "Fozzy", "Piggy", "Animal", "Gonzo" }); GSObject apple = new GSObject(); apple.AttachString("name", "Apple"); apple.AttachString("color", "red"); apple.AttachBool("inStock", true); apple.AttachFloat("price", (float)1.5); GSObject lemon = new GSObject(); apple.AttachString("name", "Lemon"); apple.AttachString("color", "yellow"); apple.AttachBool("inStock", false); apple.AttachFloat("price", (float)0.8); GSObject apricoat = new GSObject(); apple.AttachString("name", "Apricoat"); apple.AttachString("color", "orange"); apple.AttachBool("inStock", true); apple.AttachFloat("price", (float)1.9); GSObject kiwi = new GSObject(); apple.AttachString("name", "Kiwi"); apple.AttachString("color", "green"); apple.AttachBool("inStock", true); apple.AttachFloat("price", (float)2.3); GSArray fruits = new GSArray(); fruits.AddGSObject(apple); fruits.AddGSObject(lemon); fruits.AddGSObject(apricoat); fruits.AddGSObject(kiwi); obj.AttachGSArray("fruits", fruits); Stopwatch w1 = Stopwatch.StartNew(); for (int i = 0; i < 50000; i++) { byte[] b = obj.ToGSBinary(); } w1.Stop(); Console.WriteLine(BitConverter.IsLittleEndian ? "Little Endian" : "Big Endian"); Console.WriteLine(w1.ElapsedMilliseconds + "ms"); } Here's the code for some of my other classes that are used in the code above. Most of it is repetitive. GSObject GSArray GSWrappedObject

    Read the article

  • Backpacks and Booth Paint: TechEd 2012

    - by The Un-T Guy
    Arriving in the parking lot of the Orange County Convention Center, I immediately knew I was in the right place. As far as the eye could see, the acres of asphalt were awash in backpacks, quirky (to be kind) outfits, and bad haircuts. This was the place. This was Microsoft Mecca v2012 for geeks and nerds, the Central Florida event of the year, a gathering of high tech professionals whose skills I both greatly respect and, frankly, fear a little. I was wholly and completely out of element, a dork in a vast sea of geek jumbo. It like was wearing dockers and a golf shirt walking into a RenFaire, but one with really crappy costumes and no turkey legs...save those attached to some of the attendees. Of course the corporate whores...errrr, vendors were in place, ready to parlay the convention's fre-nerd-ic energy into millions of dollars by convincing the big-brained and under-sexed in the crowd (i.e., virtually all of them...present company excluded, of course) that their product or service was the only thing standing between them and professional success, industry fame, and clear skin. "With KramTech 2012," they seemed to scream, "you will be THE ROCK STAR of your company's IT department!" As car shows and tattoo parlors learned long ago, Tech companies seem to believe that the best way to attract the attention of this crowd is through the hint of the promise of sex. They recruit and deploy an army of "sales reps" whose primary qualifications appear to be long hair, short skirts, high heels, and a vagina. Unlike their distant cousins in the car and body art industries, however, this sub-species of booth paint (semi-gloss decoration that adds nothing to the substance of the product) seems torn between committing to being all-out sex objects and recognition that they are in the presence of intelligent, discerning people. People who are smart enough to know exactly what these vendors are doing. Also unlike their distant car show and tattoo shop cousins, these young women (what…are there no gay tech professionals who could use some eye candy?) seem to realize that while IT remains a male-dominated field, there are ever-increasing numbers of intelligent, capable, strong professional women – women who’ve battled to make it in this field through hard work and work performance rather than a hard body and performing after work. This is not to say that all of the young female sales reps are there only because of their physical attributes. Many are competent, intelligent, and driven -- not to mention attractive. They're working hard on the front lines of delivering the next generation of technology. The distinction is pretty clear, however, between these young professionals and the booth paint. The former enthusiastically deliver credible information about the products they’re hawking. The latter are positioned in the aisles, uncomfortably avoiding eye contact as they struggle to operate the badge readers. Surprisingly, not all of the women in attendance seemed to object to the objectification of their younger sisters. One IT professional woman who came of age in the industry (mostly in IT marketing) said, “I have no problem with it. I was a ‘booth babe’ for years and it doesn’t bother me at all.” Others, however, weren’t quite so gracious. One woman I spoke with, an IT manager from Cheyenne, Wyoming, said it was demeaning and frankly, as more and more women grow into IT management positions, not a great marketing idea. “Using these young women is, to me, no different than vendors giving out t-shirts to attract attention. It’s sad because it’s still hard for a woman to be respected in the IT field and this just perpetuates the outdated notion that IT is a male-dominated field.” She went on to say that decisions by vendors to employ these young women in this “inappropriate way” could impact her purchasing decisions. “I might be swayed toward a vendor who has women on staff who are intelligent and dynamic rather than the vendors who use the ‘decoration’ girls.” So in many ways, the IT industry is no different than most other industries as it struggles to maximize performance by finding and developing talent – all of the talent, not just the 50% with a penis. Women in IT, like their brethren, struggle to find their niche in the field, to grow professionally, and reach for the brass ring, struggling to overcome obstacles as they climb the mountain of professional success in a never-ending cycle of economic uncertainty. But as (generally) well-educated and highly-trained professionals, they are probably better positioned than those in many other industries. Beside, they’ve got one other advantage over their non-IT counterparts as they attempt their ascent to the summit: They’ve already got the backpacks.

    Read the article

  • Yet another blog about IValueConverter

    - by codingbloke
    After my previous blog on a Generic Boolean Value Converter I thought I might as well blog up another IValueConverter implementation that I use. The Generic Boolean Value Converter effectively converters an input which only has two possible values to one of two corresponding objects.  The next logical step would be to create a similar converter that can take an input which has multiple (but finite and discrete) values to one of multiple corresponding objects.  To put it more simply a Generic Enum Value Converter. Now we already have a tool that can help us in this area, the ResourceDictionary.  A simple IValueConverter implementation around it would create a StringToObjectConverter like so:- StringToObjectConverter using System; using System.Windows; using System.Windows.Data; using System.Linq; using System.Windows.Markup; namespace SilverlightApplication1 {     [ContentProperty("Items")]     public class StringToObjectConverter : IValueConverter     {         public ResourceDictionary Items { get; set; }         public string DefaultKey { get; set; }                  public StringToObjectConverter()         {             DefaultKey = "__default__";         }         public virtual object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)         {             if (value != null && Items.Contains(value.ToString()))                 return Items[value.ToString()];             else                 return Items[DefaultKey];         }         public virtual object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)         {             return Items.FirstOrDefault(kvp => value.Equals(kvp.Value)).Key;         }     } } There are some things to note here.  The bulk of managing the relationship between an object instance and the related string key is handled by the Items property being an ResourceDictionary.  Also there is a catch all “__default__” key value which allows for only a subset of the possible input values to mapped to an object with the rest falling through to the default. We can then set one of these up in Xaml:-             <local:StringToObjectConverter x:Key="StatusToBrush">                 <ResourceDictionary>                     <SolidColorBrush Color="Red" x:Key="Overdue" />                     <SolidColorBrush Color="Orange" x:Key="Urgent" />                     <SolidColorBrush Color="Silver" x:Key="__default__" />                 </ResourceDictionary>             </local:StringToObjectConverter> You could well imagine that in the model being bound these key names would actually be members of an enum.  This still works due to the use of ToString in the Convert method.  Hence the only requirement for the incoming object is that it has a ToString implementation which generates a sensible string instead of simply the type name. I can’t imagine right now a scenario where this converter would be used in a TwoWay binding but there is no reason why it can’t.  I prefer to avoid leaving the ConvertBack throwing an exception if that can be be avoided.  Hence it just enumerates the KeyValuePair entries to find a value that matches and returns the key its mapped to. Ah but now my sense of balance is assaulted again.  Whilst StringToObjectConverter is quite happy to accept an enum type via the Convert method it returns a string from the ConvertBack method not the original input enum type that arrived in the Convert.  Now I could address this by complicating the ConvertBack method and examining the targetType parameter etc.  However I prefer to a different approach, deriving a new EnumToObjectConverter class instead. EnumToObjectConverter using System; namespace SilverlightApplication1 {     public class EnumToObjectConverter : StringToObjectConverter     {         public override object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)         {             string key = Enum.GetName(value.GetType(), value);             return base.Convert(key, targetType, parameter, culture);         }         public override object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)         {             string key = (string)base.ConvertBack(value, typeof(String), parameter, culture);             return Enum.Parse(targetType, key, false);         }     } }   This is a more belts and braces solution with specific use of Enum.GetName and Enum.Parse.  Whilst its more explicit in that the a developer has to  choose to use it, it is only really necessary when using TwoWay binding, in OneWay binding the base StringToObjectConverter would serve just as well. The observant might note that there is actually no “Generic” aspect to this solution in the end.  The use of a ResourceDictionary eliminates the need for that.

    Read the article

  • WPF - Only want one expander open at a time in grouped Listbox

    - by Portsmouth
    I have a UserControl with a templated grouped listbox with expanders and only want one expander open at any time. I have browsed through the site but haven't found anything except binding the IsExpanded to IsSelected which isn't quite what I want. I am trying to put some code in the Expanded event that would loop through Expanders and close all the ones that aren't the expander passed in the Expanded event. I can't seem to figure out how to get at them. I've tried ListBox.Items.Groups but didn't see how to get at them and tried ListBox.ItemContainerGenerator.ContainerFromItem (or Index) but nothing came back. Thanks <ListBox Name="ListBox"> <ListBox.GroupStyle> <GroupStyle> <GroupStyle.ContainerStyle> <Style TargetType="{x:Type GroupItem}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type GroupItem}"> <Border BorderBrush="CadetBlue" BorderThickness="1"> <Expander BorderThickness="0,0,0,1" Expanded="Expander_Expanded" Focusable="False" IsExpanded="{Binding IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType= {x:Type ListBoxItem}}}" > <Expander.Header> <Grid> <StackPanel Height="30" Orientation="Horizontal"> <TextBlock Foreground="Navy" FontWeight="Bold" Text="{Binding Path=Name}" Margin="5,0,0,0" MinWidth="200" Padding="3" VerticalAlignment="Center" /> <TextBlock Foreground="Navy" FontWeight="Bold" Text=" Setups: " VerticalAlignment="Center" HorizontalAlignment="Right"/> <TextBlock Foreground="Navy" FontWeight="Bold" Text="{Binding Path=ItemCount}" VerticalAlignment="Center" HorizontalAlignment="Right" /> </StackPanel> </Grid> </Expander.Header> <Expander.Content> <Grid Background="white" > <ItemsPresenter /> </Grid> </Expander.Content> <Expander.Style > <Style TargetType="{x:Type Expander}"> <Style.Triggers> <Trigger Property="IsMouseOver" Value="true"> <Setter Property="Background"> <Setter.Value> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Color="WhiteSmoke" Offset="0.0" /> <GradientStop Color="Orange" Offset="1.0" /> </LinearGradientBrush> </Setter.Value> </Setter> </Trigger> <Trigger Property="IsMouseOver" Value="false" <Setter Property="Background"> <Setter.Value>

    Read the article

  • How would you organize a large complex web application (see basic example)?

    - by Anurag
    How do you usually organize complex web applications that are extremely rich on the client side. I have created a contrived example to indicate the kind of mess it's easy to get into if things are not managed well for big apps. Feel free to modify/extend this example as you wish - http://jsfiddle.net/NHyLC/1/ The example basically mirrors part of the comment posting on SO, and follows the following rules: Must have 15 characters minimum, after multiple spaces are trimmed out to one. If Add Comment is clicked, but the size is less than 15 after removing multiple spaces, then show a popup with the error. Indicate amount of characters remaining and summarize with color coding. Gray indicates a small comment, brown indicates a medium comment, orange a large comment, and red a comment overflow. One comment can only be submitted every 15 seconds. If comment is submitted too soon, show a popup with appropriate error message. A couple of issues I noticed with this example. This should ideally be a widget or some sort of packaged functionality. Things like a comment per 15 seconds, and minimum 15 character comment belong to some application wide policies rather than being embedded inside each widget. Too many hard-coded values. No code organization. Model, Views, Controllers are all bundled together. Not that MVC is the only approach for organizing rich client side web applications, but there is none in this example. How would you go about cleaning this up? Applying a little MVC/MVP along the way? Here's some of the relevant functions, but it will make more sense if you saw the entire code on jsfiddle: /** * Handle comment change. * Update character count. * Indicate progress */ function handleCommentUpdate(comment) { var status = $('.comment-status'); status.text(getStatusText(comment)); status.removeClass('mild spicy hot sizzling'); status.addClass(getStatusClass(comment)); } /** * Is the comment valid for submission */ function commentSubmittable(comment) { var notTooSoon = !isTooSoon(); var notEmpty = !isEmpty(comment); var hasEnoughCharacters = !isTooShort(comment); return notTooSoon && notEmpty && hasEnoughCharacters; } // submit comment $('.add-comment').click(function() { var comment = $('.comment-box').val(); // submit comment, fake ajax call if(commentSubmittable(comment)) { .. } // show a popup if comment is mostly spaces if(isTooShort(comment)) { if(comment.length < 15) { // blink status message } else { popup("Comment must be at least 15 characters in length."); } } // show a popup is comment submitted too soon else if(isTooSoon()) { popup("Only 1 comment allowed per 15 seconds."); } });

    Read the article

  • printing multi dimentional array

    - by Honey
    i have this multi dimentional array that i want to print into a table having each record/item go into its own row but it goes column wise. this is the output that im getting: http://mypetshopping.com/product.php ps: the value of $product will by dynamic based on what product is being viewed. <?php session_start(); ?> <table> <thead> <tr> <th>Name</th> <th>Hash</th> <th>Quantity</th> <th>Size</th> <th>Color</th> </tr> </thead> <tbody> <?php function addCart($product, $quantity, $size,$color) { $hash = md5($product); $_SESSION['cart'][$product]['name'] = $product; $_SESSION['cart'][$product]['hash'] = $hash; $_SESSION['cart'][$product]['quantity'] = $quantity; $_SESSION['cart'][$product]['size'] = $size; $_SESSION['cart'][$product]['color'] = $color; } addCart('Red Dress',1,'XL','red'); addCart('Blue Dress',1,'XL','blue'); addCart('Slippers',1,'XL','orange'); addCart('Green Hat',1,'XXXL','green'); $cart = $_SESSION['cart']; foreach($cart as $product => $array) { foreach($array as $key => $value) { ?> <tr> <td><?=$value;?></td> <td><?=$value;?></td> <td><?=$value;?></td> <td><?=$value;?></td> <td><?=$value;?></td> </tr> <?php } } ?>

    Read the article

  • WPF - Only want one expander open at a time

    - by Portsmouth
    I have a UserControl with a templated grouped listbox with expanders and only want one expander open at any time. I have browsed through the site but haven't found anything except binding the IsExpanded to IsSelected which isn't quite what I want. I am trying to put some code in the Expanded event that would loop through Expanders and close all the ones that aren't the expander passed in the Expanded event. I can't seem to figure out how to get at them. I've tried ListBox.Items.Groups but didn't see how to get at them and tried ListBox.ItemContainerGenerator.ContainerFromItem (or Index) but nothing came back. Thanks <ListBox Name="ListBox"> <ListBox.GroupStyle > <GroupStyle> <GroupStyle.ContainerStyle> <Style TargetType="{x:Type GroupItem}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type GroupItem}"> <Border BorderBrush="CadetBlue" BorderThickness="1"> <Expander BorderThickness="0,0,0,1" Expanded="Expander_Expanded" Focusable="False" IsExpanded="{Binding IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType= {x:Type ListBoxItem}}}" > <Expander.Header> <Grid> <StackPanel Height="30" Orientation="Horizontal"> <TextBlock Foreground="Navy" FontWeight="Bold" Text="{Binding Path=Name}" Margin="5,0,0,0" MinWidth="200" Padding="3" VerticalAlignment="Center" /> <TextBlock Foreground="Navy" FontWeight="Bold" Text=" Setups: " VerticalAlignment="Center" HorizontalAlignment="Right"/> <TextBlock Foreground="Navy" FontWeight="Bold" Text="{Binding Path=ItemCount}" VerticalAlignment="Center" HorizontalAlignment="Right" /> </StackPanel> </Grid> </Expander.Header> <Expander.Content> <Grid Background="white" > <ItemsPresenter /> </Grid> </Expander.Content> <Expander.Style > <Style TargetType="{x:Type Expander}"> <Style.Triggers> <Trigger Property="IsMouseOver" Value="true"> <Setter Property="Background"> <Setter.Value> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Color="WhiteSmoke" Offset="0.0" /> <GradientStop Color="Orange" Offset="1.0" /> </LinearGradientBrush> </Setter.Value> </Setter> </Trigger> <Trigger Property="IsMouseOver" Value="false" <Setter Property="Background"> <Setter.Value> </code>

    Read the article

  • Android Drawable question.

    - by Tarmon
    Hey Everyone, I am trying to create a drawable in code and change the color based on some criteria. I can get it to work but it doesn't want to let me set the padding on the view. Any help would be appreciated. <?xml version="1.0" encoding="utf-8"?> <ImageView android:id="@+id/icon" android:layout_width="50px" android:layout_height="fill_parent" /> <TextView android:id="@+id/label" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingLeft="17px" android:textSize="28sp" /> ImageView icon = (ImageView) row.findViewById(R.id.icon); ShapeDrawable mDrawable; int x = 0; int y = 0; int width = 50; int height = 50; float[] outerR = new float[] { 12, 12, 12, 12, 12, 12, 12, 12 }; mDrawable = new ShapeDrawable(new RoundRectShape(outerR, null, null)); mDrawable.setBounds(x, y+height, x + width, y); switch(position){ case 0: mDrawable.getPaint().setColor(0xffff0000); //Red break; case 1: mDrawable.getPaint().setColor(0xffff0000); //Red break; case 2: mDrawable.getPaint().setColor(0xff00c000); //Green break; case 3: mDrawable.getPaint().setColor(0xff00c000); //Green break; case 4: mDrawable.getPaint().setColor(0xff0000ff); //Blue break; case 5: mDrawable.getPaint().setColor(0xff0000ff); //Blue break; case 6: mDrawable.getPaint().setColor(0xff696969); //Gray break; case 7: mDrawable.getPaint().setColor(0xff696969); //Gray break; case 8: mDrawable.getPaint().setColor(0xffffff00); //Yellow break; case 9: mDrawable.getPaint().setColor(0xff8b4513); //Brown break; case 10: mDrawable.getPaint().setColor(0xff8b4513); //Brown break; case 11: mDrawable.getPaint().setColor(0xff8b4513); //Brown break; case 12: mDrawable.getPaint().setColor(0xffa020f0); //Purple break; case 13: mDrawable.getPaint().setColor(0xffff0000); //Red break; case 14: mDrawable.getPaint().setColor(0xffffd700); //Gold break; case 15: mDrawable.getPaint().setColor(0xffff6600); //Orange break; } icon.setBackgroundDrawable(mDrawable); icon.setPadding(5, 5, 5, 5); If I set the padding in XML it just ignores it. Thanks, Rob

    Read the article

  • How to fix this window.open memory leak?

    - by DotnetShadow
    Hi there, I was recently looking at this memory leak tool sIEve: http://home.orange.nl/jsrosman/ So I decided to test out the tool by creating a main page that will open up a popup window. I started by creating 3 pages: index.html, page1.html and page2.html, the index.html page will open a child window (popup) linking to page1.html. Page1 will have a anchor tag that links to page2.html, while page2 will have a link back to page1.html PROBLEM So in the tool I entered the index.html page, popup window opened to page1.html, I then clicked the page2 link, no leaks detected yet. While I'm on page2 I click the link back to page1, and that's where the tool claims there is a link. The leak seems to be happening on the index.html page and I have no idea as to why it would be doing that. Even more concerning is that I can see elements that the tool detects that aren't even on my page. Does anyone have any experience with this tool or know if this really is a memory leak? Any samples of showing how to achieve what I'm doing without memory leaks? INDEX.HTML <script type="text/javascript"> MYLEAK = function() { var childWindow = null; function showWindow() { childWindow = window.open("page1.html", "myWindow"); return false; } return { init: function() { $("#window-link").bind("click", showWindow); } } }(); </script> </head> <body> <a id="window-link" href="#" on>Open Window</a> <script type="text/javascript"> $(document).ready(function() { MYLEAK.init(); }); </script> </body> </html> PAGE1.HTML <html> <body> <h1>Page 1</h1> <a href="page2.html">Page2</a> </body> </html> PAGE2.HTML <html> <body> <h1>Page 2</h1> <a href="page1.html">Page1</a> </body> </html> Appreciate your efforts.

    Read the article

  • How would you organize this Javascript?

    - by Anurag
    How do you usually organize complex web applications that are extremely rich on the client side. I have created a contrived example to indicate the kind of mess it's easy to get into if things are not managed well for big apps. Feel free to modify/extend this example as you wish - http://jsfiddle.net/NHyLC/1/ The example basically mirrors part of the comment posting on SO, and follows the following rules: Must have 15 characters minimum, after multiple spaces are trimmed out to one. If Add Comment is clicked, but the size is less than 15 after removing multiple spaces, then show a popup with the error. Indicate amount of characters remaining and summarize with color coding. Gray indicates a small comment, brown indicates a medium comment, orange a large comment, and red a comment overflow. One comment can only be submitted every 15 seconds. If comment is submitted too soon, show a popup with appropriate error message. A couple of issues I noticed with this example. This should ideally be a widget or some sort of packaged functionality. Things like a comment per 15 seconds, and minimum 15 character comment belong to some application wide policies rather than being embedded inside each widget. Too many hard-coded values. No code organization. Model, Views, Controllers are all bundled together. Not that MVC is the only approach for organizing rich client side web applications, but there is none in this example. How would you go about cleaning this up? Applying a little MVC/MVP along the way? Here's some of the relevant functions, but it will make more sense if you saw the entire code on jsfiddle: /** * Handle comment change. * Update character count. * Indicate progress */ function handleCommentUpdate(comment) { var status = $('.comment-status'); status.text(getStatusText(comment)); status.removeClass('mild spicy hot sizzling'); status.addClass(getStatusClass(comment)); } /** * Is the comment valid for submission */ function commentSubmittable(comment) { var notTooSoon = !isTooSoon(); var notEmpty = !isEmpty(comment); var hasEnoughCharacters = !isTooShort(comment); return notTooSoon && notEmpty && hasEnoughCharacters; } // submit comment $('.add-comment').click(function() { var comment = $('.comment-box').val(); // submit comment, fake ajax call if(commentSubmittable(comment)) { .. } // show a popup if comment is mostly spaces if(isTooShort(comment)) { if(comment.length < 15) { // blink status message } else { popup("Comment must be at least 15 characters in length."); } } // show a popup is comment submitted too soon else if(isTooSoon()) { popup("Only 1 comment allowed per 15 seconds."); } });

    Read the article

  • Display the form again ?

    - by noralain
    Hi all, I want to ask about the form in javascript .. I want to do a game that the user enter the correct word, then alert message will apeared for correct word.. When the user do the first word correctly, the program will display another word (to be corrected) .. but the problem which i faced that i can't make the form display again to continue play the game .. i used : var d = document.getElementById("form1"); d.style.visibility = "visible"; but it doesn't work !! This is my code: <title>Word Decoder</title> <script type="text/javascript"> function checkWord(word, score){ var ok = words[score].valueOf(); var ok1 = document.getElementById("wordid"); if(ok1.value == ok){ score ++; alert("Correct, your score is: " + score); var d = document.getElementById("form1"); d.style.visibility = "visible"; return false; } else { alert("Wrong Spelling"); return false; } } </script> </head> <body> <script type="text/javascript"> var words = new Array ("apple", "orange", "banana", "manago", "table"); var reWords = new Array ("alpep", "ergano", "aaabnn", "goamna", "lbeat"); var count = 0; var score = 0; "</br>"; </script> <form id="form1"> <br> <dir id="displayForm" style="position: relative; visibility: visible; display: block"> <h3><b> <script> document.write(reWords[score]);</script> </b></h3> <br> Enter the correct word: <input type="text" value="" id="wordid"/> <input type="submit" value="Check Answer ??" onclick="return checkWord(wordid, score);" /> </dir> </form> </body> Can help me to solve the problem? Again: I want the game will display a scrambled word and the user must unscrambled the word to move to the other word. The problem is i can't display the form again to make the user unscrambled the second, third ..etc words..

    Read the article

  • Prolog: Sentence Parser Problem

    - by Devon
    Hey guys, Been sat here for hours now just staring at this code and have no idea what I'm doing wrong. I know what's happening from tracing the code through (it is going on an eternal loop when it hits verbPhrase). Any tips are more then welcome. Thank you. % Knowledge-base det(the). det(a). adjective(quick). adjective(brown). adjective(orange). adjective(sweet). noun(cat). noun(mat). noun(fox). noun(cucumber). noun(saw). noun(mother). noun(father). noun(family). noun(depression). prep(on). prep(with). verb(sat). verb(nibbled). verb(ran). verb(looked). verb(is). verb(has). % Sentece Structures sentence(Phrase) :- append(NounPhrase, VerbPhrase, Phrase), nounPhrase(NounPhrase), verbPhrase(VerbPhrase). sentence(Phrase) :- verbPhrase(Phrase). nounPhrase([]). nounPhrase([Head | Tail]) :- det(Head), nounPhrase2(Tail). nounPhrase(Phrase) :- nounPhrase2(Phrase). nounPhrase(Phrase) :- append(NP, PP, Phrase), nounPhrase(NP), prepPhrase(PP). nounPhrase2([]). nounPhrase2(Word) :- noun(Word). nounPhrase2([Head | Tail]) :- adjective(Head), nounPhrase2(Tail). prepPhrase([]). prepPhrase([Head | Tail]) :- prep(Head), nounPhrase(Tail). verbPhrase([]). verbPhrase(Word) :- verb(Word). verbPhrase([Head | Tail]) :- verb(Head), nounPhrase(Tail). verbPhrase(Phrase) :- append(VP, PP, Phrase), verbPhrase(VP), prepPhrase(PP).

    Read the article

  • Artichow PlotGroup: Legends not showing

    - by Hameed
    I am working on a little project on OpenCATS, developing some charts. In one of the charts, I need to add multiple plots to a PlotGroup and add Legends as well. I have written a small function that creates the chart, however I have difficulty displaying the legends when I add them to a PlotGroup object. Here is the code: public function draw($format = false) { /* Make sure we have GD support. */ if (!function_exists('imagecreatefromjpeg')) { die(); } if ($format === false) { $format = IMG_PNG; } $group = new PlotGroup(); $graph = new Graph($this->width, $this->height, NULL, 0, $this->width-135); $graph->setFormat($format); $graph->setBackgroundColor(new Color(0xF4, 0xF4, 0xF4)); $graph->shadow->setSize(3); $graph->title->set($this->title); $graph->title->setFont(new Tuffy(10)); $graph->title->setColor(new Color(0x00, 0x00, 0x8B)); $graph->border->setColor(new Color(187, 187, 187, 15)); $group->axis->bottom->setLabelText($this->xLabels); $group->axis->bottom->label->setFont(new Tuffy(8)); $group->setPadding(25, 145, 10, 22); $plotcount = 0; $plot = array(); foreach ($this->xValues as $xVal) { $plotcount++; $plot[$plotcount-1] = new LinePlot($xVal, LinePlot::LINE); $plot[$plotcount-1]->setPadding(25, 145, 10, 22); if ($plotcount % 5 ==0 ) $plot[$plotcount-1]->setColor(new Blue); else if ($plotcount % 4 ==0 ) $plot[$plotcount-1]->setColor(new DarkGreen); else if ($plotcount % 3 ==0 ) $plot[$plotcount-1]->setColor(new Red); else if ($plotcount % 2 ==0 ) $plot[$plotcount-1]->setColor(new Orange); $plot[$plotcount-1]->setThickness(2); $plot[$plotcount-1]->legend->add($plot[$plotcount-1], $this->legends[$plotcount-1]); $plot[$plotcount-1]->legend->setTextFont(new Tuffy(8)); $plot[$plotcount-1]->legend->setPadding(3, 3, 3, 3, 3); $plot[$plotcount-1]->legend->setPosition(1, 0.825); $plot[$plotcount-1]->legend->setBackgroundColor(new Color(0xFF, 0xFF, 0xFF)); $plot[$plotcount-1]->legend->border->setColor(new Color(0xD0, 0xD0, 0xD0)); $plot[$plotcount-1]->legend->shadow->setSize(0); $group->add($plot[$plotcount-1]); } $graph->add($group); $graph->draw(); } } If I draw only one LinePlot it works: So for instance if I change $graph->add($group); to $graph->add($plot[0]); then only one of the lines will show up with the legend next to it.

    Read the article

  • iphone cocos2d sprites disappearing

    - by jer
    I've been working on a game and implementing the physics stuff with chipmunk. All was going fine on the cocos2d part until the integration with chipmunk. A bit of background: The game is a game with blocks. Levels are defined in a property list, where positions, size of the blocks, gravitational forces, etc., are all defined for each block to be shown in the level. The problem is with the blocks showing up. I have a method on my BlockLayer class which is part of my game's main scene. Upon creation of the layer, the property list is read, and all the blocks are created. The following method is called to create the blocks: - (void)createBlock:(Block*)block withAssets:(NSBundle*)assets { Sprite* sprite; switch(block.blockColour) { case kBlockColourGreen: sprite = [Sprite spriteWithFile:[assets pathForResource:@"green" ofType:@"png" inDirectory:@"Blocks"]]; break; case kBlockColourOrange: sprite = [Sprite spriteWithFile:[assets pathForResource:@"orange" ofType:@"png" inDirectory:@"Blocks"]]; break; case kBlockColourRed: sprite = [Sprite spriteWithFile:[assets pathForResource:@"red" ofType:@"png" inDirectory:@"Blocks"]]; break; case kBlockColourBlue: sprite = [Sprite spriteWithFile:[assets pathForResource:@"blue" ofType:@"png" inDirectory:@"Blocks"]]; break; } sprite.position = block.bounds.origin; [self addChild:sprite]; if(block.blockColour == kBlockColourGreen || block.blockColour == kBlockColourRed) space-gravity = cpvmult(cpv(0, 10), 1000); cpVect verts[] = { cpv(-block.bounds.size.width, -block.bounds.size.height), cpv(-block.bounds.size.width, block.bounds.size.height), cpv(block.bounds.size.width, block.bounds.size.height), cpv(block.bounds.size.width, -block.bounds.size.height) }; cpBody* blockBody = cpBodyNew([block.mass floatValue], INFINITY); blockBody-p = cpv(block.bounds.origin.x, block.bounds.origin.y); blockBody-v = cpvzero; cpSpaceAddBody(space, blockBody); cpShape* blockShape = cpPolyShapeNew(blockBody, 4, verts, cpvzero); blockShape-e = 0.9f; blockShape-u = 0.9f; blockShape-data = sprite; cpSpaceAddShape(space, blockShape); } With the above code, the sprites never show up. However, if I comment out the "cpSpaceAddBody(space, blockBody);" line, the sprites show up. The position and size of the blocks are stored in the "bounds" property of instances of the Block class, which is a CGRect. Not sure if it's important, but the orientation of the app is in landscape left, and all the coordinates are based on that orientation. Any help would be greatly appreciated.

    Read the article

  • Why aren't min-width and max-width working as I expect?

    - by Nathan Long
    I'm trying to adjust a CSS page layout using min-width and max-width. To simplify the problem, I made this test page. I'm trying it out in the latest versions of Firefox and Chrome with the same results. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Testing min-width and max-width</title> <style type="text/css"> div{float: left; max-width: 400px; min-width: 200px;} div.a{background: orange;} div.b{background: gray;} </style> </head> <body> <div class="a"> (Giant block of filler text here) </div> <div class="b"> (Giant block of filler text here) </div> </body> </html> Here's what I expect to happen: With the browser maximized, the divs sit side by side, each 400px wide: their maximum width Shrink the browser window, and they both shrink to 200px: their minimum width Further shrinking the browser has no effect on them Here's what actually happens, starting at step 2: Shrink the browser window, and as soon as they can't sit side-by-side at their max width, the second div drops below the first Further shrinking the browser makes them get narrower and narrower, as small as I can make the window So here's are my questions: What does max-width mean if the element will sooner hop down in the layout than go lower than its maximum width? What does min-width mean if the element will happily get narrower than that if the browser window keeps shrinking? Is there any way to achieve what I want: have these elements sit side-by-side, happily shrinking until they reach 200px each, and only then adjust the layout so that the second one drops down? And of course... What am I doing wrong?

    Read the article

  • How do you set the ZIndex on a TabItem?

    - by CC Inc
    I am wanting my TabItems to be positioned in between a border to achieve a "binder" affect, like this: However, I cannot seem to achieve this affect using ZIndex with my borders and each TabItem item. Currently, I get this result: Using this code: <Border CornerRadius="40,40,0,0" Background="Orange" Margin="8,31,2,21" Grid.RowSpan="4" Panel.ZIndex="-3" ></Border> <Border CornerRadius="40,40,0,0" Background="Red" Margin="6,29,4,23" Grid.RowSpan="4" Panel.ZIndex="-1"></Border> <Border CornerRadius="40,40,0,0" Background="Yellow" Margin="3,26,7,26" Grid.RowSpan="4" Panel.ZIndex="1"></Border> <Border CornerRadius="40,40,0,0" Background="DarkRed" Margin="1,23,9,29" Grid.RowSpan="4" Panel.ZIndex="3"></Border> <Border CornerRadius="40,40,0,0" Background="OrangeRed" Margin="-2,19,12,33" Grid.RowSpan="4" Name="border1" Panel.ZIndex="5"></Border> <TabControl Name="tabControl1" TabStripPlacement="Bottom" Background="Transparent" Margin="-2,32,15,6" Grid.RowSpan="4" BorderThickness="0"> <TabItem Name="tabItem1" Margin="0,0,0,1" Panel.ZIndex="4"> <TabItem.Header> <TextBlock> Main</TextBlock> </TabItem.Header> </TabItem> <TabItem Name="tabItem2" Panel.ZIndex="5"> <TabItem.Header> <TextBlock Height="13" Width="91"> Internet Explorer</TextBlock> </TabItem.Header> </TabItem> <TabItem Name="tabItem3" Panel.ZIndex="0"> <TabItem.Header> <TextBlock> Firefox</TextBlock> </TabItem.Header> </TabItem> <TabItem Name="tabItem4" Panel.ZIndex="-2"> <TabItem.Header> <TextBlock> Chrome</TextBlock> </TabItem.Header> </TabItem> <TabItem Name="tabItem5" Panel.ZIndex="-4"> <TabItem.Header> <TextBlock> Opera</TextBlock> </TabItem.Header> </TabItem> </TabControl> However, this does not achieve the desired affect. How can I do this in WPF? Is TabControl the best choice?

    Read the article

  • Correct table layout generation with CSS: unexpected cells shift

    - by MrG
    I'm trying to generate a dynamic table using CSS: <html> <head> <style> div.el1, div.el2 { color:white; width:70px;height:70px; border:0px; padding:0px; font-size: 10px; font-family: "Courier"; } div.el1 { background-color: green; } div.el2 { background-color: orange; } div.tablediv { display: table; border:0px; border-spacing:0px; border-collapse:separate; } div.celldiv { display: table-cell; } div.rowdiv { display: table-row; width:auto; } </style> </head> <body> <div class="tablediv"> <div class="rowdiv"> <div class="celldiv"> <div class="el1" id="x1y1">ABC</div> </div> <div class="celldiv"> <div class="el2" id="x1y2"></div> </div> </div> <div class="rowdiv"> <div class="celldiv"> <div class="el1" id="x2y1"></div> </div> <div class="celldiv"> <div class="el1" id="x2y2"></div> </div> </div> </div> </body> </html> The content of body is dynamically generated and should be displayed as a table. Unfortunately, each cell shifts down if it contains data: expected reality --- --- --- --- | | | | | | --- --- |ABC|--- | | | | | | --- --- --- --- | | | --- --- I'm grateful for any help. Many thanks!

    Read the article

  • D3 fisheye on width on bar chart

    - by Dexter Tan
    i have been trying to create a vertical bar chart with a d3 fisheye cartesian distortion with only the x-axis being distorted. I have succeeded in distorting the x position of the vertical bars on mouseover with the following code: var maxMag = d3.max(dataset, function(d) { return d.value[10]; }); var minDate = d3.min(dataset, function(d) { return new Date(d.value[1], d.value[2]-1, d.value[3]).getTime(); }); var maxDate = d3.max(dataset, function(d) { return new Date(d.value[1], d.value[2]-1, d.value[3]).getTime(); }); var yScale = d3.scale.linear().domain([0, maxMag]).range([0, h]); var xScale = d3.fisheye.scale(d3.scale.linear).domain([minDate, maxDate]).range([0, w]).focus(w/2); var bar = svg.append("g") .attr("class", "bars") .selectAll(".bar") .data(dataset) .enter().append("rect") .attr("class", "bar") .attr("y", function(d) { return h - yScale(d.value[10]); }) .attr("width", w/dataset.length) .attr("height", function(d) { return yScale(d.value[10]); }) .attr("fill", function(d) { return (d.value[10] <= 6? "yellow" : "orange" ); }) .call(position); // Positions the bars based on data. function position(bar) { bar.attr("x", function(d) { var date = null; if (d.date != null) { date = d.date; } else { date = new Date(d.value[1],0,1); if (d.value[2] != null) date.setMonth(d.value[2]-1); if (d.value[3] != null) date.setMonth(d.value[3]); d.date = date; } return xScale(date.getTime()); }); } svg.on("mousemove", function() { var mouse = d3.mouse(this); xScale.distortion(2.5).focus(mouse[0]); bar.call(position); }); However at this point, applying fisheye on the width remains a mystery to me. I have tried several methods like using a fisheye scale for width however it does not work as expected. What i wish to do is to have the width of a bar expand on mouseover, the same way a single vertical bar is singled out on mouseover with the cartesian distortion. Any clues or help will be much appreciated! edit: http://dexter.xumx.me to view the visualisation i am talking about for easier understanding!

    Read the article

  • How do I change the visual style of a listitem based on its bound value?

    - by Rodd
    I have a listbox (here's the xaml): <ListBox MinWidth="300" ItemsSource="{Binding Relationships, Mode=OneWay}" SelectedItem="{Binding SelectedRelationship, Mode=TwoWay}" SelectionMode="Single" HorizontalAlignment="Left" > <ListBox.ItemTemplate> <DataTemplate> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> <RowDefinition/> <RowDefinition/> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <CheckBox IsChecked = "{Binding IsPrimary}" IsHitTestVisible="False" /> <StackPanel Orientation="Horizontal" Grid.Column="1"> <TextBlock Text="{Binding RelationshipType}" FontWeight="Bold" Margin="0,0,5,0" /> <TextBlock Text="{Binding Status}" FontStyle="Italic" /> </StackPanel> <TextBlock Text="{Binding UnitName}" Grid.Row="1" Grid.Column="1" /> <TextBlock Text="{Binding StartDate, Converter={StaticResource DateConverter}}" Grid.Row="2" Grid.Column="1"/> <TextBlock Text="{Binding RetireDate}" Grid.Row="3" Grid.Column="1" /> <TextBlock Text="{Binding EndDate}" Grid.Row="4" Grid.Column="1" /> <TextBlock Text="{Binding ReasonForLeaving}" Grid.Row="5" Grid.Column="1" /> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox> What I want to do is have each item in the listbox have one of 3 backgrounds (green if the value of IsPrimary = true, Orange if the EndDate value is empty and grey if the EndDate value is not empty. Is there a way to template the listbox items so that they evaluate bound items to determine a view state or to have each listbox item bind to a value that I can set for each item in my viewmodel? Thanks for your help.

    Read the article

  • How can a button click method find out which item is selected in a ListView?

    - by Ian Bayley
    I have a single screen with a bank of buttons below a ListView. Entries on the ListView light up in orange when I scroll so I assume that are selected. When I then press the "Delete" button I want the onClickListener to remove the currently selected entry. But getSelectedItemPosition() always gives me -1. If I can't hope to use the GUI controls in this way, please give me another way of getting the same result. I have even tried setting the onClickListener of the List View to store the index before the button is pressed (in case pressing the button unselects the entry) but even that is always -1 it seems. Here's the code (without the modification which didn't work) package com.bayley; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import java.util.ArrayList; /** * * @author p0074564 */ public class September extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); final ListView myListView = (ListView) findViewById(R.id.myListView); Button addButton = (Button) findViewById(R.id.AddButton); Button deleteButton = (Button) findViewById(R.id.DeleteButton); final EditText editText = (EditText) findViewById(R.id.myEditText); final ArrayList<String> todoItems = new ArrayList<String>(); todoItems.add("Monday"); todoItems.add("Tuesday"); todoItems.add("Wednesday"); final ArrayAdapter<String> aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItems); myListView.setAdapter(aa); addButton.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { todoItems.add(editText.getText().toString()); aa.notifyDataSetChanged(); } }); deleteButton.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { // always returns -1 unfortunately ie nothing is ever selected int index = myListView.getSelectedItemPosition(); if (index >= 0) { todoItems.remove(index); } aa.notifyDataSetChanged(); } }); } }

    Read the article

< Previous Page | 19 20 21 22 23 24 25 26  | Next Page >