Daily Archives

Articles indexed Sunday November 25 2012

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

  • RAM caching causes severe performance drops

    - by B T
    I have read plenty of threads on memory caching and the standard response of "large cache is good, it shouldn't effect performance", "the kernel knows best". I have recently upgraded from 12.04 to 12.10 and changed from VirtualBox to VMware Workstation and the performance differences are severe (I suspect it is because of the latter). When I am running my virtual machine the system load monitor graph shows less than 50% memory usage generally. System load indicator is showing me that the rest of my RAM is used in the cache all the time. Plain and simple this is the comparison: BEFORE Cache was very sparingly used, pretty much none of my memory usage was the cache Swappiness was 0 (caused my memory to be used first, then swap only if needed) Performance was quite good and logical RAM was used fully first, caching was minimal. I could run enough software to utilize my full 4GB of RAM without any performance degradation whatsoever Swap space was then used as needed which was obviously slower (I am on a HDD) but was still usable when the current program was loaded into memory AFTER Cache is used to fill the full 4GB as soon as my virtual machine is run Swappiness is 0 (same behaviour as before but cache uses full memory straight away) Performance is terrible and unusable while running Ubuntu software Basic things like changing windows takes 2 minutes + Changing screens happens frame by frame over sometimes up to 5 minutes Cannot run an IDE and VM like I could with ease before So basically, any suggestions on how to take my performance back to how it was before while keeping my current setup? My suspicion is VMWare is the problem, but how do I see what is tied to the use of the cache? Surely there is a way to control this behaviour in software as polished as VMware? Thanks EDIT: Could also be important to note that the behaviour differs depending on whether VMware is open or closed. If VMware is open, then the ram will lock at like 50% and 50% cache and go into the complete lock up mentioned above. Contrastingly, if VMware is closed (after being open), then the RAM will continue to rise as it needs / cache will stay as the complete remaining memory and there is no noticeable performance degradation.

    Read the article

  • Nautilus tags/labels/marks/columns for folders/files

    - by madox2
    Is there any way how to mark folders or files with tags(or labels, new columns or whatever) in Nautilus? It would be nice to sort marked folders or files through this tags. Especially my first idea was to mark folders in my Movie directory with tags seen, not seen, must see, and so on. Then I realized it would be useful in any other workspaces with any custom tags... Is there any nautilus extension for this? Or any other file manager which can do this? It might look like this:

    Read the article

  • How to make Logitech Anywhere MX work in Ubuntu 12.X?

    - by alfC
    I have a Logitech Anywhere MX mouse (wireless), when I connect it to the computer it doesn't work. The mouse works in other computers with Windows and with Fedora 17, but it doesn't work in two different computers with Ubuntu 12.04 and 12.10. Moreover these same computers work with another Microsoft wireless mouse. So I think the combination of Logitech MX and Ubuntu doesn't play well. The dmesg log entry looks like this: [ 578.845838] usb 3-2: Product: USB Receiver [ 578.845841] usb 3-2: Manufacturer: Logitech [ 578.851625] logitech-djreceiver 0003:046D:C52B.0009: hiddev0,hidraw0: USB HID v1.11 Device [Logitech USB Receiver] on usb-0000:00:14.0-2/input2 [ 578.851899] logitech-djreceiver 0003:046D:C52B.0009: logi_dj_probe:logi_dj_recv_query_paired_devices error:-32 [ 578.854518] logitech-djreceiver: probe of 0003:046D:C52B.0009 failed with error -32 Instead of the expected (taken from Fedora): [154344.634520] usb 2-1.2: Manufacturer: Logitech [154344.647935] logitech-djreceiver 0003:046D:C52B.000D: hiddev0,hidraw0: USB HID v1.11 Device [Logitech USB Receiver] on usb-0000:00:1d.0-1.2/input2 [154344.653788] input: Logitech Unifying Device. Wireless PID:1017 as /devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2/2-1.2:1.2/0003:046D:C52B.000D/input/input21 [154344.654192] logitech-djdevice 0003:046D:C52B.000E: input,hidraw1: USB HID v1.11 Mouse [Logitech Unifying Device. Wireless PID:1017] on usb-0000:00:1d.0-1.2:1

    Read the article

  • How to install custom c library?

    - by arijit
    I just wanted to add a c library to Ubuntu which was created by Harvard University for cs50 course. They provided instructions for how to install the library which is listed below. Debian, Ubuntu First become root, as with: sudo su - Then install the CS50 Library as follows: apt-get install gcc wget http://mirror.cs50.net/library/c/cs50-library-c-3.1.zip unzip cs50-library-c-3.1.zip rm -f cs50-library-c-3.1.zip cd cs50-library-c-3.1 gcc -c -ggdb -std=c99 cs50.c -o cs50.o ar rcs libcs50.a cs50.o chmod 0644 cs50.h libcs50.a mkdir -p /usr/local/include chmod 0755 /usr/local/include mv -f cs50.h /usr/local/include mkdir -p /usr/local/lib chmod 0755 /usr/local/lib mv -f libcs50.a /usr/local/lib cd .. rm -rf cs50-library-c-3.1 I did exactly as directed. But the compiler reported “Undefined reference to a function”--the function was Get String. So, I searched for a solution and found one. It said to use the -l switch. Now when I compile I use something like: gcc –o hello.c hello –lcs50 (I don’t remember the exact command.) However, I cannot use the make command, which is easier to use. I understand that there is some problem with linking the library. What is a good solution to this problem?

    Read the article

  • Customer Reviews on Company Listings [closed]

    - by GSTAR
    I'm not sure if this is the right place but I am after some general advice on a feature I am looking to implement on my website. The website I have is a Wedding Directory. Here, companies can advertise in the form of a directory listing. This listing contains the company details - such as what they do and how you can contact them. There are three packages available - Basic package is free and Silver and Gold packages are charged for. Now in order to further enhance the directory, I want to enable customer reviews for each listing. This is basically whereby customers who have used a particular company's service can write a review (and rate out of 5) of their experience. The dilemma I face is that if customers are to be paying for their listings then surely they will expect to not have content on their listing that would tarnish their reputation (i.e. negative reviews). But at the same time I want to be impartial and help my site visitors to make informed choices on which companies to book when arranging their weddings. Of course I will exercise my ability to remove offensive or fake reviews but I do not want to be removing reviews just to satisfy my clients. Suppose a client pays me a premium fee to have their listing on my front page and at the top of the listings. Now suppose that client gets lost of negative reviews - the fact that they have increased visibility means that they will also get increased bad publicity. This in turn means they won't renew their package and will most likely request the listing to be taken down. So, how can I get the right balance here and keep everyone happy?

    Read the article

  • OpenGl / C++ and some strange light problem on half board

    - by mlodziaszka
    I have some problem with lights in my opengl "game". I have board with is square (-50,50), (50, 50), (50, -50), (-50,-50) x and z since y doesn't matter at all. I tried to make something like flashlight its moving and rotating with camera (me), but when i try to rotate more then 90 degree to left or right it just give diffrend light: http://imageshack.us/photo/my-images/688/lightij.jpg/ (left is spotlight, right point light) There is also a point light in the middle, but its working strange(not like a pointlight) it shines only on half of the board from (-50,50), (50, 50), (50, 0), (-50,-0) x and y: Link to my repo where u can find game exe in download and full code in source: https://bitbucket.org/mlodziaszka/my_game All more fragments of light: float gl_amb[] = { 0.2f, 0.2f, 0.2f, 1.0f }; glLightModelfv(GL_LIGHT_MODEL_AMBIENT, gl_amb); glEnable(GL_LIGHTING); // Wlaczenie oswietlenia glShadeModel(GL_SMOOTH); // Wybor techniki cieniowania glEnable(GL_LIGHT0); // Wlaczenie 0-go zrodla swiatla glEnable(GL_LIGHT1); Cubes parametri: float m1_amb[] = { 1.0f, 0.0f, 0.0f, 1.0f }; float m1_dif[] = { 1.0f, 0.0f, 0.0f, 1.0f }; float m1_spe[] = { 1.0f, 0.0f, 0.0f, 1.0f }; glMaterialfv(GL_FRONT, GL_AMBIENT, m1_amb); glMaterialfv(GL_FRONT, GL_DIFFUSE, m1_dif); glMaterialfv(GL_FRONT, GL_SPECULAR, m1_spe); glMaterialf(GL_FRONT, GL_SHININESS, 50.0f); Texture parametri: float m1_amb[] = { 1.0f, 1.0f, 1.0f, 1.0f }; float m1_dif[] = { 1.0f, 1.0f, 1.0f, 1.0f }; float m1_spe[] = { 1.0f, 1.0f, 1.0f, 1.0f }; glMaterialfv(GL_FRONT, GL_AMBIENT, m1_amb); glMaterialfv(GL_FRONT, GL_DIFFUSE, m1_dif); glMaterialfv(GL_FRONT, GL_SPECULAR, m1_spe); glMaterialf(GL_FRONT, GL_SHININESS, 0.0f); glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ); Light0: //with some magic sn't working anyway float l0_amb[] = { 0.2f, 0.2f, 0.2f, 1.0f }; float l0_dif[] = { 1.0f, 1.0f, 1.0f, 1.0f }; float l0_spe[] = { 1.0f, 1.0f, 1.0f, 1.0f }; float l0_pos[] = { g_Camera.m_vPosition.x, g_Camera.m_vPosition.y, g_Camera.m_vPosition.z, 1.0f }; float temp = 0.0f, temp2 = 0.0f, temp3 = 0.0f; if(g_Camera.m_vView.z < g_Camera.m_vPosition.z) { temp = g_Camera.m_vView.x - g_Camera.m_vPosition.x; temp2 = g_Camera.m_vView.z - g_Camera.m_vPosition.z; } else { temp = g_Camera.m_vView.x - g_Camera.m_vPosition.x; temp2 = g_Camera.m_vView.z - g_Camera.m_vPosition.z; } float l0_pos1[] = {temp, 0.0f, temp2}; //float l0_pos1[] = {-1.0f, 0.0f, -1.0f}; glLightfv(GL_LIGHT0, GL_AMBIENT, l0_amb); glLightfv(GL_LIGHT0, GL_DIFFUSE, l0_dif); glLightfv(GL_LIGHT0, GL_SPECULAR, l0_spe); glLightfv(GL_LIGHT0, GL_POSITION, l0_pos); glLightf (GL_LIGHT0, GL_SPOT_CUTOFF, 15.0f); glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, l0_pos1); Light1: float l1_amb[] = { 0.2f, 0.2f, 0.2f, 1.0f }; float l1_dif[] = { 1.0f, 1.0f, 1.0f, 1.0f }; float l1_spe[] = { 1.0f, 1.0f, 1.0f, 1.0f }; float l1_pos[] = { 0.0f, 0.0f, 0.0f, 1.0f }; glLightfv(GL_LIGHT1, GL_AMBIENT, l1_amb); glLightfv(GL_LIGHT1, GL_DIFFUSE, l1_dif); glLightfv(GL_LIGHT1, GL_SPECULAR, l1_spe); glLightfv(GL_LIGHT1, GL_POSITION, l1_pos); I know that way I made this very old, but for now i want to keep this like that. I wouldbe realy gratefull if someone can tell me what is wrong with my lights xD full code: link up ^^

    Read the article

  • Why is Spritebatch drawing my Textures out of order?

    - by Andrew
    I just started working with XNA Studio after programming 2D games in java. Because of this, I have absolutely no experience with Spritebatch and sprite sorting. In java, I could just layer the images by calling the draw methods in order. For a while, my Spritebatch was working fine in deferred sorting mode, but when I made a change to one of my textures, it suddenly started drawing them out of order. I have searched for a solution to this problem, but nothing seems to work. I have tried adding layer depths to the sprites and changing the sort mode to BackToFront or FrontToBack or even immediate, but nothing seems to work. Here is my drawing code: protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Gray); Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); for (int x = 0; x < 5; x++) { for (int y = 0; y < 5; y++) { region[x, y].draw(((float)w / aw)); // Draws the Tile-Based background } } player.draw(spriteBatch, ((float)w / aw));//draws the character (This method is where the problem occurs) enemy.draw(spriteBatch, (float)w/aw); // draws a basic enemy Game1.spriteBatch.End(); base.Draw(gameTime); } player.draw method: public void draw(SpriteBatch sb, float ratio){ //draws the player base (The character without hair or equipment) sb.Draw(playerbase[0], new Rectangle((int)(pos.X - (24 * ratio)), (int)(pos.Y - (48 * ratio)), (int)(48 * ratio), (int)(48 * ratio)), new Rectangle(orientation * 48, animFrame * 48, 48, 48), Color.White,0,Vector2.Zero,SpriteEffects.None,0); //draws the player's hair sb.Draw(playerbase[3], new Rectangle((int)(pos.X - (24 * ratio)), (int)(pos.Y - (48 * ratio)), (int)(48 * ratio), (int)(48 * ratio)), new Rectangle(orientation * 48, animFrame * 48, 48, 48), Color.White, 0, Vector2.Zero, SpriteEffects.None, 0); //draws the player's shirt sb.Draw(equipment[0], new Rectangle((int)(pos.X - (24 * ratio)), (int)(pos.Y - (48 * ratio)), (int)(48 * ratio), (int)(48 * ratio)), new Rectangle(orientation * 48, animFrame * 48, 48, 48), Color.White, 0, Vector2.Zero, SpriteEffects.None, 0); //draws the player's pants sb.Draw(equipment[1], new Rectangle((int)(pos.X - (24 * ratio)), (int)(pos.Y - (48 * ratio)), (int)(48 * ratio), (int)(48 * ratio)), new Rectangle(orientation * 48, animFrame * 48, 48, 48), Color.White, 0, Vector2.Zero, SpriteEffects.None, 0); //draws the player's shoes sb.Draw(equipment[2], new Rectangle((int)(pos.X - (24 * ratio)), (int)(pos.Y - (48 * ratio)), (int)(48 * ratio), (int)(48 * ratio)), new Rectangle(orientation * 48, animFrame * 48, 48, 48), Color.White, 0, Vector2.Zero, SpriteEffects.None, 0); } the game has a top-down perspective much like the early legend of zelda games. It draws sections of the texture depending on which direction the character is facing and the animation frame. However, instead of drawing the character in the order the draw methods are called, it ends up drawing the character out of order. Please help me with this problem.

    Read the article

  • Gigantic 2d maps?

    - by Jesper Hallenberg
    I've been thinking about a game idea for a week or two and the last few hours I was thinking of some technical stuff and came up with that the map would need to be 360,000x360,000 pixels in size. To me it sounds insane, but I've never done much in depth game development so I'm not sure if its reasonable or not to have a map that large. Basicly my question is, would it work to have a map that large in a 2D game?

    Read the article

  • How to achieve selection of a tile from a tile sheet based on an ID?

    - by Bugster
    Let's say I have a tile sheet that contains 8 sprites per sheet. Each sprite is a tile of 30x30. I wrote my own custom map parser/map loader however I'm having trouble extracting a certain tile sprite from the file. I'll describe my problem better in order for everyone to understand. I wrote an enum of materials, each material has a value according to it's location relative to the tile sheet. For example void is 1, grass is 2, rock is 3, etc. So in my tile sheet they are represented as such: +---+---+---+---+---+ | 1 | 2 | 3 | 4 | 5 | +---+---+---+---+---+ Which is equivalent to: +------+-------+-------+ | void | grass | stone | +------+-------+-------+ Basically when rendering, I created a tile class, each tile has 2 coordinates: X and Y (They are calculated automatically) and a material which can be represented either as a number, either as a value (ID). When rendering, I have a vector of sprites which are all taken from 1 file called tilesheet.png, however each of them must only draw a certain portion of the tile sheet, for example say I have something like this: tile coordinateBounds(topLeftX, topLeftY, tileWidth, tileHeight); During the initialization of the map I calculate an array of tiles, and I give each of them their position, their materials based on the values in a map file and a few other variables such as collision. I need to apply the coordinateBounds to each of them according to their material value. For example if the material is grass it should only take the grass sprite from the tilesheet. I must also mention I'm using SFML, and there are no borders or spacing between the tiles.

    Read the article

  • Live asynchronous time feed for websites

    - by Maven
    I want to show up the time over my website based over the location of the user, let’s say if user one browsing the website is from USA than the time should be what is in USA currently and same for China etc. and all. I was wondering if there exists a JavaScript plugin for it but I didn’t find any as dynamic as I want, my requirements include: Something that can be fully stylized according to website theme (no iframes) The pattern I want is to be in (HH:MM:SS) It should be asynchronous like the second [SS] keep ticking and the time keep updating Is this possible, a way around to achieve it?

    Read the article

  • Ruby does 'elseif' still exist

    - by catchmikey
    I'm just learning ROR and I came across the if / else statements. I also came across 'elseif' but my text editor (textmate) doesn't pick it up as a keyword, not does the program run properly. if name == 'Chris' puts 'What a lovely name.' elseif name == 'Katy' puts 'What a lovely name!' end I'm using the book, Learn to Program, which was written several years ago. I was wondering if the 'elseif' was changed because when I simply use 'else' it seems to function properly

    Read the article

  • Which part of this simple script is breaking internet explorer?

    - by user961627
    I'm writing a simple virtual keyboard for Arabic (indic) digits. Just links that, when clicked, produce the corresponding Unicode Indic character. The following is my HTML, in the body tag: <a href="#" id='start'>Start</a> <div id='vkb' style='padding:20px;font-size:16pt; border:2px solid #eee; width:250px' dir='ltr'> <a class='key' href='#' id='0'>&#1632;</a> <a class='key' href='#' id='1'>&#1633;</a> <a class='key' href='#' id='2'>&#1634;</a> <a class='key' href='#' id='3'>&#1635;</a> <a class='key' href='#' id='4'>&#1636;</a><br /> <a class='key' href='#' id='5'>&#1637;</a> <a class='key' href='#' id='6'>&#1638;</a> <a class='key' href='#' id='7'>&#1639;</a> <a class='key' href='#' id='8'>&#1640;</a> <a class='key' href='#' id='9'>&#1641;</a> <br /> <a href="#" id='stop'>Stop</a> </div> <div id='output' /></div> This is my CSS: a { text-decoration:none; } .key { padding:7px; background-color:#fff; margin:5px; border:2px solid #eee; display:inline-block; } .key:hover { background-color:#eee; } And this is my javascript: <script type="text/javascript" src="js/jquery.js"></script> <script> $(document).ready(function(){ var toprint = ""; $('#vkb').hide(); $('#start').click(function(e){ toprint = ""; $('#vkb').show(); }); $('#stop').click(function(e){ $('#vkb').hide(); ret = ar2ind(toprint); $('#output').text(ret); toprint = ""; }); $('#vkb').click(function(e){ var $key = $(e.target).closest('.key'); var pressed = $key.attr('id'); if(pressed === undefined){ pressed = ""; } toprint = toprint + pressed; }); }); function ar2ind(str) { str = str.replace(/0/g, "?"); str = str.replace(/1/g, "?"); str = str.replace(/2/g, "?"); str = str.replace(/3/g, "?"); str = str.replace(/4/g, "?"); str = str.replace(/5/g, "?"); str = str.replace(/6/g, "?"); str = str.replace(/7/g, "?"); str = str.replace(/8/g, "?"); str = str.replace(/9/g, "?"); return str; } </script> It seems simple enough but it's crashing in IE9. (Might be crashing in earlier versions too but haven't been able to check.)

    Read the article

  • Simple Java math operations

    - by user1730056
    I'm making a BMI calculator that doesn't seem to be working. The math operations work if i just do something like w/h, but once i had the brackets, it returns an error. If i change the variables w and h and use a constant number, the operation works. Another problem is that although i'm making result a double, it seems to be rounding to the nearest int. Could someone tell me what I'm doing wrong here? public class ass10 { public static void main(String[] args) { bmi(223,100); } public static bmi(int w, int h){ double result; result = (w/(h*h))*703 System.out.println(result) } }

    Read the article

  • Photo inside the image view should not go cross on dragging

    - by TGMCians
    I want photo inside the imageview should not go outside on dragging. In my code when i start to drag bitmap inside the imageview its goes out from imageview but i want when it cross the imageview its should come at starting point of imageview. How to achieve this. please help me for this. @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.save(); scaleCount=scaleCount+scale; angleCount = addAngle(angleCount, Math.toDegrees(angle)); Log.v("Positions", "X: "+x+" " + "Y: "+y); Log.d("ScaleCount", String.valueOf(scaleCount)); Log.d("Angle", String.valueOf(angleCount)); if (!isInitialized) { int w = getWidth(); int h = getHeight(); position.set(w / 2, h / 2); isInitialized = true; } Paint paint = new Paint(); Log.v("Height and Width", "Height: "+ getHeight() + "Width: "+ getWidth()); transform.reset(); transform.postTranslate(-width / 2.0f, -height / 2.0f); transform.postRotate((float) Math.toDegrees(angle)); transform.postScale(scale, scale); transform.postTranslate(position.getX(), position.getY()); canvas.drawBitmap(bitmap, transform, paint); canvas.restore(); BitmapWidth=BitmapWidth+bitmap.getScaledWidth(canvas); BitmapHeight=BitmapHeight+bitmap.getScaledHeight(canvas); try { /*paint.setColor(0xFF007F00); canvas.drawCircle(vca.getX(), vca.getY(), 30, paint); paint.setColor(0xFF7F0000); canvas.drawCircle(vcb.getX(), vcb.getY(), 30, paint);*/ /*paint.setColor(0xFFFF0000); canvas.drawLine(vpa.getX(), vpa.getY(), vpb.getX(), vpb.getY(), paint); paint.setColor(0xFF00FF00); canvas.drawLine(vca.getX(), vca.getY(), vcb.getX(), vcb.getY(), paint);*/ } catch(NullPointerException e) { // Just being lazy here... } } @Override public boolean onTouch(View v, MotionEvent event) { vca = null; vcb = null; vpa = null; vpb = null; x=event.getX(); y=event.getY(); try { touchManager.update(event); if (touchManager.getPressCount() == 1) { vca = touchManager.getPoint(0); vpa = touchManager.getPreviousPoint(0); position.add(touchManager.moveDelta(0)); } else { if (touchManager.getPressCount() == 2) { vca = touchManager.getPoint(0); vpa = touchManager.getPreviousPoint(0); vcb = touchManager.getPoint(1); vpb = touchManager.getPreviousPoint(1); VMVector2D current = touchManager.getVector(0, 1); VMVector2D previous = touchManager.getPreviousVector(0, 1); float currentDistance = current.getLength(); float previousDistance = previous.getLength(); if (currentDistance-previousDistance != 0) { scale *= currentDistance / previousDistance; } angle -= VMVector2D.getSignedAngleBetween(current, previous); /*angleCount=angleCount+angle;*/ } } invalidate(); } catch(Exception exception) { // Log.d("VM", exception.getMessage()); } return true; }

    Read the article

  • Why am I getting an IndexOutOfBoundsException here?

    - by Berzerker
    I'm getting an index out of bounds exception thrown and I don't know why, within my replaceValue method below. [null, (10,4), (52,3), (39,9), (78,7), (63,8), (42,2), (50,411)] replacement value test:411 size=7 [null, (10,4), (52,3), (39,9), (78,7), (63,8), (42,2), (50,101)] removal test of :(10,4) [null, (39,9), (52,3), (42,2), (78,7), (63,8), (50,101)] size=6 I try to replace the value again here and get an error... package heappriorityqueue; import java.util.*; public class HeapPriorityQueue<K,V> { protected ArrayList<Entry<K,V>> heap; protected Comparator<K> comp; int size = 0; protected static class MyEntry<K,V> implements Entry<K,V> { protected K key; protected V value; protected int loc; public MyEntry(K k, V v,int i) {key = k; value = v;loc =i;} public K getKey() {return key;} public V getValue() {return value;} public int getLoc(){return loc;} public String toString() {return "(" + key + "," + value + ")";} void setKey(K k1) {key = k1;} void setValue(V v1) {value = v1;} public void setLoc(int i) {loc = i;} } public HeapPriorityQueue() { heap = new ArrayList<Entry<K,V>>(); heap.add(0,null); comp = new DefaultComparator<K>(); } public HeapPriorityQueue(Comparator<K> c) { heap = new ArrayList<Entry<K,V>>(); heap.add(0,null); comp = c; } public int size() {return size;} public boolean isEmpty() {return size == 0; } public Entry<K,V> min() throws EmptyPriorityQueueException { if (isEmpty()) throw new EmptyPriorityQueueException("Priority Queue is Empty"); return heap.get(1); } public Entry<K,V> insert(K k, V v) { size++; Entry<K,V> entry = new MyEntry<K,V>(k,v,size); heap.add(size,entry); upHeap(size); return entry; } public Entry<K,V> removeMin() throws EmptyPriorityQueueException { if (isEmpty()) throw new EmptyPriorityQueueException("Priority Queue is Empty"); if (size == 1) return heap.remove(1); Entry<K,V> min = heap.get(1); heap.set(1, heap.remove(size)); size--; downHeap(1); return min; } public V replaceValue(Entry<K,V> e, V v) throws InvalidEntryException, EmptyPriorityQueueException { // replace the value field of entry e in the priority // queue with the given value v, and return the old value This is where I am getting the IndexOutOfBounds exception, on heap.get(i); if (isEmpty()){ throw new EmptyPriorityQueueException("Priority Queue is Empty."); } checkEntry(e); int i = e.getLoc(); Entry<K,V> entry=heap.get(((i))); V oldVal = entry.getValue(); K key=entry.getKey(); Entry<K,V> insert = new MyEntry<K,V>(key,v,i); heap.set(i, insert); return oldVal; } public K replaceKey(Entry<K,V> e, K k) throws InvalidEntryException, EmptyPriorityQueueException, InvalidKeyException { // replace the key field of entry e in the priority // queue with the given key k, and return the old key if (isEmpty()){ throw new EmptyPriorityQueueException("Priority Queue is Empty."); } checkKey(k); checkEntry(e); K oldKey=e.getKey(); int i = e.getLoc(); Entry<K,V> entry = new MyEntry<K,V>(k,e.getValue(),i); heap.set(i,entry); downHeap(i); upHeap(i); return oldKey; } public Entry<K,V> remove(Entry<K,V> e) throws InvalidEntryException, EmptyPriorityQueueException{ // remove entry e from priority queue and return it if (isEmpty()){ throw new EmptyPriorityQueueException("Priority Queue is Empty."); } MyEntry<K,V> entry = checkEntry(e); if (size==1){ return heap.remove(size--); } int i = e.getLoc(); heap.set(i, heap.remove(size--)); downHeap(i); return entry; } protected void upHeap(int i) { while (i > 1) { if (comp.compare(heap.get(i/2).getKey(), heap.get(i).getKey()) <= 0) break; swap(i/2,i); i = i/2; } } protected void downHeap(int i) { int smallerChild; while (size >= 2*i) { smallerChild = 2*i; if ( size >= 2*i + 1) if (comp.compare(heap.get(2*i + 1).getKey(), heap.get(2*i).getKey()) < 0) smallerChild = 2*i+1; if (comp.compare(heap.get(i).getKey(), heap.get(smallerChild).getKey()) <= 0) break; swap(i, smallerChild); i = smallerChild; } } protected void swap(int j, int i) { heap.get(j).setLoc(i); heap.get(i).setLoc(j); Entry<K,V> temp; temp = heap.get(j); heap.set(j, heap.get(i)); heap.set(i, temp); } public String toString() { return heap.toString(); } protected MyEntry<K,V> checkEntry(Entry<K,V> ent) throws InvalidEntryException { if(ent == null || !(ent instanceof MyEntry)) throw new InvalidEntryException("Invalid entry."); return (MyEntry)ent; } protected void checkKey(K key) throws InvalidKeyException{ try{comp.compare(key,key);} catch(Exception e){throw new InvalidKeyException("Invalid key.");} } }

    Read the article

  • Using AsyncTask to display data in ListView, but onPostExecute not being called

    - by sumisu
    I made a simple AsyncTask class to display data in ListView with the help of this stackoverflow question. But the AsyncTask onPostExecute is not being called. This is my code: public class Start extends SherlockActivity { // JSON Node names private static final String TAG_ID = "id"; private static final String TAG_NAME = "name"; // category JSONArray JSONArray category = null; private ListView lv; @Override public void onCreate(Bundle savedInstanceState) { setTheme(SampleList.THEME); //Used for theme switching in samples super.onCreate(savedInstanceState); setContentView(R.layout.test); new MyAsyncTask().execute("http://...."); // Launching new screen on Selecting Single ListItem lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // getting values from selected ListItem String name = ((TextView) view.findViewById(R.id.name)).getText().toString(); String cost = ((TextView) view.findViewById(R.id.mail)).getText().toString(); // Starting new intent Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class); in.putExtra("categoryname", name); System.out.println(cost); in.putExtra("categoryid", cost); startActivity(in); } }); } public class MyAsyncTask extends AsyncTask<String, Void, ArrayList<HashMap<String, String>> > { // Hashmap for ListView ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>(); @Override protected ArrayList<HashMap<String, String>> doInBackground(String... params) { // Creating JSON Parser instance JSONParser jParser = new JSONParser(); // getting JSON string from URL category = jParser.getJSONArrayFromUrl(params[0]); try { // looping through All Contacts for(int i = 0; i < category.length(); i++){ JSONObject c = category.getJSONObject(i); // Storing each json item in variable String id = c.getString(TAG_ID); String name = c.getString(TAG_NAME); // creating new HashMap HashMap<String, String> map = new HashMap<String, String>(); // adding each child node to HashMap key => value map.put(TAG_ID, id); map.put(TAG_NAME, name); // adding HashList to ArrayList contactList.add(map); } } catch (JSONException e) { Log.e("log_tag", "Error parsing data "+e.toString()); } return contactList; } @Override protected void onPostExecute(ArrayList<HashMap<String, String>> result) { ListAdapter adapter = new SimpleAdapter(Start.this, result , R.layout.list_item, new String[] { TAG_NAME, TAG_ID }, new int[] { R.id.name, R.id.mail }); // selecting single ListView item lv = (ListView) findViewById(R.id.ListView); lv.setAdapter(adapter); } } } Eclipse: 11-25 11:40:31.896: E/AndroidRuntime(917): java.lang.RuntimeException: Unable to start activity ComponentInfo{de.essentials/de.main.Start}: java.lang.NullPointerException

    Read the article

  • Prime Numbers in C?

    - by Ali Azam Rana
    FIRST PROGRAM #include<stdio.h> void main() { int n,c; printf("enter a numb"); scanf("%i",n); for(c=2;c<=n;c++) { if(n%c==0) break; } if(c==n) printf("\nprime\n"); else printf("\nnot prime\n"); getchar(); } SECOND PROGRAM #include <stdio.h> int main() { printf("Enter a Number\n"); int in,loop,rem,chk; scanf("%d",&in); for (loop = 1; loop <=in; loop++) { rem = in % loop; if(rem == 0) chk = chk +1; } if (chk == 2) printf("\nPRIME NUM ENTERED\n"); else printf("\nNUM ENTERED NOT PRIME\n"); getchar(); } the 2nd program works other was the one my friend wrote the program looks fine but on checking it by stepping into we found that the if condition in first program is coming true under every input so whats the logical error here please help me found out......

    Read the article

  • Java: Extend SimpleDateFormat with new pattern letters

    - by Adam Matan
    Java's SimpleDateFormat is used to format a Date object to a string. The formatter supports various pattern letters, which denote textual representation of a Date field. For example, yy is two-letter year, yyyy is four-letter year, and E is day of week. For example, A SimpleDateFormat initialized with yyyy.MM.dd G 'at' HH:mm:ss z will format a date to something like 2001.07.04 AD at 12:08:56 PDT. I would like to add some pattern letters to SimpleDateFormat. For example, want C to denote Hebrew weekday (??? ?????, ??? ???, ...). What's the right way to extend SimpleDateFormat with these new pattern letters? The only online example I could find seems somewhat complicated. I can live with formatting only, without parsing.

    Read the article

  • android zxing intentintegrator

    - by cristi _b
    I've written the following code that works fine if you decide to scan a QR code (using zxing) and store it in private storage but in case you decide to cancel scanning, it crashes and the file previously stored content disappears. I think it might be a design error, not sure why. Below is relevant code ... /** * menu generation */ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; } /** * menu handling */ @Override public boolean onOptionsItemSelected(MenuItem item) { Context context = getApplicationContext(); Toast toast = Toast.makeText(context, "", Toast.LENGTH_LONG); toast.setGravity(Gravity.FILL_HORIZONTAL, 0, 0); switch (item.getItemId()) { case R.id.qrScan: IntentIntegrator integrator = new IntentIntegrator(this); integrator.initiateScan(); return true; case R.id.qrReset: File dir = getFilesDir(); File file = new File(dir, qrCodeFile); boolean deleted = file.delete(); return true; case R.id.appClose: this.finish(); return true; default: return super.onOptionsItemSelected(item); } } ... public void onActivityResult(int requestCode, int resultCode, Intent intent) { IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); Context context = getApplicationContext(); Toast toast = Toast.makeText(context, "", Toast.LENGTH_SHORT); if (scanResult != null) { FileOutputStream fos = null; CharSequence text = scanResult.getContents(); try { fos = openFileOutput(qrCodeFile, Context.MODE_PRIVATE); try { fos.write(text.toString().getBytes()); fos.close(); toast.setGravity(Gravity.FILL_HORIZONTAL, 0, 0); toast.setText("Code saved"); toast.show(); } catch (IOException ex) { toast.setGravity(Gravity.FILL_HORIZONTAL, 0, 0); toast.setText("Invalid code"); toast.show(); Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex); } } catch (FileNotFoundException ex) { toast.setGravity(Gravity.FILL_HORIZONTAL, 0, 0); toast.setText("Error while saving"); toast.show(); Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex); } } else { toast.setGravity(Gravity.FILL_HORIZONTAL, 0, 0); toast.setText("Invalid code"); toast.show(); } }

    Read the article

  • Developed android application cannot connect to phpmyadmin

    - by user1850936
    I am developing an app with eclipse. I tried to store the data that key in by user into database in phpmyadmin. Unfortunately, after the user has clicked on submit button, there is no response and data is not stored in my database. Here is my java file: import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONObject; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import android.content.res.Configuration; public class UserRegister extends Activity { JSONParser jsonParser = new JSONParser(); EditText inputName; EditText inputUsername; EditText inputEmail; EditText inputPassword; RadioButton button1; RadioButton button2; Button button3; int success = 0; private static String url_register_user = "http://10.20.92.81/database/add_user.php"; private static final String TAG_SUCCESS = "success"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user_register); inputName = (EditText) findViewById(R.id.nameTextBox); inputUsername = (EditText) findViewById(R.id.usernameTextBox); inputEmail = (EditText) findViewById(R.id.emailTextBox); inputPassword = (EditText) findViewById(R.id.pwTextBox); Button button3 = (Button) findViewById(R.id.regSubmitButton); button3.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { String name = inputName.getText().toString(); String username = inputUsername.getText().toString(); String email = inputEmail.getText().toString(); String password = inputPassword.getText().toString(); if (name.contentEquals("")||username.contentEquals("")||email.contentEquals("")||password.contentEquals("")) { AlertDialog.Builder builder = new AlertDialog.Builder(UserRegister.this); builder.setMessage(R.string.nullAlert) .setTitle(R.string.alertTitle); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); AlertDialog dialog = builder.show(); } // creating new product in background thread RegisterNewUser(); } }); } public void RegisterNewUser() { try { String name = inputName.getText().toString(); String username = inputUsername.getText().toString(); String email = inputEmail.getText().toString(); String password = inputPassword.getText().toString(); // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("name", name)); params.add(new BasicNameValuePair("username", username)); params.add(new BasicNameValuePair("email", email)); params.add(new BasicNameValuePair("password", password)); // getting JSON Object // Note that create product url accepts POST method JSONObject json = jsonParser.makeHttpRequest(url_register_user, "GET", params); // check log cat for response Log.d("Send Notification", json.toString()); success = json.getInt(TAG_SUCCESS); if (success == 1) { // successfully created product Intent i = new Intent(getApplicationContext(), StudentLogin.class); startActivity(i); finish(); } else { // failed to register } } catch (Exception e) { e.printStackTrace(); } } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } } my php file: <?php $response = array(); require_once __DIR__ . '/db_connect.php'; $db = new DB_CONNECT(); if (isset($_GET['name']) && isset($_GET['username']) && isset($_GET['email']) && isset($_GET['password'])) { $name = $_GET['name']; $username = $_GET['username']; $email = $_GET['email']; $password = $_GET['password']; // mysql inserting a new row $result = mysql_query("INSERT INTO register(name, username, email, password) VALUES('$name', '$username', '$email', '$password')"); // check if row inserted or not if ($result) { // successfully inserted into database $response["success"] = 1; $response["message"] = "You are successfully registered to MEMS."; // echoing JSON response echo json_encode($response); } else { // failed to insert row $response["success"] = 0; $response["message"] = "Oops! An error occurred."; // echoing JSON response echo json_encode($response); } } else { // required field is missing $response["success"] = 0; $response["message"] = "Required field(s) is missing"; // echoing JSON response echo json_encode($response); } ?> the log cat is as follows: 11-25 10:37:46.772: I/Choreographer(638): Skipped 30 frames! The application may be doing too much work on its main thread.

    Read the article

  • JAVA bytecode optimization

    - by Idob
    This is a basic question. I have code which shouldn't run on metadata beans. All metadata beans are located under metadata package. Now, I use reflection API to find out whether a class is located in the the metadata package. if (newEntity.getClass().getPackage().getName().contains("metadata")) I use this If in several places within this code. The question is: Should I do this once with: boolean isMetadata = false if (newEntity.getClass().getPackage().getName().contains("metadata")) { isMetadata = true; } C++ makes optimizations and knows that this code was already called and it won't call it again. Does JAVA makes optimization? I know reflection API is a beat heavy and I prefer not to lose expensive runtime.

    Read the article

  • EF Linq Product Sum when no records returned

    - by user1622713
    I’ve seen variations of this question all over the place but none of the answers work for me. Most of them are just trying to sum a single column too – nothing more complex such as the sum of a product as below: public double Total { get { return _Context.Sales.Where(t => t.Quantity > 0) .DefaultIfEmpty() .Sum(t => t.Quantity * t.Price); } } If no rows are returned I want to return zero. However if no rows are returned the .Sum() fails. There are various options of trying to insert Convert.ToDouble and using null coalesce operators, but they all still gave me errors. I’m sure I am missing a simple way to do this – any help greatly appreciated after too long banging head against google brick wall!

    Read the article

  • NoMethodError / undefined method `foobar_path' when using form_for

    - by user1850886
    I'm using form_for to create a chatroom and when I view the page I get the following error: NoMethodError in Chatrooms#new undefined method `chatrooms_path' for #<#<Class:0xa862b94>:0xa5307f0> Here's the code for the view, located in app/views/chatrooms/new.html.erb: <div class="center"> <%= form_for(@chatroom) do |f| %> <%=f.text_field :topic%> <br> <%=f.submit "Start a discussion", class: "btn btn-large btn-primary"%> <% end %> </div> Here's the relevant controller: class ChatroomsController < ApplicationController def new @chatroom = Chatroom.new end def show @chatroom = Chatroom.find(params[:id]) end end If I change the line <%= form_for(@chatroom) do |f| %> to <%= form_for(:chatroom) do |f| %> it works fine. I've searched around for similar questions but none of the solutions have worked for me. Help?

    Read the article

  • fail-fast iterator

    - by joy
    I get this definition : As name suggest fail-fast Iterators fail as soon as they realized that structure of Collection has been changed since iteration has begun. what it mean by since iteration has begun? is that mean after Iterator it=set.iterator() this line of code? public static void customize(BufferedReader br) throws IOException{ Set<String> set=new HashSet<String>(); // Actual type parameter added **Iterator it=set.iterator();**

    Read the article

  • Android calculator with button click

    - by rynwtts
    I am trying to calculate a field named lblAnswer by adding values txtA + txtB. I am fairly new to the android development world and would like to know what is the best way of going about this. I have already added the necessarily edit fields to the GUI. I am now working in the java file to try and create the method. This method has been named doCalc. Here is what I have thus far. public void doCalc() { lblAnswer = txtA + txtB; } It has been suggested that I add more code here is the full code. Thank you for that suggestion. Here is the Java File. package com.example.wattsprofessional; import android.app.Activity; import android.os.Bundle; import android.view.Menu; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } public void doCalc() { lblAnswer = txtA + txtB; Double.parseDouble(txtA.getText().toString()); lblAnswer.setText"t } and here is the xml file. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <EditText android:id="@+id/txtA" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="40dp" android:ems="10" android:hint="Write Here" android:inputType="numberDecimal" > <requestFocus /> </EditText> <EditText android:id="@+id/txtB" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/txtA" android:layout_below="@+id/txtA" android:layout_marginTop="32dp" android:ems="10" android:hint="Second Here" android:inputType="numberDecimal" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="@string/calculate" android:onClick="doCalc"/> <TextView android:id="@+id/lblAnswer" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/button1" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:text="TextView" /> </RelativeLayout>

    Read the article

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