Search Results

Search found 5642 results on 226 pages for 'coding efficiency'.

Page 7/226 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Is micro-optimisation important when coding?

    - by BozKay
    I recently asked a question on stackoverflow.com to find out why isset() was faster than strlen() in php. This raised questions around the importance of readable code and whether performance improvements of micro-seconds in code were worth even considering. My father is a retired programmer, I showed him the responses and he was absolutely certain that if a coder does not consider performance in their code even at the micro level, they are not good programmers. I'm not so sure - perhaps the increase in computing power means we no longer have to consider these kind of micro-performance improvements? Perhaps this kind of considering is up to the people who write the actual language code? (of php in the above case). The environmental factors could be important - the internet consumes 10% of the worlds energy, I wonder how wasteful a few micro-seconds of code is when replicated trillions of times on millions of websites? I'd like to know answers preferably based on facts about programming. Is micro-optimisation important when coding? EDIT : My personal summary of 25 answers, thanks to all. Sometimes we need to really worry about micro-optimisations, but only in very rare circumstances. Reliability and readability are far more important in the majority of cases. However, considering micro-optimisation from time to time doesn't hurt. A basic understanding can help us not to make obvious bad choices when coding such as if (expensiveFunction() && counter < X) Should be if (counter < X && expensiveFunction()) (example from @zidarsk8) This could be an inexpensive function and therefore changing the code would be micro-optimisation. But, with a basic understanding, you would not have to because you would write it correctly in the first place.

    Read the article

  • Why use spaces instead of tabs for indentation? [closed]

    - by erenon
    Possible Duplicate: Are spaces preferred over tabs for indentation? Why do most coding standards recommend the use of spaces instead of tabs? Tabs can be configured to be as many characters wide as needed, but spaces can't. Example: Zend cs Pear cs Pear manual: This helps to avoid problems with diffs, patches, SVN history and annotations. How could tabs cause problems?

    Read the article

  • how to tackle a new project

    - by stevo
    Hi, I have a question about best practice on how to tackle a new project, any project. When starting a new project how do you go about tackling the project, do you split it into sections, start writing code, draw up flow diagrams. I'm asking this question because I'm looking for advice on how I can start new projects so I can get going on them quicker. I can have it planned, designed and starting coding with everything worked out. Any advice? Thanks Stephen

    Read the article

  • What's the best book for coding conventions?

    - by Joschua
    What's the best book about coding conventions (and perhaps design patterns), that you highly recommend (at best code samples in Python, C++ or Java)? It would be good, if the book (or just another) also covers the topics project management and agile software development if appropriate (for example how projects fail through spaghetti code). I will accept the answer with the book(s) (maximum two books per answer, please), that looks the most interesting, because the reading might take a while :)

    Read the article

  • How important is knowing functionality before coding?

    - by minusSeven
    I work for a software development company where the development work have been off shored to us. The on shore team handle the support and talk directly to the clients. We never talk to the clients directly we just talk people from the on shore team who talk directly to the clients. When requirements come, on shore team talk to the clients and make requirement documents and informs us. We make design documents after studying the requirements (we follow traditional waterfall model ). But there is one problem in the whole process: nobody in the either off-shore or on-shore understand the functionality of the application completely. We just know its a big complex web app handling complex order processing, catalog management, campaign management and other activities. We struggle with the design document as the requirements would not be clear. It then goes into a series of questions/answers back and forth between the on shore team,off shore team and clients. We would often be told to understand functionality from the code. But that's usually not feasible as the code base is huge and even understanding a simple menu item take days if not weeks. We tried telling the clients to give us knowledge transfer about the application but to no avail. Our manager would often tell us to start coding even if the design document is not complete or requirements not clear. We would start by coding part of the requirement that seems clear and wait for the rest. This usually would delay the deployment by a month. In extreme cases we would have very low errors in the development and production but the clients would say that's not what they asked. That would start a blame game and a series of change requests and we would end up developing something very different. My question is how would you do development work if you don't know the functionality of the app fully? UPDATE About development methodology it isn't really my choice and I am not my team's lead It is the way it began. I tried to tell people about the advantages of agile but to no avail. Besides I don't think my team has the necessary mindset to work in AGILE environment.

    Read the article

  • Collaborative coding chat options

    - by jayunit100
    Hi guys : Are there any established online sites for collaborative coding ? I have a github project with 5 developers, in different areas - we need somewhere that we can all "hangout" at. Right now we use group skype, but skype is designed more for family/social communication , and doesn't work on linux. IRC is okay, but its a little difficult to use for novices. an interface like yammer, twitter, facebook would be ideal, but also, we would want it to be real time (not requiring page reloads etc...)

    Read the article

  • General programming techniques to speed up coding time

    - by mcwise
    I am preparing for a programming contest in C++ where it is all about producing working code in a short time. An example would be to use a macro to get the minimum of two ints(but I was told that you shouldn't use macros as they are not type-safe) or using memsets to initialize arrays (but I was told that you shouldn't use memsets in C++). This leads to the question, what kind of coding techniques exist to use at a real job?

    Read the article

  • Use Those Extra Mouse Buttons to Increase Efficiency

    - by Mark Virtue
    Did you know that the most commonly used mouse actions are clicking a window’s “Close” button (the X in the top-right corner), and clicking the “Back” button (in a browser and various other programs)?  How much time do you spend every day locating the Close button or the Back button with your mouse so that you can click on them?  And what about that mouse you’re using – how many buttons does it have, besides the two main ones?  Most mouses these days have at least four (including the scroll-wheel, which a lot of people don’t realize is also a button as well).  Why not assign those extra buttons to your most common mouse actions, and save yourself a bundle of mousing-around time every day? If your mouse was manufactured by one of the “premium” mouse manufacturers (Microsoft, Logitech, etc), it almost certain came with driver software to allow you to customize your mouse’s controls and take advantage of your mouse’s special features.  Microsoft, for example, provides driver software called IntelliPoint (link below), while Logitech provides SetPoint.  It’s possible that your mouse has some extra buttons but doesn’t come with its own driver software (the author is using a Microsoft Bluetooth Notebook Mouse 5000, which amazingly is not supported by the Microsoft IntelliPoint software!).  If your mouse falls into this category, you can use a marvelous free product called X-Mouse Button Control, from Highresolution Enterprises (link below).  It provides a truly amazing array of mouse configuration options, including assigning actions to buttons on a per-application basis. Once X-Mouse Button Control is downloaded, its setup process is quite straightforward. Once downloaded, you can start the program via Start / Highresolution Enterprises / X-Mouse Button Control.  You will find the program’s icon in the system tray: Right-click on the icon and select Setup from the pop-up menu.  The program’s configuration window appears: It’s extremely unlikely that we will want to change the functionality of our mouse’s two main buttons (left and right), so instead we’ll look at the rest of the options on the right side of the window.  The Middle Button refers to either the third, middle button (found on some old mouses), or the pressing of the wheel itself, as a button (if you didn’t know you could press your wheel like a button, try it out now).  Mouse Button 4 and Mouse Button 5 usually refer to the extra buttons found on the side of the mouse, often near your thumb. So what can we use these extra mouse buttons for?  Well, clearly Close and Back are two obvious candidates.  Each of these can be found by selecting them from the drop-down menu next to each button field: Once the two options are chosen, the window will look something like this: If you’re not interested in choosing Back or Close, you may like to try some of the other options in the list, including: Cut, Copy and Paste Undo Show the Desktop Next/Previous track (for media playback) Open any program Simulate any keystroke or combination of keystrokes ….and many other options.  Explore the drop-down list to see them all. You may decide, for example, that closing the current document (as opposed to the current program) would be a good use for Mouse Button 5.  In other words, we need to simulate the keypress of Ctrl-F4.  Let’s see how we achieve this. First we select Simulated Keystrokes from the drop-down list: The Simulated Keystrokes window opens: The instructions on the page are pretty comprehensive.  If you want to simulate the Ctrl-F4 keystroke, you need to type {CTRL}{F4} into the box: …and then click OK. Assigning Actions to Buttons on a Per-Application Basis One of the most powerful features of X-Mouse Button Control is the ability to assign actions to buttons on a per-application basis.  This means that if we have a particular program open, then our mouse will behave differently – our buttons will do different things. For example, when we have Windows Media Player open, for example, we may wish to have buttons assigned to Play/Pause, Next track and Previous track, as well as changing the volume with the mouse!  This is easy with X-Mouse Button Control.  We start by opening Windows Media Player.  This makes the next step easier.  Then we return to X-Mouse Button Control and add a new “configuration”.  This is done by clicking the Add button: A window opens containing a list of all running programs, including our recently opened Windows Media Player: We select Windows Media Player and click OK.  A new, blank “configuration” is created: We repeat the earlier steps to assign buttons to Play/Pause, Next track and Previous track, and assign scrolling the wheel to alter the volume:   To save all our changes and close the window, we click Apply. Now spend a few minutes thinking of all the applications you use the most, and what are the most common simple tasks you perform in each of those applications.  Those tasks are then perfect candidates for per-application button assignments. There are many more configuration options and capabilities of X-Mouse Button Control – too many to list here.  We encourage you to spend a bit of time exploring the Setup window.  Then, most important of all, don’t forget to use your new mouse buttons!  Get into the habit of using them, and then after a while you’ll start to wonder how you ever tolerated the laborious, tedious, time-consuming process of actually locating each window’s Close button… Download X-Mouse Button Control Highresolution Enterprise Similar Articles Productive Geek Tips Add Specialized Toolbar Buttons to Firefox the Easy WayBoost Your Mouse Pointing Accuracy in WindowsMake Mouse Navigation Faster in WindowsVista Style Popup Previews for Firefox TabsStupid Geek Tricks: Using the Quick Zoom Feature in Outlook TouchFreeze Alternative in AutoHotkey The Icy Undertow Desktop Windows Home Server – Backup to LAN The Clear & Clean Desktop Use This Bookmarklet to Easily Get Albums Use AutoHotkey to Assign a Hotkey to a Specific Window Latest Software Reviews Tinyhacker Random Tips DVDFab 6 Revo Uninstaller Pro Registry Mechanic 9 for Windows PC Tools Internet Security Suite 2010 Download Videos from Hulu Pixels invade Manhattan Convert PDF files to ePub to read on your iPad Hide Your Confidential Files Inside Images Get Wildlife Photography Tips at BBC’s PhotoMasterClasses Mashpedia is a Real-time Encyclopedia

    Read the article

  • SQLAuthority News – Windows Efficiency Tricks and Tips – Personal Technology Tip

    - by pinaldave
    This is the second post in my series about my favorite Technology Tips, and I wanted to focus on my favorite Microsoft product.  Choosing just one topic to cover was too hard, though.  There are so many interesting things I have to share that I am forced to turn this second installment into a five-part post.  My five favorite Windows tips and tricks. 1) You can open multiple applications using the task bar. With the new Windows 7 taskbar, you can start navigating with just one click.  For example, you can launch Word by clicking on the icon on your taskbar, and if you are using multiple different programs at the same time, you can simply click on the icon to return to Word.  However, what if you need to open another Word document, or begin a new one?  Clicking on the Word icon is just going to bring you back to your original program.  Just click on the Word icon again while holding down the shift key, and you’ll open up a new document. 2) Navigate the screen with the touch of a button – and not your mouse button. Yes, we live in a pampered age.  We have access to amazing technology, and it just gets better every year.  But have you ever found yourself wishing that right when you were in the middle of something, you didn’t have to interrupt your work flow be reaching for your mouse to navigate through the screen?  Yes, we have all been guilty of this pampered wish.  But Windows has delivered!  Now you can move your application window using your arrow keys. Lock the window to the left, right hand screen: Win+left Arrow and Win+right Arrow Maximize & minimize: Win+up arrow and Win+down arrow Minimize all items on screen: Win+M Return to your original folder, or browse through all open windows: Alt+up arrow, Alt+Left Arrow, or Alt+right arrow Close down or reopen all windows: win+home 3) Are you one of the few people who still uses Command Prompt? You know who you are, and you aren’t ashamed to still use this option that so many people have forgotten about it.  You can easily access it by holding down the shift key while RIGHT clicking on any folder. 4) Quickly select multiple files without using your mouse. We all know how to select multiple files or folders by Ctrl-clicking or Shift-clicking multiple items.  But all of us have tried this, and then accidentally released Ctrl, only to lose all our precious work.  Now there is a way to select only the files you want through a check box system.  First, go to Windows Explorer, click Organize, and then “Folder and Search Options.”  Go to the View tab, and under advanced settings, you can find a box that says “Use check boxes to select items.”  Once this has been selected, you will be able to hover your mouse over any file and a check box will appear.  This makes selecting multiple, random files quick and easy. 5) Make more out of remote access. If you work anywhere in the tech field, you are probably the go-to for computer help with friends and family, and you know the usefulness of remote access (ok, some of us use this extensively at work, as well, but we all have friends and family who rely on our skills!).  Often it is necessary to restart a computer, which is impossible in remote access as the computer will not show the shutdown menu.  To force the computer to do your wishes, we return to Command Prompt.  Open Command Prompt and type “shutdown /s” for shutdown, or “shutdown /r” for restart. I hope you will find above five tricks which I use in my daily use very important. Reference: Pinal Dave (http://blog.SQLAuthority.com) Filed under: PostADay, SQL, SQL Authority, SQL Query, SQL Server, SQL Tips and Tricks, SQLAuthority News, T SQL, Technology Tagged: Personal Technology

    Read the article

  • SQLAuthority News – Android Efficiency Tips and Tricks – Personal Technology Tip #003

    - by pinaldave
    I use my phone for lots of things.  I use it mainly to replace my tablet – I can e-mail, take and edit photos, and do almost everything I can do on a laptop with this phone.  And I am sure that there are many of you out there just like me.  I personally have a Galaxy S3, which uses the Android operating system, and I have decided to feature it as the third installment of my Technology Tips and Tricks series. 1) Shortcut to your favorite contacts on home screen Access your most-called contacts easily from your home screen by holding your finger on any empty spot on the home screen.  A menu will pop up that allows you to choose Shortcuts, and Contact.  You can scroll through your contact list and then just tap on the name of the person you want to be able to dial with a single click. 2) Keep track of your data usage Yes, we all should keep a close eye on our data usage, because it is very easy to go over our limits and then end up with a giant bill at the end of the month.  Never get surprised when you open that mobile phone envelope again.  Go to Settings, then Data Usage, and you can find a quick rundown of your usage, how much data each app uses, and you can even set alarms to let you know when you are nearing the limits.   Better yet, you can set the phone to stop using data when it reaches a certain limit. 3) Bring back Good Grammar We often hear proclamations about the downfall of written language, and how texting abbreviations, misspellings, and lack of punctuation are the root of all evil.  Well, we can show all those doomsdayers that all is not lost by bringing punctuation back to texting.  Usually we leave it off when we text because it takes too long to get to the screen with all the punctuation options.  But now you can hold down the period (or “full stop”) button and a list of all the commonly-used punctuation marks will pop right up. 4) Apps, Apps, Apps and Apps And finally, I cannot end an article about smart phones without including a list of my favorite apps.  Here are a list of my Top 10 Applications on my Android (not counting social media apps). Advanced Task Killer – Keeps my phone snappy by closing un-necessary apps WhatsApp - my favorite alternate to Text SMS Flipboard - my ‘timepass’ moments Skype – keeps me close to friends and family GoogleMaps - I am never lost because of this one thing Amazon Kindle – Books my best friends DropBox - My data always safe Pluralsight Player – Learning never stops for me Samsung Kies Air – Connecting Phone to Computer Chrome – Replacing default browser I have not included any social media applications in the above list, but you can be sure that I am linked to Twitter, Facebook, Google+, LinkedIn, and YouTube. Reference: Pinal Dave (http://blog.SQLAuthority.com)   Filed under: Best Practices, PostADay, SQL, SQL Authority, SQL Query, SQL Server, SQL Tips and Tricks, SQLAuthority News, T SQL, Technology Tagged: Android, Personal Technology

    Read the article

  • SQLAuthority News – Android Efficiency Tips and Tricks – Personal Technology Tip

    - by pinaldave
    I use my phone for lots of things.  I use it mainly to replace my tablet – I can e-mail, take and edit photos, and do almost everything I can do on a laptop with this phone.  And I am sure that there are many of you out there just like me.  I personally have a Galaxy S3, which uses the Android operating system, and I have decided to feature it as the third installment of my Technology Tips and Tricks series. 1) Shortcut to your favorite contacts on home screen Access your most-called contacts easily from your home screen by holding your finger on any empty spot on the home screen.  A menu will pop up that allows you to choose Shortcuts, and Contact.  You can scroll through your contact list and then just tap on the name of the person you want to be able to dial with a single click. 2) Keep track of your data usage Yes, we all should keep a close eye on our data usage, because it is very easy to go over our limits and then end up with a giant bill at the end of the month.  Never get surprised when you open that mobile phone envelope again.  Go to Settings, then Data Usage, and you can find a quick rundown of your usage, how much data each app uses, and you can even set alarms to let you know when you are nearing the limits.   Better yet, you can set the phone to stop using data when it reaches a certain limit. 3) Bring back Good Grammar We often hear proclamations about the downfall of written language, and how texting abbreviations, misspellings, and lack of punctuation are the root of all evil.  Well, we can show all those doomsdayers that all is not lost by bringing punctuation back to texting.  Usually we leave it off when we text because it takes too long to get to the screen with all the punctuation options.  But now you can hold down the period (or “full stop”) button and a list of all the commonly-used punctuation marks will pop right up. 4) Apps, Apps, Apps and Apps And finally, I cannot end an article about smart phones without including a list of my favorite apps.  Here are a list of my Top 10 Applications on my Android (not counting social media apps). Advanced Task Killer – Keeps my phone snappy by closing un-necessary apps WhatsApp - my favorite alternate to Text SMS Flipboard - my ‘timepass’ moments Skype – keeps me close to friends and family GoogleMaps - I am never lost because of this one thing Amazon Kindle – Books my best friends DropBox - My data always safe Pluralsight Player – Learning never stops for me Samsung Kies Air – Connecting Phone to Computer Chrome – Replacing default browser I have not included any social media applications in the above list, but you can be sure that I am linked to Twitter, Facebook, Google+, LinkedIn, and YouTube. Reference: Pinal Dave (http://blog.SQLAuthority.com)   Filed under: Best Practices, PostADay, SQL, SQL Authority, SQL Query, SQL Server, SQL Tips and Tricks, SQLAuthority News, T SQL, Technology Tagged: Android, Personal Technology

    Read the article

  • Stack vs queue -based programming language efficiency [closed]

    - by Core Xii
    Suppose there are two programming languages; one where the only form of storage is one (preferred) or two (may be required for Turing-completeness) stacks, and another where the only form of storage is a single queue, with appropriate instructions in each to manipulate their respective storage to achieve Turing-completeness. Which one can more efficiently encode complex algorithms? Such that most given algorithms take less code to implement, less time to compute and less memory to do so. Also, how do they compare to a language with a traditional array (or unbounded tape, if you will) as storage?

    Read the article

  • Ball bouncing at a certain angle and efficiency computations

    - by X Y
    I would like to make a pong game with a small twist (for now). Every time the ball bounces off one of the paddles i want it to be under a certain angle (between a min and a max). I simply can't wrap my head around how to actually do it (i have some thoughts and such but i simply cannot implement them properly - i feel i'm overcomplicating things). Here's an image with a small explanation . One other problem would be that the conditions for bouncing have to be different for every edge. For example, in the picture, on the two small horizontal edges i do not want a perfectly vertical bounce when in the middle of the edge but rather a constant angle (pi/4 maybe) in either direction depending on the collision point (before the middle of the edge, or after). All of my collisions are done with the Separating Axes Theorem (and seem to work fine). I'm looking for something efficient because i want to add a lot of things later on (maybe polygons with many edges and such). So i need to keep to a minimum the amount of checking done every frame. The collision algorithm begins testing whenever the bounding boxes of the paddle and the ball intersect. Is there something better to test for possible collisions every frame? (more efficient in the long run,with many more objects etc, not necessarily easy to code). I'm going to post the code for my game: Paddle Class public class Paddle : Microsoft.Xna.Framework.DrawableGameComponent { #region Private Members private SpriteBatch spriteBatch; private ContentManager contentManager; private bool keybEnabled; private bool isLeftPaddle; private Texture2D paddleSprite; private Vector2 paddlePosition; private float paddleSpeedY; private Vector2 paddleScale = new Vector2(1f, 1f); private const float DEFAULT_Y_SPEED = 150; private Vector2[] Normals2Edges; private Vector2[] Vertices = new Vector2[4]; private List<Vector2> lst = new List<Vector2>(); private Vector2 Edge; #endregion #region Properties public float Speed { get {return paddleSpeedY; } set { paddleSpeedY = value; } } public Vector2[] Normal2EdgesVector { get { NormalsToEdges(this.isLeftPaddle); return Normals2Edges; } } public Vector2[] VertexVector { get { return Vertices; } } public Vector2 Scale { get { return paddleScale; } set { paddleScale = value; NormalsToEdges(this.isLeftPaddle); } } public float X { get { return paddlePosition.X; } set { paddlePosition.X = value; } } public float Y { get { return paddlePosition.Y; } set { paddlePosition.Y = value; } } public float Width { get { return (Scale.X == 1f ? (float)paddleSprite.Width : paddleSprite.Width * Scale.X); } } public float Height { get { return ( Scale.Y==1f ? (float)paddleSprite.Height : paddleSprite.Height*Scale.Y ); } } public Texture2D GetSprite { get { return paddleSprite; } } public Rectangle Boundary { get { return new Rectangle((int)paddlePosition.X, (int)paddlePosition.Y, (int)this.Width, (int)this.Height); } } public bool KeyboardEnabled { get { return keybEnabled; } } #endregion private void NormalsToEdges(bool isLeftPaddle) { Normals2Edges = null; Edge = Vector2.Zero; lst.Clear(); for (int i = 0; i < Vertices.Length; i++) { Edge = Vertices[i + 1 == Vertices.Length ? 0 : i + 1] - Vertices[i]; if (Edge != Vector2.Zero) { Edge.Normalize(); //outer normal to edge !! (origin in top-left) lst.Add(new Vector2(Edge.Y, -Edge.X)); } } Normals2Edges = lst.ToArray(); } public float[] ProjectPaddle(Vector2 axis) { if (Vertices.Length == 0 || axis == Vector2.Zero) return (new float[2] { 0, 0 }); float min, max; min = Vector2.Dot(axis, Vertices[0]); max = min; for (int i = 1; i < Vertices.Length; i++) { float p = Vector2.Dot(axis, Vertices[i]); if (p < min) min = p; else if (p > max) max = p; } return (new float[2] { min, max }); } public Paddle(Game game, bool isLeftPaddle, bool enableKeyboard = true) : base(game) { contentManager = new ContentManager(game.Services); keybEnabled = enableKeyboard; this.isLeftPaddle = isLeftPaddle; } public void setPosition(Vector2 newPos) { X = newPos.X; Y = newPos.Y; } public override void Initialize() { base.Initialize(); this.Speed = DEFAULT_Y_SPEED; X = 0; Y = 0; NormalsToEdges(this.isLeftPaddle); } protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); paddleSprite = contentManager.Load<Texture2D>(@"Content\pongBar"); } public override void Update(GameTime gameTime) { //vertices array Vertices[0] = this.paddlePosition; Vertices[1] = this.paddlePosition + new Vector2(this.Width, 0); Vertices[2] = this.paddlePosition + new Vector2(this.Width, this.Height); Vertices[3] = this.paddlePosition + new Vector2(0, this.Height); // Move paddle, but don't allow movement off the screen if (KeyboardEnabled) { float moveDistance = Speed * (float)gameTime.ElapsedGameTime.TotalSeconds; KeyboardState newKeyState = Keyboard.GetState(); if (newKeyState.IsKeyDown(Keys.Down) && Y + paddleSprite.Height + moveDistance <= Game.GraphicsDevice.Viewport.Height) { Y += moveDistance; } else if (newKeyState.IsKeyDown(Keys.Up) && Y - moveDistance >= 0) { Y -= moveDistance; } } else { if (this.Y + this.Height > this.GraphicsDevice.Viewport.Height) { this.Y = this.Game.GraphicsDevice.Viewport.Height - this.Height - 1; } } base.Update(gameTime); } public override void Draw(GameTime gameTime) { spriteBatch.Begin(SpriteSortMode.Texture,null); spriteBatch.Draw(paddleSprite, paddlePosition, null, Color.White, 0f, Vector2.Zero, Scale, SpriteEffects.None, 0); spriteBatch.End(); base.Draw(gameTime); } } Ball Class public class Ball : Microsoft.Xna.Framework.DrawableGameComponent { #region Private Members private SpriteBatch spriteBatch; private ContentManager contentManager; private const float DEFAULT_SPEED = 50; private float speedIncrement = 0; private Vector2 ballScale = new Vector2(1f, 1f); private const float INCREASE_SPEED = 50; private Texture2D ballSprite; //initial texture private Vector2 ballPosition; //position private Vector2 centerOfBall; //center coords private Vector2 ballSpeed = new Vector2(DEFAULT_SPEED, DEFAULT_SPEED); //speed #endregion #region Properties public float DEFAULTSPEED { get { return DEFAULT_SPEED; } } public Vector2 ballCenter { get { return centerOfBall; } } public Vector2 Scale { get { return ballScale; } set { ballScale = value; } } public float SpeedX { get { return ballSpeed.X; } set { ballSpeed.X = value; } } public float SpeedY { get { return ballSpeed.Y; } set { ballSpeed.Y = value; } } public float X { get { return ballPosition.X; } set { ballPosition.X = value; } } public float Y { get { return ballPosition.Y; } set { ballPosition.Y = value; } } public Texture2D GetSprite { get { return ballSprite; } } public float Width { get { return (Scale.X == 1f ? (float)ballSprite.Width : ballSprite.Width * Scale.X); } } public float Height { get { return (Scale.Y == 1f ? (float)ballSprite.Height : ballSprite.Height * Scale.Y); } } public float SpeedIncreaseIncrement { get { return speedIncrement; } set { speedIncrement = value; } } public Rectangle Boundary { get { return new Rectangle((int)ballPosition.X, (int)ballPosition.Y, (int)this.Width, (int)this.Height); } } #endregion public Ball(Game game) : base(game) { contentManager = new ContentManager(game.Services); } public void Reset() { ballSpeed.X = DEFAULT_SPEED; ballSpeed.Y = DEFAULT_SPEED; ballPosition.X = Game.GraphicsDevice.Viewport.Width / 2 - ballSprite.Width / 2; ballPosition.Y = Game.GraphicsDevice.Viewport.Height / 2 - ballSprite.Height / 2; } public void SpeedUp() { if (ballSpeed.Y < 0) ballSpeed.Y -= (INCREASE_SPEED + speedIncrement); else ballSpeed.Y += (INCREASE_SPEED + speedIncrement); if (ballSpeed.X < 0) ballSpeed.X -= (INCREASE_SPEED + speedIncrement); else ballSpeed.X += (INCREASE_SPEED + speedIncrement); } public float[] ProjectBall(Vector2 axis) { if (axis == Vector2.Zero) return (new float[2] { 0, 0 }); float min, max; min = Vector2.Dot(axis, this.ballCenter) - this.Width/2; //center - radius max = min + this.Width; //center + radius return (new float[2] { min, max }); } public void ChangeHorzDirection() { ballSpeed.X *= -1; } public void ChangeVertDirection() { ballSpeed.Y *= -1; } public override void Initialize() { base.Initialize(); ballPosition.X = Game.GraphicsDevice.Viewport.Width / 2 - ballSprite.Width / 2; ballPosition.Y = Game.GraphicsDevice.Viewport.Height / 2 - ballSprite.Height / 2; } protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); ballSprite = contentManager.Load<Texture2D>(@"Content\ball"); } public override void Update(GameTime gameTime) { if (this.Y < 1 || this.Y > GraphicsDevice.Viewport.Height - this.Height - 1) this.ChangeVertDirection(); centerOfBall = new Vector2(ballPosition.X + this.Width / 2, ballPosition.Y + this.Height / 2); base.Update(gameTime); } public override void Draw(GameTime gameTime) { spriteBatch.Begin(); spriteBatch.Draw(ballSprite, ballPosition, null, Color.White, 0f, Vector2.Zero, Scale, SpriteEffects.None, 0); spriteBatch.End(); base.Draw(gameTime); } } Main game class public class gameStart : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; public gameStart() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; this.Window.Title = "Pong game"; } protected override void Initialize() { ball = new Ball(this); paddleLeft = new Paddle(this,true,false); paddleRight = new Paddle(this,false,true); Components.Add(ball); Components.Add(paddleLeft); Components.Add(paddleRight); this.Window.AllowUserResizing = false; this.IsMouseVisible = true; this.IsFixedTimeStep = false; this.isColliding = false; base.Initialize(); } #region MyPrivateStuff private Ball ball; private Paddle paddleLeft, paddleRight; private int[] bit = { -1, 1 }; private Random rnd = new Random(); private int updates = 0; enum nrPaddle { None, Left, Right }; private nrPaddle PongBar = nrPaddle.None; private ArrayList Axes = new ArrayList(); private Vector2 MTV; //minimum translation vector private bool isColliding; private float overlap; //smallest distance after projections private Vector2 overlapAxis; //axis of overlap #endregion protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); paddleLeft.setPosition(new Vector2(0, this.GraphicsDevice.Viewport.Height / 2 - paddleLeft.Height / 2)); paddleRight.setPosition(new Vector2(this.GraphicsDevice.Viewport.Width - paddleRight.Width, this.GraphicsDevice.Viewport.Height / 2 - paddleRight.Height / 2)); paddleLeft.Scale = new Vector2(1f, 2f); //scale left paddle } private bool ShapesIntersect(Paddle paddle, Ball ball) { overlap = 1000000f; //large value overlapAxis = Vector2.Zero; MTV = Vector2.Zero; foreach (Vector2 ax in Axes) { float[] pad = paddle.ProjectPaddle(ax); //pad0 = min, pad1 = max float[] circle = ball.ProjectBall(ax); //circle0 = min, circle1 = max if (pad[1] <= circle[0] || circle[1] <= pad[0]) { return false; } if (pad[1] - circle[0] < circle[1] - pad[0]) { if (Math.Abs(overlap) > Math.Abs(-pad[1] + circle[0])) { overlap = -pad[1] + circle[0]; overlapAxis = ax; } } else { if (Math.Abs(overlap) > Math.Abs(circle[1] - pad[0])) { overlap = circle[1] - pad[0]; overlapAxis = ax; } } } if (overlapAxis != Vector2.Zero) { MTV = overlapAxis * overlap; } return true; } protected override void Update(GameTime gameTime) { updates += 1; float ftime = 5 * (float)gameTime.ElapsedGameTime.TotalSeconds; if (updates == 1) { isColliding = false; int Xrnd = bit[Convert.ToInt32(rnd.Next(0, 2))]; int Yrnd = bit[Convert.ToInt32(rnd.Next(0, 2))]; ball.SpeedX = Xrnd * ball.SpeedX; ball.SpeedY = Yrnd * ball.SpeedY; ball.X += ftime * ball.SpeedX; ball.Y += ftime * ball.SpeedY; } else { updates = 100; ball.X += ftime * ball.SpeedX; ball.Y += ftime * ball.SpeedY; } //autorun :) paddleLeft.Y = ball.Y; //collision detection PongBar = nrPaddle.None; if (ball.Boundary.Intersects(paddleLeft.Boundary)) { PongBar = nrPaddle.Left; if (!isColliding) { Axes.Clear(); Axes.AddRange(paddleLeft.Normal2EdgesVector); //axis from nearest vertex to ball's center Axes.Add(FORMULAS.NormAxisFromCircle2ClosestVertex(paddleLeft.VertexVector, ball.ballCenter)); } } else if (ball.Boundary.Intersects(paddleRight.Boundary)) { PongBar = nrPaddle.Right; if (!isColliding) { Axes.Clear(); Axes.AddRange(paddleRight.Normal2EdgesVector); //axis from nearest vertex to ball's center Axes.Add(FORMULAS.NormAxisFromCircle2ClosestVertex(paddleRight.VertexVector, ball.ballCenter)); } } if (PongBar != nrPaddle.None && !isColliding) switch (PongBar) { case nrPaddle.Left: if (ShapesIntersect(paddleLeft, ball)) { isColliding = true; if (MTV != Vector2.Zero) ball.X += MTV.X; ball.Y += MTV.Y; ball.ChangeHorzDirection(); } break; case nrPaddle.Right: if (ShapesIntersect(paddleRight, ball)) { isColliding = true; if (MTV != Vector2.Zero) ball.X += MTV.X; ball.Y += MTV.Y; ball.ChangeHorzDirection(); } break; default: break; } if (!ShapesIntersect(paddleRight, ball) && !ShapesIntersect(paddleLeft, ball)) isColliding = false; ball.X += ftime * ball.SpeedX; ball.Y += ftime * ball.SpeedY; //check ball movement if (ball.X > paddleRight.X + paddleRight.Width + 2) { //IncreaseScore(Left); ball.Reset(); updates = 0; return; } else if (ball.X < paddleLeft.X - 2) { //IncreaseScore(Right); ball.Reset(); updates = 0; return; } base.Update(gameTime); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Aquamarine); spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); spriteBatch.End(); base.Draw(gameTime); } } And one method i've used: public static Vector2 NormAxisFromCircle2ClosestVertex(Vector2[] vertices, Vector2 circle) { Vector2 temp = Vector2.Zero; if (vertices.Length > 0) { float dist = (circle.X - vertices[0].X) * (circle.X - vertices[0].X) + (circle.Y - vertices[0].Y) * (circle.Y - vertices[0].Y); for (int i = 1; i < vertices.Length;i++) { if (dist > (circle.X - vertices[i].X) * (circle.X - vertices[i].X) + (circle.Y - vertices[i].Y) * (circle.Y - vertices[i].Y)) { temp = vertices[i]; //memorize the closest vertex dist = (circle.X - vertices[i].X) * (circle.X - vertices[i].X) + (circle.Y - vertices[i].Y) * (circle.Y - vertices[i].Y); } } temp = circle - temp; temp.Normalize(); } return temp; } Thanks in advance for any tips on the 4 issues. EDIT1: Something isn't working properly. The collision axis doesn't come out right and the interpolation also seems to have no effect. I've changed the code a bit: private bool ShapesIntersect(Paddle paddle, Ball ball) { overlap = 1000000f; //large value overlapAxis = Vector2.Zero; MTV = Vector2.Zero; foreach (Vector2 ax in Axes) { float[] pad = paddle.ProjectPaddle(ax); //pad0 = min, pad1 = max float[] circle = ball.ProjectBall(ax); //circle0 = min, circle1 = max if (pad[1] < circle[0] || circle[1] < pad[0]) { return false; } if (Math.Abs(pad[1] - circle[0]) < Math.Abs(circle[1] - pad[0])) { if (Math.Abs(overlap) > Math.Abs(-pad[1] + circle[0])) { overlap = -pad[1] + circle[0]; overlapAxis = ax * (-1); } //to get the proper axis } else { if (Math.Abs(overlap) > Math.Abs(circle[1] - pad[0])) { overlap = circle[1] - pad[0]; overlapAxis = ax; } } } if (overlapAxis != Vector2.Zero) { MTV = overlapAxis * Math.Abs(overlap); } return true; } And part of the Update method: if (ShapesIntersect(paddleRight, ball)) { isColliding = true; if (MTV != Vector2.Zero) { ball.X += MTV.X; ball.Y += MTV.Y; } //test if (overlapAxis.X == 0) //collision with horizontal edge { } else if (overlapAxis.Y == 0) //collision with vertical edge { float factor = Math.Abs(ball.ballCenter.Y - paddleRight.Y) / paddleRight.Height; if (factor > 1) factor = 1f; if (overlapAxis.X < 0) //left edge? ball.Speed = ball.DEFAULTSPEED * Vector2.Normalize(Vector2.Reflect(ball.Speed, (Vector2.Lerp(new Vector2(-1, -3), new Vector2(-1, 3), factor)))); else //right edge? ball.Speed = ball.DEFAULTSPEED * Vector2.Normalize(Vector2.Reflect(ball.Speed, (Vector2.Lerp(new Vector2(1, -3), new Vector2(1, 3), factor)))); } else //vertex collision??? { ball.Speed = -ball.Speed; } } What seems to happen is that "overlapAxis" doesn't always return the right one. So instead of (-1,0) i get the (1,0) (this happened even before i multiplied with -1 there). Sometimes there isn't even a collision registered even though the ball passes through the paddle... The interpolation also seems to have no effect as the angles barely change (or the overlapAxis is almost never (-1,0) or (1,0) but something like (0.9783473, 0.02743843)... ). What am i missing here? :(

    Read the article

  • what is the Web development process efficiency judgment criteria

    - by Ahmed safan
    I'm working as a web developer and I want to be able to determine if I'm efficient. Does this include the how long it take to accomplish tasks such as: Server side code for the site logic with one language or multiple php,asp,asp.net. Client side code like javascript with jquery for ajax, menus and other interactivity Page layout, html, css (color, fonts (but I have no artistic sense!)) The needs of the site and how it will work (planning) How can i judge how long it will take to complete a website? The site has CMS for adding and editing news, products, articles on the experience of the company. Also, they can edit team work, add Recreational Activities and a logo gallery with compressed psd download, and send messages to cpanel and to email. You are starting from scratch except JQuery and PHPmailer. How can I estimate how long the job will take, and how can I calculate the required time to finish any new projects? I'm so sorry for many scattered questions, but I'm in my first experiment and I want to take benefits from the great experience of those who have it.

    Read the article

  • Inline template efficiency

    - by Darryl Gove
    I like inline templates, and use them quite extensively. Whenever I write code with them I'm always careful to check the disassembly to see that the resulting output is efficient. Here's a potential cause of inefficiency. Suppose we want to use the mis-named Leading Zero Detect (LZD) instruction on T4 (this instruction does a count of the number of leading zero bits in an integer register - so it should really be called leading zero count). So we put together an inline template called lzd.il looking like: .inline lzd lzd %o0,%o0 .end And we throw together some code that uses it: int lzd(int); int a; int c=0; int main() { for(a=0; a<1000; a++) { c=lzd(c); } return 0; } We compile the code with some amount of optimisation, and look at the resulting code: $ cc -O -xtarget=T4 -S lzd.c lzd.il $ more lzd.s .L77000018: /* 0x001c 11 */ lzd %o0,%o0 /* 0x0020 9 */ ld [%i1],%i3 /* 0x0024 11 */ st %o0,[%i2] /* 0x0028 9 */ add %i3,1,%i0 /* 0x002c */ cmp %i0,999 /* 0x0030 */ ble,pt %icc,.L77000018 /* 0x0034 */ st %i0,[%i1] What is surprising is that we're seeing a number of loads and stores in the code. Everything could be held in registers, so why is this happening? The problem is that the code is only inlined at the code generation stage - when the actual instructions are generated. Earlier compiler phases see a function call. The called functions can do all kinds of nastiness to global variables (like 'a' in this code) so we need to load them from memory after the function call, and store them to memory before the function call. Fortunately we can use a #pragma directive to tell the compiler that the routine lzd() has no side effects - meaning that it does not read or write to memory. The directive to do that is #pragma no_side_effect(<routine name), and it needs to be placed after the declaration of the function. The new code looks like: int lzd(int); #pragma no_side_effect(lzd) int a; int c=0; int main() { for(a=0; a<1000; a++) { c=lzd(c); } return 0; } Now the loop looks much neater: /* 0x0014 10 */ add %i1,1,%i1 ! 11 ! { ! 12 ! c=lzd(c); /* 0x0018 12 */ lzd %o0,%o0 /* 0x001c 10 */ cmp %i1,999 /* 0x0020 */ ble,pt %icc,.L77000018 /* 0x0024 */ nop

    Read the article

  • Memory read/write access efficiency

    - by wolfPack88
    I've heard conflicting information from different sources, and I'm not really sure which one to believe. As such, I'll post what I understand and ask for corrections. Let's say I want to use a 2D matrix. There are three ways that I can do this (at least that I know of). 1: int i; char **matrix; matrix = malloc(50 * sizeof(char *)); for(i = 0; i < 50; i++) matrix[i] = malloc(50); 2: int i; int rowSize = 50; int pointerSize = 50 * sizeof(char *); int dataSize = 50 * 50; char **matrix; matrix = malloc(dataSize + pointerSize); char *pData = matrix + pointerSize - rowSize; for(i = 0; i < 50; i++) { pData += rowSize; matrix[i] = pData; } 3: //instead of accessing matrix[i][j] here, we would access matrix[i * 50 + j] char *matrix = malloc(50 * 50); In terms of memory usage, my understanding is that 3 is the most efficient, 2 is next, and 1 is least efficient, for the reasons below: 3: There is only one pointer and one allocation, and therefore, minimal overhead. 2: Once again, there is only one allocation, but there are now 51 pointers. This means there is 50 * sizeof(char *) more overhead. 1: There are 51 allocations and 51 pointers, causing the most overhead of all options. In terms of performance, once again my understanding is that 3 is the most efficient, 2 is next, and 1 is least efficient. Reasons being: 3: Only one memory access is needed. We will have to do a multiplication and an addition as opposed to two additions (as in the case of a pointer to a pointer), but memory access is slow enough that this doesn't matter. 2: We need two memory accesses; once to get a char *, and then to the appropriate char. Only two additions are performed here (once to get to the correct char * pointer from the original memory location, and once to get to the correct char variable from wherever the char * points to), so multiplication (which is slower than addition) is not required. However, on modern CPUs, multiplication is faster than memory access, so this point is moot. 1: Same issues as 2, but now the memory isn't contiguous. This causes cache misses and extra page table lookups, making it the least efficient of the lot. First and foremost: Is this correct? Second: Is there an option 4 that I am missing that would be even more efficient?

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >