Daily Archives

Articles indexed Wednesday June 26 2013

Page 13/19 | < Previous Page | 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • Go up one directory in mod_rewrite

    - by Rudolph Gottesheim
    I've got a standard Zend Framework 1 project that looks a bit like this: Project |- public |- .htaccess |- index.php The .htaccess looks like this: RewriteEngine On RewriteBase / RewriteRule ^image/.*$ img.php?file=$1 [NC,L] RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^.*$ - [NC,L] RewriteRule ^.*$ index.php [NC,L] Now I want to start transitioning the site to Zend Framework 2, which I put in a separate directory in the root, so the whole thing looks like this: Project |- public |- .htaccess |- index.php |- zf2 |- public |- .htaccess |- index.php What would I have to change in my original (ZF1) .htaccess to route all requests to (for example) /zf2/whatever to ZF2's index.php? I've tried RewriteRule ^zf2(/.*)$ ../zf2/public/index.php [NC,L] in the line after RewriteBase /, but that just gives me a 400 Bad Request.

    Read the article

  • I want to combine the databases from two different sites under one URL. How is this possible?

    - by Punct Ulica
    I have a small site that I want to merge with a bigger one. How can I merge the second one with the first? I know that one solution would be to make the smaller one a subdomain of the bigger one, but I would like the following thing to happen: when I click on a category or a tag, posts from both sites/databases would appear. Something like Smashing Magazine did when it assimilated designinformer.com. The other solution and the one that I would prefer would be to merge the two databases, but I don't know if this is possible.

    Read the article

  • A drop in SERP after following webmaster guidelines [on hold]

    - by digiwig
    So here's a puzzle for all you SEO gurus out there. I recently launched my own site. I had target keywords which were ranking very well for about 1 month, within the top five and even appearing in first place. In an attempt to maintain good positioning, I followed guidelines by adding robots.txt, an xml sitemap redirecting non-www to www redirecting index.php to root domain adding htaccess 301 redirect for old pages I added rich snippets created a google+ account, verified my picture to appear, I went through each of the webmaster issues with duplicate titles and meta descriptions and improved header tag document outlines i even created a few more blog posts to keep the content freshing and moving. So now my website appears on page 2 with my target keywords - and all because I followed the guidelines. What is happening? I see competitors with stagnant content superglued to position 1.

    Read the article

  • Canonical redirection meta tag [duplicate]

    - by sankalp
    This question already has an answer here: How to use rel='canonical' properly 2 answers There are two pages in my website with the same content; only the URL's are different: www.websitename.com and www.websitename.com/default.html. Someone suggested that I should add canonical tags to avoid them being considered as duplicate content. Where should I add canonical tags and why?

    Read the article

  • Google AdSense scorecard : Text and image ads enabled is marked as Yellow

    - by Shivan Raptor
    Start with definitions: Yellow: Satisfactory. You could make some further improvements to this item. I have few sites using Google AdSense to make cents (yes, cents only). On recent update of Google AdSense, a new module called Scorecard displayed on my dashboard. In item Revenue optimization Text and image ads enabled , it is marked as Yellow. But I have already enabled Text and Image ads in all my sites. Why does it still having Yellow instead of Green? Is it a bug of Google AdSense Scorecard ?

    Read the article

  • Java Animation Memory Overload [on hold]

    - by user2425429
    I need a way to reduce the memory usage of these programs while keeping the functionality. Every time I add 50 milliseconds or so to the set&display loop in AnimationTest1, it throws an out of memory error. Here is the code I have now: import java.awt.DisplayMode; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Polygon; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import javax.swing.ImageIcon; public class AnimationTest1 { public static void main(String args[]) { AnimationTest1 test = new AnimationTest1(); test.run(); } private static final DisplayMode POSSIBLE_MODES[] = { new DisplayMode(800, 600, 32, 0), new DisplayMode(800, 600, 24, 0), new DisplayMode(800, 600, 16, 0), new DisplayMode(640, 480, 32, 0), new DisplayMode(640, 480, 24, 0), new DisplayMode(640, 480, 16, 0) }; private static final long DEMO_TIME = 4000; private ScreenManager screen; private Image bgImage; private Animation anim; public void loadImages() { // create animation List<Polygon> polygons=new ArrayList(); int[] x=new int[]{20,4,4,20,40,56,56,40}; int[] y=new int[]{20,32,40,44,44,40,32,20}; polygons.add(new Polygon(x,y,8)); anim = new Animation(); //# of frames long startTime = System.currentTimeMillis(); long currTimer = startTime; long elapsedTime = 0; boolean animated = false; Graphics2D g = screen.getGraphics(); int width=200; int height=200; //set&display loop while (currTimer - startTime < DEMO_TIME*2) { //draw the polygons if(!animated){ for(int j=0; j<polygons.size();j++){ for(int pos=0; pos<polygons.get(j).npoints; pos++){ polygons.get(j).xpoints[pos]+=1; } } anim.setNewPolyFrame(polygons , width , height , 64); } else{ // update animation anim.update(elapsedTime); draw(g); g.dispose(); screen.update(); try{ Thread.sleep(20); } catch(InterruptedException ie){} } if(currTimer - startTime == DEMO_TIME) animated=true; elapsedTime = System.currentTimeMillis() - currTimer; currTimer += elapsedTime; } } public void run() { screen = new ScreenManager(); try { DisplayMode displayMode = screen.findFirstCompatibleMode(POSSIBLE_MODES); screen.setFullScreen(displayMode); loadImages(); } finally { screen.restoreScreen(); } } public void draw(Graphics g) { // draw background g.drawImage(bgImage, 0, 0, null); // draw image g.drawImage(anim.getImage(), 0, 0, null); } } ScreenManager: import java.awt.Color; import java.awt.DisplayMode; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Toolkit; import java.awt.Window; import java.awt.event.KeyListener; import java.awt.event.MouseListener; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import javax.swing.JFrame; import javax.swing.JPanel; public class ScreenManager extends JPanel { private GraphicsDevice device; /** Creates a new ScreenManager object. */ public ScreenManager() { GraphicsEnvironment environment=GraphicsEnvironment.getLocalGraphicsEnvironment(); device = environment.getDefaultScreenDevice(); setBackground(Color.white); } /** Returns a list of compatible display modes for the default device on the system. */ public DisplayMode[] getCompatibleDisplayModes() { return device.getDisplayModes(); } /** Returns the first compatible mode in a list of modes. Returns null if no modes are compatible. */ public DisplayMode findFirstCompatibleMode( DisplayMode modes[]) { DisplayMode goodModes[] = device.getDisplayModes(); for (int i = 0; i < modes.length; i++) { for (int j = 0; j < goodModes.length; j++) { if (displayModesMatch(modes[i], goodModes[j])) { return modes[i]; } } } return null; } /** Returns the current display mode. */ public DisplayMode getCurrentDisplayMode() { return device.getDisplayMode(); } /** Determines if two display modes "match". Two display modes match if they have the same resolution, bit depth, and refresh rate. The bit depth is ignored if one of the modes has a bit depth of DisplayMode.BIT_DEPTH_MULTI. Likewise, the refresh rate is ignored if one of the modes has a refresh rate of DisplayMode.REFRESH_RATE_UNKNOWN. */ public boolean displayModesMatch(DisplayMode mode1, DisplayMode mode2) { if (mode1.getWidth() != mode2.getWidth() || mode1.getHeight() != mode2.getHeight()) { return false; } if (mode1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && mode2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && mode1.getBitDepth() != mode2.getBitDepth()) { return false; } if (mode1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && mode2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && mode1.getRefreshRate() != mode2.getRefreshRate()) { return false; } return true; } /** Enters full screen mode and changes the display mode. If the specified display mode is null or not compatible with this device, or if the display mode cannot be changed on this system, the current display mode is used. <p> The display uses a BufferStrategy with 2 buffers. */ public void setFullScreen(DisplayMode displayMode) { JFrame frame = new JFrame(); frame.setUndecorated(true); frame.setIgnoreRepaint(true); frame.setResizable(true); device.setFullScreenWindow(frame); if (displayMode != null && device.isDisplayChangeSupported()) { try { device.setDisplayMode(displayMode); } catch (IllegalArgumentException ex) { } } frame.createBufferStrategy(2); Graphics g=frame.getGraphics(); g.setColor(Color.white); g.drawRect(0, 0, frame.WIDTH, frame.HEIGHT); frame.paintAll(g); g.setColor(Color.black); g.dispose(); } /** Gets the graphics context for the display. The ScreenManager uses double buffering, so applications must call update() to show any graphics drawn. <p> The application must dispose of the graphics object. */ public Graphics2D getGraphics() { Window window = device.getFullScreenWindow(); if (window != null) { BufferStrategy strategy = window.getBufferStrategy(); return (Graphics2D)strategy.getDrawGraphics(); } else { return null; } } /** Updates the display. */ public void update() { Window window = device.getFullScreenWindow(); if (window != null) { BufferStrategy strategy = window.getBufferStrategy(); if (!strategy.contentsLost()) { strategy.show(); } } // Sync the display on some systems. // (on Linux, this fixes event queue problems) Toolkit.getDefaultToolkit().sync(); } /** Returns the window currently used in full screen mode. Returns null if the device is not in full screen mode. */ public Window getFullScreenWindow() { return device.getFullScreenWindow(); } /** Returns the width of the window currently used in full screen mode. Returns 0 if the device is not in full screen mode. */ public int getWidth() { Window window = device.getFullScreenWindow(); if (window != null) { return window.getWidth(); } else { return 0; } } /** Returns the height of the window currently used in full screen mode. Returns 0 if the device is not in full screen mode. */ public int getHeight() { Window window = device.getFullScreenWindow(); if (window != null) { return window.getHeight(); } else { return 0; } } /** Restores the screen's display mode. */ public void restoreScreen() { Window window = device.getFullScreenWindow(); if (window != null) { window.dispose(); } device.setFullScreenWindow(null); } /** Creates an image compatible with the current display. */ public BufferedImage createCompatibleImage(int w, int h, int transparency) { Window window = device.getFullScreenWindow(); if (window != null) { GraphicsConfiguration gc = window.getGraphicsConfiguration(); return gc.createCompatibleImage(w, h, transparency); } return null; } } Animation: import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Polygon; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.List; /** The Animation class manages a series of images (frames) and the amount of time to display each frame. */ public class Animation { private ArrayList frames; private int currFrameIndex; private long animTime; private long totalDuration; /** Creates a new, empty Animation. */ public Animation() { frames = new ArrayList(); totalDuration = 0; start(); } /** Adds an image to the animation with the specified duration (time to display the image). */ public synchronized void addFrame(BufferedImage image, long duration){ ScreenManager s = new ScreenManager(); totalDuration += duration; frames.add(new AnimFrame(image, totalDuration)); } /** Starts the animation over from the beginning. */ public synchronized void start() { animTime = 0; currFrameIndex = 0; } /** Updates the animation's current image (frame), if necessary. */ public synchronized void update(long elapsedTime) { if (frames.size() >= 1) { animTime += elapsedTime; /*if (animTime >= totalDuration) { animTime = animTime % totalDuration; currFrameIndex = 0; }*/ while (animTime > getFrame(0).endTime) { frames.remove(0); } } } /** Gets the Animation's current image. Returns null if this animation has no images. */ public synchronized Image getImage() { if (frames.size() > 0&&!(currFrameIndex>=frames.size())) { return getFrame(currFrameIndex).image; } else{ System.out.println("There are no frames!"); System.exit(0); } return null; } private AnimFrame getFrame(int i) { return (AnimFrame)frames.get(i); } private class AnimFrame { Image image; long endTime; public AnimFrame(Image image, long endTime) { this.image = image; this.endTime = endTime; } } public void setNewPolyFrame(List<Polygon> polys,int imagewidth,int imageheight,int time){ BufferedImage image=new BufferedImage(imagewidth, imageheight, 1); Graphics g=image.getGraphics(); for(int i=0;i<polys.size();i++){ g.drawPolygon(polys.get(i)); } addFrame(image,time); g.dispose(); } }

    Read the article

  • Animation Color [on hold]

    - by user2425429
    I'm having problems in my java program for animation. I'm trying to draw a hexagon with a shape similar to that of a trapezoid. Then, I'm making it move to the right for a certain amount of time (DEMO_TIME). Animation and ScreenManager are "API" classes, and AnimationTest1 is a demo. In my test program, it runs with a black screen and white stroke color. I'd like to know why this happened and how to fix it. I'm a beginner, so I apologize for this question being stupid to all you game programmers. Here is the code I have now: import java.awt.DisplayMode; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Polygon; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import javax.swing.ImageIcon; public class AnimationTest1 { public static void main(String args[]) { AnimationTest1 test = new AnimationTest1(); test.run(); } private static final DisplayMode POSSIBLE_MODES[] = { new DisplayMode(800, 600, 32, 0), new DisplayMode(800, 600, 24, 0), new DisplayMode(800, 600, 16, 0), new DisplayMode(640, 480, 32, 0), new DisplayMode(640, 480, 24, 0), new DisplayMode(640, 480, 16, 0) }; private static final long DEMO_TIME = 4000; private ScreenManager screen; private Image bgImage; private Animation anim; public void loadImages() { // create animation List<Polygon> polygons=new ArrayList(); int[] x=new int[]{20,4,4,20,40,56,56,40}; int[] y=new int[]{20,32,40,44,44,40,32,20}; polygons.add(new Polygon(x,y,8)); anim = new Animation(); //# of frames long startTime = System.currentTimeMillis(); long currTimer = startTime; long elapsedTime = 0; boolean animated = false; Graphics2D g = screen.getGraphics(); int width=200; int height=200; while (currTimer - startTime < DEMO_TIME*2) { //draw the polygons if(!animated){ for(int j=0; j<polygons.size();j++){ for(int pos=0; pos<polygons.get(j).npoints; pos++){ polygons.get(j).xpoints[pos]+=1; } } anim.setNewPolyFrame(polygons , width , height , 64); } else{ // update animation anim.update(elapsedTime); draw(g); g.dispose(); screen.update(); try{ Thread.sleep(20); } catch(InterruptedException ie){} } if(currTimer - startTime == DEMO_TIME) animated=true; elapsedTime = System.currentTimeMillis() - currTimer; currTimer += elapsedTime; } } public void run() { screen = new ScreenManager(); try { DisplayMode displayMode = screen.findFirstCompatibleMode(POSSIBLE_MODES); screen.setFullScreen(displayMode); loadImages(); } finally { screen.restoreScreen(); } } public void draw(Graphics g) { // draw background g.drawImage(bgImage, 0, 0, null); // draw image g.drawImage(anim.getImage(), 0, 0, null); } } ScreenManager: import java.awt.Color; import java.awt.DisplayMode; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Toolkit; import java.awt.Window; import java.awt.event.KeyListener; import java.awt.event.MouseListener; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import javax.swing.JFrame; import javax.swing.JPanel; public class ScreenManager extends JPanel { private GraphicsDevice device; /** Creates a new ScreenManager object. */ public ScreenManager() { GraphicsEnvironment environment=GraphicsEnvironment.getLocalGraphicsEnvironment(); device = environment.getDefaultScreenDevice(); setBackground(Color.white); } /** Returns a list of compatible display modes for the default device on the system. */ public DisplayMode[] getCompatibleDisplayModes() { return device.getDisplayModes(); } /** Returns the first compatible mode in a list of modes. Returns null if no modes are compatible. */ public DisplayMode findFirstCompatibleMode( DisplayMode modes[]) { DisplayMode goodModes[] = device.getDisplayModes(); for (int i = 0; i < modes.length; i++) { for (int j = 0; j < goodModes.length; j++) { if (displayModesMatch(modes[i], goodModes[j])) { return modes[i]; } } } return null; } /** Returns the current display mode. */ public DisplayMode getCurrentDisplayMode() { return device.getDisplayMode(); } /** Determines if two display modes "match". Two display modes match if they have the same resolution, bit depth, and refresh rate. The bit depth is ignored if one of the modes has a bit depth of DisplayMode.BIT_DEPTH_MULTI. Likewise, the refresh rate is ignored if one of the modes has a refresh rate of DisplayMode.REFRESH_RATE_UNKNOWN. */ public boolean displayModesMatch(DisplayMode mode1, DisplayMode mode2) { if (mode1.getWidth() != mode2.getWidth() || mode1.getHeight() != mode2.getHeight()) { return false; } if (mode1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && mode2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && mode1.getBitDepth() != mode2.getBitDepth()) { return false; } if (mode1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && mode2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && mode1.getRefreshRate() != mode2.getRefreshRate()) { return false; } return true; } /** Enters full screen mode and changes the display mode. If the specified display mode is null or not compatible with this device, or if the display mode cannot be changed on this system, the current display mode is used. <p> The display uses a BufferStrategy with 2 buffers. */ public void setFullScreen(DisplayMode displayMode) { JFrame frame = new JFrame(); frame.setUndecorated(true); frame.setIgnoreRepaint(true); frame.setResizable(true); device.setFullScreenWindow(frame); if (displayMode != null && device.isDisplayChangeSupported()) { try { device.setDisplayMode(displayMode); } catch (IllegalArgumentException ex) { } } frame.createBufferStrategy(2); Graphics g=frame.getGraphics(); g.setColor(Color.white); g.drawRect(0, 0, frame.WIDTH, frame.HEIGHT); frame.paintAll(g); g.setColor(Color.black); g.dispose(); } /** Gets the graphics context for the display. The ScreenManager uses double buffering, so applications must call update() to show any graphics drawn. <p> The application must dispose of the graphics object. */ public Graphics2D getGraphics() { Window window = device.getFullScreenWindow(); if (window != null) { BufferStrategy strategy = window.getBufferStrategy(); return (Graphics2D)strategy.getDrawGraphics(); } else { return null; } } /** Updates the display. */ public void update() { Window window = device.getFullScreenWindow(); if (window != null) { BufferStrategy strategy = window.getBufferStrategy(); if (!strategy.contentsLost()) { strategy.show(); } } // Sync the display on some systems. // (on Linux, this fixes event queue problems) Toolkit.getDefaultToolkit().sync(); } /** Returns the window currently used in full screen mode. Returns null if the device is not in full screen mode. */ public Window getFullScreenWindow() { return device.getFullScreenWindow(); } /** Returns the width of the window currently used in full screen mode. Returns 0 if the device is not in full screen mode. */ public int getWidth() { Window window = device.getFullScreenWindow(); if (window != null) { return window.getWidth(); } else { return 0; } } /** Returns the height of the window currently used in full screen mode. Returns 0 if the device is not in full screen mode. */ public int getHeight() { Window window = device.getFullScreenWindow(); if (window != null) { return window.getHeight(); } else { return 0; } } /** Restores the screen's display mode. */ public void restoreScreen() { Window window = device.getFullScreenWindow(); if (window != null) { window.dispose(); } device.setFullScreenWindow(null); } /** Creates an image compatible with the current display. */ public BufferedImage createCompatibleImage(int w, int h, int transparency) { Window window = device.getFullScreenWindow(); if (window != null) { GraphicsConfiguration gc = window.getGraphicsConfiguration(); return gc.createCompatibleImage(w, h, transparency); } return null; } } Animation: import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Polygon; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.List; /** The Animation class manages a series of images (frames) and the amount of time to display each frame. */ public class Animation { private ArrayList frames; private int currFrameIndex; private long animTime; private long totalDuration; /** Creates a new, empty Animation. */ public Animation() { frames = new ArrayList(); totalDuration = 0; start(); } /** Adds an image to the animation with the specified duration (time to display the image). */ public synchronized void addFrame(BufferedImage image, long duration){ ScreenManager s = new ScreenManager(); totalDuration += duration; frames.add(new AnimFrame(image, totalDuration)); } /** Starts the animation over from the beginning. */ public synchronized void start() { animTime = 0; currFrameIndex = 0; } /** Updates the animation's current image (frame), if necessary. */ public synchronized void update(long elapsedTime) { if (frames.size() >= 1) { animTime += elapsedTime; /*if (animTime >= totalDuration) { animTime = animTime % totalDuration; currFrameIndex = 0; }*/ while (animTime > getFrame(0).endTime) { frames.remove(0); } } } /** Gets the Animation's current image. Returns null if this animation has no images. */ public synchronized Image getImage() { if (frames.size() > 0&&!(currFrameIndex>=frames.size())) { return getFrame(currFrameIndex).image; } else{ System.out.println("There are no frames!"); System.exit(0); } return null; } private AnimFrame getFrame(int i) { return (AnimFrame)frames.get(i); } private class AnimFrame { Image image; long endTime; public AnimFrame(Image image, long endTime) { this.image = image; this.endTime = endTime; } } public void setNewPolyFrame(List<Polygon> polys,int imagewidth,int imageheight,int time){ BufferedImage image=new BufferedImage(imagewidth, imageheight, 1); Graphics g=image.getGraphics(); for(int i=0;i<polys.size();i++){ g.drawPolygon(polys.get(i)); } addFrame(image,time); g.dispose(); } }

    Read the article

  • Geometry Shader : points + Triangles

    - by CmasterG
    I have different Shaders and for each Shader a instance of the ShaderClass class, which initializes the Shaders, Renders the Shaders, etc. I use most of the Shaderclasses without Geometry Shader, but in one Shader Class i also use a Geometry Shader. The problem is, that when I render one object with the Shaderclass that uses the Geometry shader, all other object are rendered with the same geometry that I create in the Geometry Shader. Can you help me? Is it possible that I have to use a Geometry Shader for each object, when I use one for one object? I use DirectX 11 with C++.

    Read the article

  • The most efficent ways for drawing lines all day long with OpenGL

    - by nkint
    I'd like to put a computer screen that is running an OpenGL programs in a room. It has to run all day long (not in the night). I'd like to draw lines that are slowly fading in the background. The setting is simple: a uniform color background (say, black) and colored lines (say, white) that are slowly fading out. With slowly I mean.. hours. Say that the first line I draw is with alpha 255 (fully visible), after one hours is 240. After 10 hours is 105. One line could have 250 points and there will be like 300 line in one day. For now I have done a prototype with very rudimentary method like: glBegin( GL_LINE_STRIP ); iterator = point_list.begin(); for (++iterator, end = point_list.end(); iterator != end; ++iterator) { const Vec3D &v = *iterator; glVertex2f(v.x(), v.y()); } glEnd(); More efficient method?

    Read the article

  • Auto-organized / smart inventory system?

    - by VeXe
    for the past week I've been working on an inventory system with Unity3D. At first I got help from the guys at Design3 but it wasn't too long till we split path, because I really didn't like the way they did their code, it didn't have any smell of OOP whatsoever. I took it further steps ahead - items take more than one slot, advanced placement system (items tries their best to find the best close fit), local mouse system (mouse gets trapped in active bag area), etc. Here's a demo of my work. What we would like to have in our game, is an auto-organizing feature - not auto-sort. We want this feature because our inventory's going to be in 'real-time' - not like in Resident Evil 1,2,3 etc where you would pause the game and do things in your inventory. Now imagine your self in a sticky situation surrounded by zombies, and you don't have bullets, you look around, you see that there are bullets nearby on the ground, so you go for them and try to pick them up, but they don't fit! you look at your inventory and find out that if you reorganize some of the items, it will fit! - now the player - in that situation doesn't have time to reorganize because he's surrounded with zombies and will die if he stops and organizes the inventory to make space (remember inventory in real-time, no pausing) - wouldn't it be nice for that to happen automatically? - Yes! (I believe this has been implemented in some games like Dungeon siege or something, so sure it's doable) take a look at this picture for example: Yes, so if you auto-sort the issue you will get your spaces but it's bad because: 1- Expensive: it doesn't need a whole sort operation to free those spaces, in the first picture, just slide the red item at the bottom to the very left, and you get the same spaces that you got from the auto-sort. 2- It's annoying to the player: "Who the F told you to re-order my stuff?" I'm not asking for "How to write the code" for this, I'm just asking for some guidance, where to look, what algorithms are involved? Is this something related to graphs and shortest path stuff? I hope not cuz I didn't manage to continue my college studies :/ But even if it is, just tell me and I will learn the stuff related. Notice there could be more than just one solution. So I guess the first thing I have to do is figure out if the situation is 'solvable' - if I know how to determine if a situation is solvable or not, then I can 'solve' it. I just need to know the conditions that makes it 'solvable'. And I believe there must be some algorithm/data structure for this. Here's a pic for more than one solution of trying to fit a 1x3 item: The arrows show just one of the solutions, but if you look you will find more than one. This is what I ultimately not auto-sorting but find a solution and applying it. Note that if I spend time on it I will come up with a way to solve it, but it wouldn't be the best way, it's like, holding a car wheel with your feet instead of your hands! XD Or just like trying to solve an issue that requires arrays, but you're not yet aware of their existence! So what is the right approach to this? Hope somebody helps, thanks a lot in advance :)

    Read the article

  • How to check if a variable is an integer? [closed]

    - by FyrePlanet
    I'm going through my C++ book and have currently made a working Guess The Number game. The game generates a random number based on current time, has the user input their guess, and then tells them whether it was too high, too low, or the correct number. The game functions fine if you enter a number, but returns 'Too High' if you enter something that is not a number (such as a letter or punctuation). Not only does it return 'too high', but it also continually returns it. I was wondering what I could do to check if the guess, as input by the user, is an integer and if it is not, to return 'Not a number. Guess again.' Here is the code. #include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { srand(time(0)); // seed the random number generator int theNumber = rand() % 100 + 1; // random number between 1 and 100 int tries = 0, guess; cout << "\tWelcome to Guess My Number!\n\n"; do { cout << "Enter a guess: "; cin >> guess; ++tries; if (guess > theNumber) cout << "Too high!\n\n"; if (guess < theNumber) cout << "Too low!\n\n"; } while (guess != theNumber); cout << "\nThat's it! You got it in " << tries << " guesses!\n"; cout << "\nPress Enter to exit.\n"; cin.ignore(cin.rdbuf()->in_avail() + 1); return 0; }

    Read the article

  • Sharing the effect

    - by Mohammad Ahmed
    my problem is : If I load 2 models ( the same model zombie ) and give them the same effect I got the following error : for(int i =0 ; i<2 ; i++) { dwarfModel[i].model = Content.Load<Model>("Models//dwarf//dwarfmodel"); dwarfModel[i].effect = Content.Load<Effect>("Models//dwarf//skinFX"); dwarfModel[i].setEffect(camera , game); dwarfModel[i].setModelAnimationStatus(game); dwarfModel[i].intializeChrachterController(new Vector3(0, 0, 0), 20, 10, 2000, 2000, 80, 40); space.Add(dwarfModel[i].chrachterController); dwarfModels.Add(dwarfModel); } enter code here

    Read the article

  • C++11 VS 2012 functor seems to choke when I have more than 5 parameters

    - by bobobobo
    function <void ( int a, int b, int ia, int ib, bool rev, const Vector4f& color )> benchTris = [&pts]( int a, int b, int ia, int ib, bool rev, const Vector4f& color ) { } The error is: error C2027: use of undefined type 'std::_Get_function_impl<_Tx>' with [ _Tx=void (int,int,int,int,bool,const Vector4f &) ] main.cpp(374) : see reference to class template instantiation 'std::function<_Fty>' being compiled with [ _Fty=void (int,int,int,int,bool,const Vector4f &) ] Works ok if I remove ONE parameter, for example a from the front: function <void ( int b, int ia, int ib, bool rev, const Vector4f& color )> benchTris = [&pts]( int b, int ia, int ib, bool rev, const Vector4f& color ) { // ok } Is there some parameter limit I don't know about?

    Read the article

  • User input being limited to the alphabet in python

    - by Danger Cat
    I am SUPER new to programming and have my first assignment coming up in python. I am writing a hangman type game, where users are required to guess the word inputted from the other user. I have written most of the code, but the only problem I am having is when users have to input the word, making sure it is only limited to the alphabet. The code I have so far is : word = str.lower(raw_input("Type in your secret word! Shhhh... ")) answer = True while answer == True: for i in range(len(word)): if word[i] not in ("abcdefghijklmnopqrstuvwxyz"): word = raw_input("Sorry, words only contain letters. Please enter a word ") break else: answer = False This works while I input a few tries, but eventually will either exit the loop or displays an error. Is there any easier way to use this? We've really only covered topics up to loops in class, and break and continue are also very new to me. Thank you! (Pardon if the code is sloppy, but as I said I am very new to this....)

    Read the article

  • ruby in 100 minutes good_morning method issue

    - by user2525947
    I have been doing the Ruby in 100 minutes on the JumpStart labs website, and encountered a problem during part 5. I was asked to create a good_morning method that would print out a greeting such as 'Happy Monday, it's the 130 day of 2013'. Here is my current program: class PersonalChef def good_morning today = Date.today.strftime("%A") day_of_year = Date.today.yday puts "Happy#{today}! It is the #{day_of_year} day of year." return self end def make_toast(color) puts " Making your toast #{color}!" return self end def make_milkshake(flavor) puts " Making a #{flavor} milkshake!" return self end def make_eggs(quantity) puts " Making you #{quantity} eggs!" return self end end when I try to run the program load on irb( 'personal_chef.rb', frank = PersonalChef.new, frank.make_milkshake('chocolate'), etc, everything works fine until I try to type frank.good_morning into irb, which gives the following error message: NameError: uninitialized constant PersonalChef :: Date from personal_chef.rb:5: in good_morning from (irb):3 from /bin/irb:12:in '' Any help or information to help me solve this issue would be greatly appreciated. Thanks for your time!

    Read the article

  • populate uipicker view with results from core data DB using an NSArray

    - by Chris
    I am trying to populate a UIPickerView with the results of a NSFetchRequest. The results of the NSFetchRequest are then stored in an NSArray. I am using Core Data to interact with the SQLite DB. I have a simple class file that contains a UIPickerView that is associated with a storyboard scene in my project. The header file for the class looks like the following, ViewControllerUsers.h #import <UIKit/UIKit.h> #import "AppDelegate.h" @interface ViewControllerUsers : UIViewController <NSFetchedResultsControllerDelegate, UIPickerViewDelegate, UIPickerViewDataSource> { NSArray *dictionaries; } @property (nonatomic, strong) NSFetchedResultsController *fetchedResultsController; // Core Data @property (strong, nonatomic) NSManagedObjectContext *managedObjectContext; @property (nonatomic, strong) NSArray *users; @property (strong, nonatomic) IBOutlet UIPickerView *uiPickerViewUsers; @property (weak, nonatomic) IBOutlet UIBarButtonItem *btnDone; @property (weak, nonatomic) IBOutlet UIButton *btnChangePin; // added for testing purposes @property (nonatomic, strong) NSArray *usernames; - (IBAction)dismissScene:(id)sender; - (IBAction)changePin:(id)sender; @end The implementation file looks like the following, ViewControllerUsers.m #import "ViewControllerUsers.h" @interface ViewControllerUsers () @end @implementation ViewControllerUsers // Core Data @synthesize managedObjectContext = _managedObjectContext; @synthesize uiPickerViewUsers = _uiPickerViewUsers; @synthesize usernames = _usernames; - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. // Core Data if (_managedObjectContext == nil) { _managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; NSLog(@"After _managedObjectContext: %@", _managedObjectContext); } NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Account"]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Account" inManagedObjectContext:_managedObjectContext]; request.resultType = NSDictionaryResultType; request.propertiesToFetch = [NSArray arrayWithObject:[[entity propertiesByName] objectForKey:@"username"]]; request.returnsDistinctResults = YES; _usernames = [_managedObjectContext executeFetchRequest:request error:nil]; NSLog (@"names: %@",_usernames); } -(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView { //One column return 1; } -(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component { //set number of rows return _usernames.count; } -(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { //set item per row return [_usernames objectAtIndex:row]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (void)viewDidUnload { [self setBtnDone:nil]; [self setUiPickerViewUsers:nil]; [self setBtnChangePin:nil]; [super viewDidUnload]; } - (IBAction)dismissScene:(id)sender { [self dismissModalViewControllerAnimated:YES]; } - (IBAction)changePin:(id)sender { } @end The current code is causing the app to crash, but the NSLog is show the results of the NSFetchRequest in the NSArray. I currently think that I am not formatting the results of the NSFetchRequest in the NSArray properly if I had to take a guess. The crash log looks like the following, 2013-06-26 16:49:24.219 KegCop[41233:c07] names: ( { username = blah; }, { username = chris; }, { username = root; } ) 2013-06-26 16:49:24.223 KegCop[41233:c07] -[NSKnownKeysDictionary1 isEqualToString:]: unrecognized selector sent to instance 0xe54d9a0 2013-06-26 16:49:24.223 KegCop[41233:c07] Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSKnownKeysDictionary1 isEqualToString:]: unrecognized selector sent to instance 0xe54d9a0' First throw call stack:

    Read the article

  • How to check for palindrome using Python logic

    - by DrOnline
    My background is only a 6 month college class in basic C/C++, and I'm trying to convert to Python. I may be talking nonsense, but it seems to me C, at least at my level, is very for-loop intensive. I solve most problems with these loops. And it seems to me the biggest mistake people do when going from C to Python is trying to implement C logic using Python, which makes things run slowly, and it's just not making the most of the language. I see on this website: http://hyperpolyglot.org/scripting (serach for "c-style for", that Python doesn't have C-style for loops. Might be outdated, but I interpret it to mean Python has its own methods for this. I've tried looking around, I can't find much up to date (Python 3) advice for this. How can I solve a palindrome challenge in Python, without using the for loop? I've done this in C in class, but I want to do it in Python, on a personal basis. The problem is from the Euler Project, great site btw. def isPalindrome(n): lst = [int(n) for n in str(n)] l=len(lst) if l==0 || l==1: return True elif len(lst)%2==0: for k in range (l) ##### else: while (k<=((l-1)/2)): if (list[]): ##### for i in range (999, 100, -1): for j in range (999,100, -1): if isPalindrome(i*j): print(i*j) break I'm missing a lot of code here. The five hashes are just reminders for myself. Concrete questions: 1) In C, I would make a for loop comparing index 0 to index max, and then index 0+1 with max-1, until something something. How to best do this in Python? 2) My for loop (in in range (999, 100, -1), is this a bad way to do it in Python? 3) Does anybody have any good advice, or good websites or resources for people in my position? I'm not a programmer, I don't aspire to be one, I just want to learn enough so that when I write my bachelor's degree thesis (electrical engineering), I don't have to simultaneously LEARN an applicable programming language while trying to obtain good results in the project. "How to go from basic C to great application of Python", that sort of thing. 4) Any specific bits of code to make a great solution to this problem would also be appreciated, I need to learn good algorithms.. I am envisioning 3 situations. If the value is zero or single digit, if it is of odd length, and if it is of even length. I was planning to write for loops... PS: The problem is: Find the highest value product of two 3 digit integers that is also a palindrome.

    Read the article

  • Compare two times without regard to Date associated - Ruby

    - by H55nick
    I am trying to find the difference in time (without days/years/months) of two different days. Example: #ruby >1.9 time1 = Time.now - 1.day time2 = Time.now #code to make changes #test: time1 == time2 # TRUE My solution: time1 = time1.strftime("%h:%m").to_time time2 = time2.strftime("%h:%m").to_time #test time1 == time2 #True #passes I was wondering if there was a better way of doing this? Maybe we could keep the Date the same as time1/time2?

    Read the article

  • Throwing exceptions as well as catching exceptions?

    - by Eric S
    I was wondering how Java takes the following scenario public static void main(String[] args) throws IndexOutOfBoundsException, CoordinateException, MissionException, SQLException, ParserConfigurationException { try { doSomething(); } catch (Exception e) { e.printStackTrace(); } } In the above code, I am declaring the main function to throw many different exceptions, but inside the function, I am catching the generic Exception. I am wondering how java takes this internally? I.e., say doSomething() throws an IndexOutOfBounds exception, will the e.printStackTrace() get called in the last catch (Exception e) {...} block? I know if an exception not declared in the throws area of the function gets thrown, the try/catch will handle it, but what about exceptions mentioned in the declaration?

    Read the article

  • How to put a background image on GridBagLayout

    - by Loligans
    I am trying to work with layout managers for the first time, and they are just kicking me in the teeth. I am trying to make a background image and then put buttons on top, using GridBagLayout, if there is a a better layoutmanager please do tell. As for trying to learn how to use layout managers, its very difficult and any learning references would also be much appreciated. This is what it looks like currently, I can get the frame to show the full image, but when i use gridlayout manager, it does that public void addComponentsToPane(Container pane){ BackgroundImage image = new BackgroundImage(); JButton button1, button2, button3, button4, button5; pane.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); if(shouldFill){ c.fill = GridBagConstraints.NONE; } button1 = new JButton("Button 1"); if (shouldWeightX) { c.weightx = 0.5; } c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 1; c.gridy = 0; button1.setOpaque(false); pane.add(button1, c); button2 = new JButton("Button 2"); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 0.5; c.gridx = 0; c.gridy = 0; button2.setOpaque(false); pane.add(button2, c); button3 = new JButton("Button 3"); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 0.5; c.gridx = 2; c.gridy = 0; button3.setOpaque(false); pane.add(button3, c); button4 = new JButton("Long-Named Button 4"); c.fill = GridBagConstraints.HORIZONTAL; c.ipady = 40; //make this component tall c.weightx = 0.0; c.gridwidth = 3; c.gridx = 0; c.gridy = 1; pane.add(button4, c); button5 = new JButton("button 1"); c.fill = GridBagConstraints.HORIZONTAL; c.ipady = 0; //reset to default c.weighty = 1.0; //request any extra vertical space c.anchor = GridBagConstraints.PAGE_END; //bottom of space c.insets = new Insets(10,0,0,0); //top padding c.gridx = 1; //aligned with button 2 c.gridwidth = 2; //2 columns wide c.gridy = 2; //third row pane.add(button5, c); c.ipadx = 800; c.ipady = 400; pane.add(image, c); } This is what i'm trying to make it look like

    Read the article

  • Ruby on Rails: create records for multiple models with one form and one submit

    - by notblakeshelton
    I have a 3 models: quote, customer, and item. Each quote has one customer and one item. I would like to create a new quote, a new customer, and a new item in their respective tables when I press the submit button. I have looked at other questions and railscasts and either they don't work for my situation or I don't know how to implement them. I also want my index page to be the page where I can create everything. quote.rb class Quote < ActiveRecord::Base attr_accessible :quote_number has_one :customer has_one :item end customer.rb class Customer < ActiveRecord::Base #unsure of what to put here #a customer can have multiple quotes, so would i use: has_many :quotes #<----? end item.rb class Item < ActiveRecord::Base #also unsure about this #each item can also be in multiple quotes quotes_controller.rb class QuotesController < ApplicationController def index @quote = Quote.new @customer = Customer.new @item = item.new end def create @quote = Quote.new(params[:quote]) @quote.save @customer = Customer.new(params[:customer]) @customer.save @item = Item.new(params[:item]) @item.save end end items_controller.rb class ItemsController < ApplicationController def index end def new @item = Item.new end def create @item = Item.new(params[:item]) @item.save end end customers_controller.rb class CustomersController < ApplicationController def index end def new @customer = Customer.new end def create @customer = Customer.new(params[:customer]) @customer.save end end quotes/index.html.erb <%= form_for @quote do |f| %> <%= f.fields_for @customer do |builder| %> <%= label_tag :firstname %> <%= builder.text_field :firstname %> <%= label_tag :lastname %> <%= builder.text_field :lastname %> <% end %> <%= f.fields_for @item do |builder| %> <%= label_tag :name %> <%= builder.text_field :name %> <%= label_tag :description %> <%= builder.text_field :description %> <% end %> <%= label_tag :quote_number %> <%= f.text_field :quote_number %> <%= f.submit %> <% end %> When I try submitting that I get an error: Can't mass-assign protected attributes: item, customer So to try and fix it I updated the attr_accessible in quote.rb to include :item, :customer but then I get this error: Item(#) expected, got ActiveSupport::HashWithIndifferentAccess(#) Any help would be greatly appreciated.

    Read the article

  • codeigniter not being able to get the full param from url?

    - by bnelsonjax
    Im having a weird issue that i cant seem to fix. It's dealing with viewing a company and adding a location to that company. when viewing a company, my url would look like this: domain.com/company/view/415 So clearly 415 is the ID of company, the company shows up correctly on my company view page. Now comes the weird part. when clicking on an "Add Location" link, which would take me to : domain.com/location/add/415 so once again this should be saying Location / Add / 415 (company ID 415) on this page, if i do it will echo 4 (instead of 415...the company id) if the company id is 754, the php echo $data['id'] would echo 7 (instead of 754). So its stripping the last 2 numbers off the Company ID. Here is my controller: public function add($id) { if (isset($_POST["add"])) { $this->Equipment_model->add($id); redirect('company/view/'.$id); } $data['locations'] = $this->Equipment_model->get_locations($id); $data['data'] = $id; $this->load->view('templates/header'); $this->load->view('equipment/add', $data); $this->load->view('templates/footer'); } here is my .htaccess RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-l RewriteCond $1 !^(index\.php|css|font|img|js|themes) RewriteRule ^(.*)$ index.php/$1 [QSA,L] Because my php/codeigniter experience is limited, maybe my terminology is off, so i created a video and uploaded it to twitch, here is the link if you wanna see what im talking about: http://www.twitch.tv/bnelsonjax/b/420079504 if anyone could help i'd be so grateful, I've been stuck on this for about a week. UPDATE ok now we are getting somehwere, when i change controller to: public function add($id) { if (isset($_POST["add"])) { $this->Equipment_model->add($id); redirect('company/view/'.$id); } $data['locations'] = $this->Equipment_model->get_locations($id); $data['data'] = $id; $data['cid'] = $id; $this->load->view('templates/header'); $this->load->view('equipment/add', $data); $this->load->view('templates/footer'); $this->output->enable_profiler(TRUE); } if i add the following to the view page: <?php echo $data['id']; ?> it echos: 7 this one: <?php echo $cid; ?> it echos 766 (CORRECT ONE) this one: <?php echo $data['cid']; ?> it echos 7 my question then is why if the controller show: $data['data'] = $id; $data['cid'] = $id; does only the one thats $data['cid'] echo correctly?

    Read the article

  • Using Gradle with an existing Android project

    - by Tom Reznik
    I have an existing Android project with the following structure: - ProjectName -- AndroidManifest.xml -- local.properties -- project.properties -- assets -- libs (containing all jars) -- modules (containing all library projects my project depends on) -- res -- src ---- com/namespace/projectname (all my classes including main activity are here) I haven't been using any specific build system to build my project other than the one provided by default with the Android Studio IDE (though the project was originally created with IntelliJ CE. I would like to use Gradle with the android plugin and do some work on my build process. I have tried several configurations in order to achieve this and have failed to complete a successful build every time. What's the recommended approach in this scenario? should I change my project structure? or is it possible to configure gradle using the existing structure? Any help would be greatly appreciated. Thanks!

    Read the article

  • checkbox like radiobutton wpf c#

    - by rockenpeace
    i have investigated this problem but this is solved in design view and code-behind. but my problem is little difference: i try to do this as only code-behind because my checkboxes are dynamically created according to database data.In other words, number of my checkboxes is not stable. i want to check only one checkbox in group of checkboxes. when i clicked one checkbox,i want that ischecked property of other checkboxes become false.this is same property in radiobuttons. i take my checkboxes from a stackpanel in xaml side: <StackPanel Margin="4" Orientation="Vertical" Grid.Row="1" Grid.Column="1" Name="companiesContainer"> </StackPanel> my xaml.cs: using (var c = new RSPDbContext()) { var q = (from v in c.Companies select v).ToList(); foreach (var na in q) { CheckBox ch = new CheckBox(); ch.Content = na.Name; ch.Tag = na; companiesContainer.Children.Add(ch); } } foreach (object i in companiesContainer.Children) { CheckBox chk = (CheckBox)i; chk.SetBinding(ToggleButton.IsCheckedProperty, "DataItem.IsChecked"); } how can i provide this property in checkboxes in xaml.cs ? thanks in advance..

    Read the article

  • My webpage ignores changes in CSS file

    - by Pavel
    No matter what I change in my .css file, the page remains the same - what's more, neither changing the link tag so that it points to another .css file nor deleting it completely makes no difference. Other changes in html code are applied. The sourcecode of the webpage shows everything as it should be. This behavior started when I redirected the link tag from previous file to the one I use now (plus there have been some changes in the tag while this problem occured, to test the behavior of my webpage); changes in neither file affect the page. For the first time when this happened, this was caused by copies of head tag in included chunks of code (for header, left menu etc. - their head part overrode the head part of the main page) and the problem was solved by removing these redundant heads from these files. But it happened again when I changed the link tag for the next time. I couldn't find any head parts in my included files, but the problem lasts (only solution I can see now is to delete the included files and copy the code directly to the file, but this would mean lots of redundant code). How can I solve this problem, so that my page response to changes in .css files without increasing redundancy? How to ensure that I can change the link to .css file just on one place with no such problems? Do I have to unload the CSS file somehow? I saw this problem both in Firefox and in Chrome. I use PSPad to write the code, just in case it would play role. EDIT: I have cleared browser cache now, and I changed the link to .css files from one to another before, but nothing helped. Now I accept the best answer saying the problem is in caching and I start a related question to find out how to solve the caching issue. If the other question's answers would say that in this case I can be sure that problem isn't in caching (very unlikely, but fail of ordinary methods of caching-problems-solving is unlikely too), I'd update this question and start searching for other possible problems, but now the message seems to be clear: when webpage ignores changes in .css files, caching is to blame.

    Read the article

< Previous Page | 9 10 11 12 13 14 15 16 17 18 19  | Next Page >