java,arrays,object,equalsView the original page-Collection of common programming errors

UnKnown Error


  • Drew Noakes
    java command-line-arguments 2014-1-10 20:07:21
    I have seen many apps that take instrument classes and take -javaagent as a param when loading also put a -noverify to the command line.The Java doc says that -noverify turns off class verification.However why would anyone want to turn off verification even if they are instrumenting classes?

  • Pascal Thivent
    java hibernate orm jpa postgis 2014-1-10 19:57:04
    I am using Hibernate/JPA to execute native PostGIS queries. The problem with these queries is that they need parameters that are not of the classical X = ‘value’ form.For example, the following lines crashString queryString = “select * from Cell c where ST_DWithin(c.shape, SetSRID(ST_GeomFromEWKT(‘POINT(:lon :lat)’),4326), 0.1)”;Query query = Cell.em().createNativeQuery(queryString, Cell.class);query.setParameter(“lon”, longitude);query.setParameter(“lat”, latitude);play.exceptions.JavaExecution

  • Rob Kielty
    java centos memory-mapped-files tlb memory-barriers 2014-1-10 19:37:48
    Memory barriers guarantee that the data cache will be consistent. However, does it guarantee that the TLB will be consistent?I am seeing a problem where the JVM (java 7 update 1) sometimes crashes with memory errors (SIGBUS, SIGSEG) when passing a MappedByteBuffer between threads.e.g.final AtomicReference<MappedByteBuffer> mbbQueue = new AtomicReference<>();// in a background thread. MappedByteBuffer map = raf.map(MapMode.READ_WRITE, offset, allocationSize); Thread.yield(); while (!i

  • Mr Teeth
    java client system 2014-1-10 18:54:23
    I’m currently doing a project where I’m going to build an application (created in Java) alongside a database. So this will be client server system i’m developing. Part of my project would be to research existing client server systems.So I was wondering is there any good client server systems, that was built using Java, that I can take a look at? I’m interested in novice to professional programs, but not something too complicated that i won’t be able to get my head around.I want to discuss them i

  • Sean Patrick Floyd
    java concurrency singleton double-checked-locking 2014-1-10 18:45:08
    Why is the pattern considered broken? It looks fine to me? Any ideas?public static Singleton getInst() {if (instace == null) createInst();return instace; }private static synchronized createInst() {if (instace == null) {instace = new Singleton(); } }

  • skaffman
    java unit-testing testng 2014-1-10 17:35:01
    I have an abstract basis class, which I use as a basis for my unit tests (TestNG 5.10). In this class I initialize the whole environment for my tests, setting up database mappings, etc. That abstract class has a method with a @BeforeClass annotation which does the initialization. Next thing, I extend that class with specific classes in which I have @Test methods and also @BeforeClass methods. These methods do class-specific initialization of the environment, e.g. put some records into the databa

  • SyBer
    java memory garbage-collection heap 2014-1-10 17:30:23
    What is the benefit of setting the -Xms parameter, and having the initial memory larger for example, then the default calculated one (64 MB in my case, according to Java GC tunning: http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html#par_gc.ergonomics.default_size)?Also, is there any good to setting both the initial and maximum memories to same size?Thanks.

  • Quaz and Wally
    java eclipse gwt libgdx 2014-1-10 16:55:45
    I’ve almost got my libgdx project running as a web application through gwt, but it keeps crashing when it tries to load a font file. I’ve found people with similar problems, but their solutions don’t seem to be working for me.This is the suspect line where the crash is occurring:font = new BitmapFont(Gdx.files.internal(“data/fonts/test.fnt”), Gdx.files.internal(“data/fonts/test_0.tga”), false, true);I’m using Gdx.files.internal so that it doesn’t try to use the classpath when searching for the

  • skaffman
    java resources log4j 2014-1-10 16:39:54
    So, I’m trying out the apache log4j library and I managed to get everything working correctly. I ran my program once and it did all of the logging just perfectly. Then, I went to run it again and it crashed. I tried again and again the program crashed.I have a few .properties files in a properties/ directory. I’m using two different .properties files and loading them both using getResource and getResourceAsStream respectively:first in order to configure my logger:PropertyConfigurator.configure(M

  • Borissow
    java linux gui native-methods 2014-1-10 16:37:07
    I am trying to read and write to the parallel port, I implemented the writing and reading in C, now I want to import that code into a java GUI application. I managed to include the C .so file into the java project and when calling the functions directly in the Java solutions main() method they work just fine. I tried to call the native functions when a button is pressed, but it won’t work, the application crashes. I am running the application as root, root priviledge is needed to change and read

  • Efe Gürkan
    c++ arrays pointers delete 2014-1-10 16:59:52
    I’m having problems about deleting dynamic arrays in my project. first appear : void StudentReviewSystem::addCourse( const int courseId, const string courseName ) {int i = findCourse( courseId );if ( i == -1 ){int newNum = numberOfCourses + 1;Course *newCourses = new Course[newNum];for ( int j = 0; j < numberOfCourses; j++ ){newCourses[j] = courses[j];}Course aCourse(courseId, courseName);newCourses[numberOfCourses] = aCourse;//delete[] courses;courses = newCourses;numberOfCourses = newNum;co

  • kjakeb
    c arrays pointers c-strings 2014-1-10 12:30:22
    I’m attempting to convert an array of ints to an array of strings in c. My code so far is:int args[] = {1, 3000}; char *str_args[15]; int i = 0; for(i; i<=((sizeof(args)/sizeof(args[0]))); i++){char buffer[10];sprintf(buffer, “%d”, args[i]);str_args[i] = buffer; } printf(“%s\n”, *str_args[0]);This code causes my program to crash instead of outputting 1 (the first arg) like I expect. What am I missing here? Thanks in advance

  • ingenspor
    iphone xcode arrays dictionary bounds 2014-1-10 12:12:47
    Here it works fine. If I try to swipe right (back) from first object in index nothing happens.- (void)swipeDetectedRight:(UISwipeGestureRecognizer *)sender { if (detailIndex != 0)detailIndex–; Label.text = [[detailsDataSource objectAtIndex: detailIndex] valueForKey:@”Text”]; }But when I’m on the last entry (nr 100) and swipes left, it crashes. Heres the code for left:- (void)swipeDetectedLeft:(UISwipeGestureRecognizer *)sender {if (detailIndex != [detailsDataSource count])detailIndex++;Label.t

  • Anas
    php arrays parsing 2014-1-10 11:18:09
    So I have two files, formatted like this:First fileadam 20 male ben 21 maleSecond fileadam blonde adam white ben blondeWhat I would like to do, is use the instance of adam in the first file, and search for it in the second file and print out the attributes.Data is seperated by tab “\t”, so this is what I have so far.$firstFile = fopen(“file1”, “rb”); //opens first file $i=0; $k=0; while (!feof($firstFile) ) { //feof = while not end of file$firstFileRow = fgets($firstFile); //fgets gets line $p

  • Syngularity
    c++ arrays file tabs io 2014-1-10 6:47:50
    I have file like this:int1–tab–int2–tab–int3–tab–int4–tab–newlineint1–tab–int2–tab–int3–tab–int4–tab–newlineint1–tab–int2–tab–int3–tab–int4–tab–newline …I want to save each row in to an array. I mean all int1 in to an array and want to do the same whit int2 int3 …I realy dont know how to do it please help me I already try read it line by line#include <sstream> #include <string>std::string line; while (std::getline(infile, line)) {std::istringstream iss(li

  • user723858
    jquery arrays json updating 2014-1-10 5:38:10
    I am trying to update a JSON array of data that is being stored in localStorage but it keeps crashing for some reason and I dont know why. Below is the code:this.setToken = function(newToken) {var settingsList = JSON.parse(window.localStorage.getItem(“settings”));var l = settingsList.length;for (var i=0; i < l; i++) {if (settingsList[i].token === “”) {app.showAlert(newToken,”[TOKEN-DEBUG]”);settingsList.[i].token = newToken;break;}}}var settings = [{“token”: “”}];window.localStorage.setItem(“

  • cplusJones
    c++ arrays string 2014-1-10 4:21:11
    This is how does it work question. Based on my understanding you have to initiate an non dynamic array with a constant number of elements (int intarr[5]) or your array will write over blocks of memory that might be allocated for something else.So why is it that you can initiate a string array (string strArray[]) without any elements?Example:#include <iostream> #include <string> using namespace std;int main() { string s[] = {“hi”, “there”};cout << s[0] << s[1]; cin >>

  • Andrew Barber
    c++ arrays heap structures 2014-1-10 3:37:02
    I need to declare an array of structures on the heap, then transfer data from parallel arrays on the stack and from calculations into each structure. I declared struct Grades {string studentName;int scores[4];double average; };….Grades *art1301 = new Grades;….(art1301 + i)->studentName = names[i];for((int i = 0 ; i < 5 ; i++ ) (art1301 + i)->scores[j] = exams[i][j];(art1301 + i)->average = average; My program accesses the first record, but it crashes after it accesses the f

  • starkk
    c arrays pointers segmentation-fault 2014-1-9 23:50:50
    This program uses quicksort to sort the numbers followed by the code which places the negative and positive numbers alternatively. #include<stdio.h> #include<stdlib.h>void swap(int *arr,int i,int j) {int temp=arr[i];arr[i]=arr[j];arr[j]=temp; }int partition(int *arr,int left,int right) {int temp=0;int i=left;int j=right;while(i<=j){while(i<=right && arr[i]<=temp)i++;while(j>=left && arr[j]>=temp)j–;if(i<j)swap(arr,i,j);}return j; }void quick_sort(i

  • tech_learning
    objective-c arrays ios6 ios-ui-automation 2014-1-9 22:36:31
    I am dealing with UIAElementArray for the ios automation and looking for an easier way to search inside the UIAElementArray.Below is the code:var textArray = this.myCollectionViews.staticTexts();textArray.toArray() // Trying to convert UIAElementArray to a javascript array.logger.logDebug(‘Array object is’ + textArray); // Here the output is [object UIAElementArray]; which I guess should be Array and not UIAElementArray.if (textArray.indexOf(‘Hello’) > -1) {// do this }Here I am getting a cr

  • xcdemon05
    c++ object memory delete heap 2014-1-10 15:28:43
    In one of my objects, I create an unsigned character array member to store some image data:unsigned char* imageData;and in the constructor I initialize it with new:MyObject::MyObject(){int imageSize = 6054400;imageData = new unsigned char[imageSize];}imageData gets filled throughout the course of the loop.This object (MyObject) won’t get deleted until the very end of the loop, but I need imageData to be deleted midway through the loop. So I just created this function:void MyObject::DeleteAllMem

  • Aleks
    memory object nsmutablearray nscopying copywithzone 2014-1-10 15:25:38
    I have a NSMutableArray called organisations which is an array of custom objects of a class I subclassed from NSObject, this subclass is called NSXOrganisation. This subclass DOES implement NSCopy like so:@interface NSXOrganisation : NSObject <NSCopying>…- (id)copyWithZone:(NSZone *)zone {id copy = [[[self class] alloc] init];if (copy) {[copy setPropertyOne:[[[self getPropertyOne] copyWithZone:zone] autorelease]]; }return copy; }Now, I alloc & init the array like so:organis

  • Justin
    iphone objective-c object ibaction 2014-1-10 13:35:15
    I’m sure this is going to sound very weird, but I’ll ask anyway. I have made multiple working applications for the iPhone, but I have to add everything to the original view controller. If I don’t do so, the app crashes. Here is my example:In the view controller:- (IBAction) someAction: (id) sender {NSLog(@”lajkrbgl”);}This works just fine. But, if I do the “Add File” and I choose “Objective-C Class”, and put the same code in, the app just crashes whenever I press the button. How can I add more o

  • otneil
    c++ pointers object vector 2014-1-9 1:32:54
    I’m having some trouble to find the best way to accomplish what I have in mind due to my inexperience. I have a class where I need to a vector of objects. So my first question will be:is there any problem having this: vector< AnyType > container* and then on the constructor initialize it with new (and deleting it on the destructor)?Another question is: if this vector is going to store objects, shouldn’t it be more like vector< AnyTipe* > so they could be dynamically created? In that case h

  • Anoop Vaidya
    objective-c cocoa-touch object memory-management retain 2014-1-8 21:43:14
    I need some clarification for following code.I have a array which contain ClassA object. Then i retrieve one of it’s object and assign it to local variable object1. ClassA object1 = [ClassAObjectContainer objectAtIndex:0];( Q.1 – Does this increase retain count?? i think it’s not )Now i remove object[ClassAObjectContainer removeObjectAtIndex:0];( Q.2 – So now object1 point to deallocated instance?? and if i send message to it will it crash??So i should use ClassA object1 = [[ClassAObjectContain

  • H2CO3
    objective-c xcode oop object ownership 2014-1-8 14:40:54
    I am trying to swap two objects upon a button action, but I can’t get it to work. It’s swapping on first time, but next time when I click on the button, it crashes with EXC_BAD_ACCESS.Here’s the code-(IBAction)swapLocation {CCLocDTO *tempDto = searchDTO.toDTO;searchDTO.toDTO = searchDTO.fromDTO;searchDTO.fromDTO = tempDto;NSLog(@”From Location is %@”,searchDTO.fromDTO.streetAddress); //it becomes empty on next button clickNSLog(@”To Location is %@”,searchDTO.toDTO.streetAddress);NSLog(@”From Spe

  • jcb344
    iphone object global-variables 2014-1-8 6:57:57
    What is the easiest way to create a global object. I have tried declaring the object outside the method with no luck.@implementation UV_TouchpadViewController; NSMutableString *string = [NSMutableString stringWithFormat:@”text”];

  • Tim Post
    c++ object delete new-operator 2014-1-8 6:39:27
    Here is a sample code that I have:void test() {Object1 *obj = new Object1();…delete obj; }I run it in Visual Studio, and it crashes at the line with ‘delete obj;’. Isn’t this the normal way to free the memory associated with an object? I realized that it automatically invokes the destructor… is this normal?Here is some code snippet:if(node->isleaf()){vector<string> vec = node->L;vec.push_back(node->code);sort(vec.begin(), vec.end());Mesh* msh = loadLeaves(vec, node->code);S

  • scotthew1
    c++ object bus-error 2014-1-8 5:37:02
    I’m running into a weird bus error when trying to create an object in C++. This is my gdb backtrace when the program crashes:#0 0xff146ff4 in _malloc_unlocked () from /usr/lib/libc.so.1 #1 0xff146e40 in malloc () from /usr/lib/libc.so.1 #2 0x24430 in __builtin_new (sz=128) at /usr/local/src/gcc-2.95.1/gcc/cp/new1.cc:84 #3 0x1e71c in FileHeader::Allocate (this=0x3f5d8, freeMap=0x3eea0, fileSize=5719)at ../filesys/filehdr.cc:63 #4 0x1f61c in FileSystem::Create (this=0x3d8b8, name=0xffbff8f3 “

  • user776720
    iphone object nsmutablearray 2014-1-7 17:26:59
    I am trying to empty an NSMutableArray with the [myarray removeallobjects]; but I am getting error exc_bad_access. Is this the right way to empty the array? I tried to set it to nil but its not working either. Actually what I am doing is filling the array with data and the user has the option to “refresh” the data and I want to empty the array before enter the refreshed data. I cant post any code because is too big.

  • Christopher Pfohl
    javascript collections backbone.js equals 2013-11-6 0:39:21
    I have a model that has a bunch of attributes but the two of interest here are id and key. key is always unique, id not so much. When I try to add more than one model with the same id to a collection, I get this error:Uncaught Error: Can’t add the same model to a collection twiceI am guessing this is because backbone is using the id to decide if two models are ===. Is that correct? If so is there a way to override this behaviour without swapping the name of the id and key attributes? I tried mes

  • Dave Mateer
    c# .net equals bitarray 2013-10-18 20:07:53
    I need something a little more than the System.Collections.BitArray class in my application. Specifically, I need the bit array:To be immutable To implement equality using value semanticsI created my own struct, largely copying the internals of the BitArray implementation. (Thanks, .Net Reflector!)I don’t deal everyday with bitwise operations, so I don’t have the highest degree of confidence in my equality implementation. (It’s passing the unit tests I am throwing at it, but I may be missing edg

  • Mathijs Flietstra
    javascript json string object equals 2013-9-30 3:36:43
    I am developing this website layout for http://myttc.ca. I was successful at retrieving most of the data and displaying it on the page.But when I had to filter my search to find only the stop names that had only Subways, I get stuck with errors. Here is the JSON page, http://myttc.ca/finch_station.json. Here, when I try to access only the stops having the route name as Yonge-University-Spadina Subway, I get an error saying Uncaught TypeError: Cannot call method ‘equals’ of undefined. I also trie

  • user1270438
    c++ equals 2013-9-19 14:57:32
    i was asked to implement a c++ code to perform the assignment x=y without the = sign and without functions. I have used the memcpy:int main(int argc, char *argv[]) {int x(5),y(3);memcpy(&x,&y,sizeof(y));printf(“%d”,x);getchar();return 0; }any other generic solutions?Thanks

  • John Threepwood
    c# equals 2013-9-17 10:37:15
    In C Sharp .NET there is a Equals method and a SetEquals method. Where is the difference?Coming from Java, my first thought was that SetEquals is not necessary, just use the Equals method for all objects.

  • user2759565
    java equals 2013-9-16 6:11:35
    I am posting a chunk of problematic code here. I am trying to compare two object types and their values simultaneously.public boolean equals(Object val1) {if (!(val1 instanceof ParentClass))return false;ParentClass val2 = (ParentClass) val1;if ((val1.getClass().equals(val2.getClass())) && val1.getVal().equals(val2.getVal()));System.out.println(“Both objects belong to same class and the values are equal too!!”);return true;}I have this chunk in my parent class and i am getting errors(The

  • David M
    java hashmap equals hashcode 2013-9-14 13:16:42
    I have this test code:import java.util.*;class MapEQ {public static void main(String[] args) {Map<ToDos, String> m = new HashMap<ToDos, String>();ToDos t1 = new ToDos(“Monday”);ToDos t2 = new ToDos(“Monday”);ToDos t3 = new ToDos(“Tuesday”);m.put(t1, “doLaundry”);m.put(t2, “payBills”);m.put(t3, “cleanAttic”);System.out.println(m.size()); } }class ToDos{String day;ToDos(String d) { day = d; }public boolean equals(Object o) {return ((ToDos)o).day == this.day;}// public int hashCode() {

  • Evan
    jquery height accordion collapse equals 2013-9-12 17:36:08
    Thanks to @ifaour for a lot of his help! This script includes:Jquery accordion using unordered lists. Active and Inactive states with toggling bullet arrow images Expand All / Collapse All that swaps its text. Equal height columns that expand and collapse when the accordion expands and collapsesYou can view a demo here http://jsbin.com/ucobo3/24/(function($) { $.fn.equalHeights = function(minHeight, maxHeight) { tallest = (minHeight) ? minHeight : 0; this.each(function() { if($(this).height() &g

  • Grammin
    java arrays object equals 2013-9-10 19:02:51
    I have two object arrays like so:Object[] array1 = {0, 1, 2, 3}; Object[] array2 = {0, 1, 2, 3};I would like to know if the arrays are equal. I’m defining equal as every value in array1 is the same as the value in that position in the array2. So these two arrays would be equal. What is the best why to find out if these two arrays are equal?if(array1 == array2) is not a deep equals so that won’t work and I don’t know if looping over each element and comparing them is the best and most efficient

  • MonteCristo
    arrays perl compare equals match 2013-9-6 9:20:34
    I have 2 arrays@a = qw/ A B C D E /;@b = qw/ B B C A /; I need to check if the same element appear in the same position of each arraye.g. $a[2] = “B”;$b[3] = “C”;if so count the number of times this happened it need to disregard any blank elementse.g.$a[6] = ;$b[6] = ;comments are most appreciated I like to understand the script.I tried intersect eq == cmp etc but I can’t quite get it and not quite sureThanks in advance.Here’s my code so far:#!/usr/bin/perl -wmy @a = <FILE1>