Search Results

Search found 196 results on 8 pages for 'compareto'.

Page 7/8 | < Previous Page | 3 4 5 6 7 8  | Next Page >

  • IComparer for integers with and empty strings at end

    - by paulio
    Hi, I've written the following IComparer but I need some help. I'm trying to sort a list of numbers but some of the numbers may not have been filled in. I want these numbers to be sent to the end of the list at all times.. for example... [EMPTY], 1, [EMPTY], 3, 2 would become... 1, 2, 3, [EMPTY], [EMPTY] and reversed this would become... 3, 2, 1, [EMPTY], [EMPTY] Any ideas? public int Compare(ListViewItem x, ListViewItem y) { int comparison = int.MinValue; ListViewItem.ListViewSubItem itemOne = x.SubItems[subItemIndex]; ListViewItem.ListViewSubItem itemTwo = y.SubItems[subItemIndex]; if (!string.IsNullOrEmpty(itemOne.Text) && !string.IsNullOrEmpty(itemTwo.Text)) { uint itemOneComparison = uint.Parse(itemOne.Text); uint itemTwoComparison = uint.Parse(itemTwo.Text); comparison = itemOneComparison.CompareTo(itemTwoComparison); } else { // ALWAYS SEND TO BOTTOM/END OF LIST. } // Calculate correct return value based on object comparison. if (OrderOfSort == SortOrder.Descending) { // Descending sort is selected, return negative result of compare operation. comparison = (-comparison); } else if (OrderOfSort == SortOrder.None) { // Return '0' to indicate they are equal. comparison = 0; } return comparison; } Cheers.

    Read the article

  • IComparer for integers and force empty strings to end

    - by paulio
    Hi, I've written the following IComparer but I need some help. I'm trying to sort a list of numbers but some of the numbers may not have been filled in. I want these numbers to be sent to the end of the list at all times.. for example... [EMPTY], 1, [EMPTY], 3, 2 would become... 1, 2, 3, [EMPTY], [EMPTY] and reversed this would become... 3, 2, 1, [EMPTY], [EMPTY] Any ideas? public int Compare(ListViewItem x, ListViewItem y) { int comparison = int.MinValue; ListViewItem.ListViewSubItem itemOne = x.SubItems[subItemIndex]; ListViewItem.ListViewSubItem itemTwo = y.SubItems[subItemIndex]; if (!string.IsNullOrEmpty(itemOne.Text) && !string.IsNullOrEmpty(itemTwo.Text)) { uint itemOneComparison = uint.Parse(itemOne.Text); uint itemTwoComparison = uint.Parse(itemTwo.Text); comparison = itemOneComparison.CompareTo(itemTwoComparison); } else { // ALWAYS SEND TO BOTTOM/END OF LIST. } // Calculate correct return value based on object comparison. if (OrderOfSort == SortOrder.Descending) { // Descending sort is selected, return negative result of compare operation. comparison = (-comparison); } else if (OrderOfSort == SortOrder.None) { // Return '0' to indicate they are equal. comparison = 0; } return comparison; } Cheers.

    Read the article

  • Why doesn't java.lang.Number implement Comparable?

    - by Julien Chastang
    Does anyone know why java.lang.Number does not implement Comparable? This means that you cannot sort Numbers with Collections.sort which seems to me a little strange. Post discussion update: Thanks for all the helpful responses. I ended up doing some more research about this topic. The simplest explanation for why java.lang.Number does not implement Comparable is rooted in mutability concerns. For a bit of review, java.lang.Number is the abstract super-type of AtomicInteger, AtomicLong, BigDecimal, BigInteger, Byte, Double, Float, Integer, Long and Short. On that list, AtomicInteger and AtomicLong to do not implement Comparable. Digging around, I discovered that it is not a good practice to implement Comparable on mutable types because the objects can change during or after comparison rendering the result of the comparison useless. Both AtomicLong and AtomicInteger are mutable. The API designers had the forethought to not have Number implement Comparable because it would have constrained implementation of future subtypes. Indeed, AtomicLong and AtomicInteger were added in Java 1.5 long after java.lang.Number was initially implemented. Apart from mutability, there are probably other considerations here too. A compareTo implementation in Number would have to promote all numeric values to BigDecimal because it is capable of accommodating all the Number sub-types. The implication of that promotion in terms of mathematics and performance is a bit unclear to me, but my intuition finds that solution kludgy.

    Read the article

  • How do I make this nested for loop, testing sums of cubes, more efficient?

    - by Brian J. Fink
    I'm trying to iterate through all the combinations of pairs of positive long integers in Java and testing the sum of their cubes to discover if it's a Fibonacci number. I'm currently doing this by using the value of the outer loop variable as the inner loop's upper limit, with the effect being that the outer loop runs a little slower each time. Initially it appeared to run very quickly--I was up to 10 digits within minutes. But now after 2 full days of continuous execution, I'm only somewhere in the middle range of 15 digits. At this rate it may end up taking a whole year just to finish running this program. The code for the program is below: import java.lang.*; import java.math.*; public class FindFib { public static void main(String args[]) { long uLimit=9223372036854775807L; //long maximum value BigDecimal PHI=new BigDecimal(1D+Math.sqrt(5D)/2D); //Golden Ratio for(long a=1;a<=uLimit;a++) //Outer Loop, 1 to maximum for(long b=1;b<=a;b++) //Inner Loop, 1 to current outer { //Cube the numbers and add BigDecimal c=BigDecimal.valueOf(a).pow(3).add(BigDecimal.valueOf(b).pow(3)); System.out.print(c+" "); //Output result //Upper and lower limits of interval for Mobius test: [c*PHI-1/c,c*PHI+1/c] BigDecimal d=c.multiply(PHI).subtract(BigDecimal.ONE.divide(c,BigDecimal.ROUND_HALF_UP)), e=c.multiply(PHI).add(BigDecimal.ONE.divide(c,BigDecimal.ROUND_HALF_UP)); //Mobius test: if integer in interval (floor values unequal) Fibonacci number! if (d.toBigInteger().compareTo(e.toBigInteger())!=0) System.out.println(); //Line feed else System.out.print("\r"); //Carriage return instead } //Display final message System.out.println("\rDone. "); } } Now the use of BigDecimal and BigInteger was delibrate; I need them to get the necessary precision. Is there anything other than my variable types that I could change to gain better efficiency?

    Read the article

  • Powershell finding services using a cmdlet dll

    - by bartonm
    I need to upgrade a dll assemblies, written in C#, in our installation. Before I replace the DLL file, I want to check if the file has a lock and if so display a message. How do I implement this in powershell? I was thinking iterate through Get-Process checking dependencies. Solved. I iterated through list looking a file path match. function IsCaradigmPowershellDLLFree() { # The list of DLLs to check for locks by running processes. $DllsToCheckForLocks = "$env:ProgramFiles\Caradigm Platform\System 3.0\Platform\PowerShell\Caradigm.Platform.Powershell.dll", "$env:ProgramFiles\Caradigm Platform\System 3.0\Platform\PowerShell\Caradigm.Platform.Powershell.InternalPlatformSetup.dll"; # Assume true, then check all process dependencies $result = $true; # Iterate through each process and check module dependencies foreach ($p in Get-Process) { # Iterate through each dll used in a given process foreach ($m in Get-Process -Name $p.ProcessName -Module -ErrorAction SilentlyContinue) { # Check if dll dependency match any DLLs in list foreach ($dll in $DllsToCheckForLocks) { # Compare the fully-qualified file paths, # if there's a match then a lock exists. if ( ($m.FileName.CompareTo($dll) -eq 0) ) { $pName = $p.ProcessName.ToString() Write-Error "$dll is locked by $pName. This dll must be have zero locked prior to upgrade. Stop this service to release this lock on $m1." $result = $false; } } } } return $result; }

    Read the article

  • Java Function Analysis

    - by khan
    Okay..I am a total Python guy and have very rarely worked with Java and its methods. The condition is that I have a got a Java function that I have to explain to my instructor and I have got no clue about how to do so..so if one of you can read this properly, kindly help me out in breaking it down and explaining it. Also, i need to find out any flaw in its operation (i.e. usage of loops, etc.) if there is any. Finally, what is the difference between 'string' and 'string[]' types? public static void search(String findfrom, String[] thething){ if(thething.length > 5){ System.err.println("The thing is quite long"); } else{ int[] rescount = new int[thething.length]; for(int i = 0; i < thething.length; i++){ String[] characs = findfrom.split("[ \"\'\t\n\b\f\r]", 0); for(int j = 0; j < characs.length; j++){ if(characs[j].compareTo(thething[i]) == 0){ rescount[i]++; } } } for (int j = 0; j < thething.length; j++) { System.out.println(thething[j] + ": " + rescount[j]); } } }

    Read the article

  • Getting an exception when trying to use extension method with SortedDictionary... why?

    - by Polaris878
    I'm trying to place custom objects into a sorted dictionary... I am then trying to use an extension method (Max()) on this sorted dictionary. However, I'm getting the exception: "At least one object must implement IComparable". I don't understand why I'm getting that, as my custom object obviously implements IComparable. Here is my code: public class MyDate : IComparable<MyDate> { int IComparable<MyDate>.CompareTo(MyDate obj) { if (obj != null) { if (this.Value.Ticks < obj.Value.Ticks) { return 1; } else if (this.Value.Ticks == obj.Value.Ticks) { return 0; } else { return -1; } } } public MyDate(DateTime date) { this.Value = date; } public DateTime Value; } class Program { static void Main(string[] args) { SortedDictionary<MyDate, int> sd = new SortedDictionary<MyDate,int>(); sd.Add(new MyDate(new DateTime(1)), 1); sd.Add(new MyDate(new DateTime(2)), 2); Console.WriteLine(sd.Max().Value); // Throws exception!! } } What on earth am I doing wrong???

    Read the article

  • Java convert time format to integer or long

    - by behrk2
    Hello, I'm wondering what the best method is to convert a time string in the format of 00:00:00 to an integer or a long? My ultimate goal is to be able to convert a bunch of string times to integers/longs, add them to an array, and find the most recent time in the array... I'd appreciate any help, thanks! Ok, based on the answers, I have decided to go ahead and compare the strings directly. However, I am having some trouble. It is possible to have more than one "most recent" time, that is, if two times are equal. If that is the case, I want to add the index of both of those times to an ArrayList. Here is my current code: days[0] = "15:00:00"; days[1] = "17:00:00"; days[2] = "18:00:00"; days[3] = "19:00:00"; days[4] = "19:00:00"; days[5] = "15:00:00"; days[6] = "13:00:00"; ArrayList<Integer> indexes = new ArrayList<Integer>(); String curMax = days[0]; for (int x = 1; x < days.length1; x++) { if (days[x].compareTo(curMax) > 0) { curMax = days[x]; indexes.add(x); System.out.println("INDEX OF THE LARGEST VALUE: " + x); } } However, this is adding index 1, 2, and 3 to the ArrayList... Can anyone help me?

    Read the article

  • Arrays not counting correctly

    - by Nick Gibson
    I know I was just asking a question earlier facepalm This is in Java coding by the way. Well after everyones VERY VERY helpful advice (thank you guys alot) I managed to get over half of the program running how I wanted. Everything is pointing in the arrays where I want them to go. Now I just need to access the arrays so that It prints the correct information randomly. This is the current code that im using: http://pastebin.org/301483 The specific code giving me problems is this: long aa; int abc; for (int i = 0; i < x; i++) { aa = Math.round(Math.random()*10); String str = Long.toString(aa); abc = Integer.parseInt(str); String[] userAnswer = new String[x]; if(abc > x) { JOptionPane.showMessageDialog(null,"Number is too high. \nNumber Generator will reset."); break; } userAnswer[i] = JOptionPane.showInputDialog(null,"Question "+quesNum+"\n"+questions[abc]+"\n\nA: "+a[abc]+"\nB: "+b[abc]+"\nC: "+c[abc]+"\nD: "+d[abc]); answer = userAnswer[i].compareTo(answers[i]); if(answer == 0) { JOptionPane.showMessageDialog(null,"Correct. \nThe Correct Answer is "+answers[abc]+""+i); } else { JOptionPane.showMessageDialog(null,"Wrong. \n The Correct Answer is "+answers[abc]+""+i); }//else

    Read the article

  • Need a Java based interruptible timer thread

    - by LambeauLeap
    I have a Main Program which is running a script on the target device(smart phone) and in a while loop waiting for stdout messages. However in this particular case, some of the heartbeat messages on the stdout could be spaced almost 45secs to a 1minute apart. something like: stream = device.runProgram(RESTORE_LOGS, new String[] {}); stream.flush(); String line = stream.readLine(); while (line.compareTo("") != 0) { reporter.commentOnJob(jobId, line); line = stream.readLine(); } So, I want to be a able to start a new interruptible thread after reading line from stdout with a required a sleep window. Upon being able to read a new line, I want to be able to interrupt/stop(having trouble killing the process), handle the newline of stdout text and restart a process. And it the event I am not able to read a line within the timer window(say 45secs) I want to a way to get out of my while loop either. I already tried the thread.run, thread.interrupt approach. But having trouble killing and starting a new thread. Is this the best way out or am I missing something obvious?

    Read the article

  • .NET port with Java's Map, Set, HashMap

    - by Nikos Baxevanis
    I am porting Java code in .NET and I am stuck in the following lines that (behave unexpectedly in .NET). Java: Map<Set<State>, Set<State>> sets = new HashMap<Set<State>, Set<State>>(); Set<State> p = new HashSet<State>(); if (!sets.containsKey(p)) { ... } The equivalent .NET code could possibly be: IDictionary<HashSet<State>, HashSet<State>> sets = new Dictionary<HashSet<State>, HashSet<State>>(); HashSet<State> p = new HashSet<State>(); if (!sets.containsKey(p)) { /* (Add to a list). Always get here in .NET (??) */ } However the code comparison fails, the program think that "sets" never contain Key "p" and eventually results in OutOfMemoryException. Perhaps I am missing something, object equality and identity might be different between Java and .NET. I tried implementing IComparable and IEquatable in class State but the results were the same. Edit: What the code does is: If the sets does not contain key "p" (which is a HashSet) it is going to add "p" at the end of a LinkedList. The State class (Java) is a simple class defined as: public class State implements Comparable<State> { boolean accept; Set<Transition> transitions; int number; int id; static int next_id; public State() { resetTransitions(); id = next_id++; } // ... public int compareTo(State s) { return s.id - id; } public boolean equals(Object obj) { return super.equals(obj); } public int hashCode() { return super.hashCode(); }

    Read the article

  • Bizzare Java invalid Assignment Operator Error

    - by Kay
    public class MaxHeap<T extends Comparable<T>> implements Heap<T>{ private T[] heap; private int lastIndex; private static final int defaultInitialCapacity = 25; public void add(T newItem) throws HeapException{ if (lastIndex < Max_Heap){ heap[lastIndex] = newItem; int place = lastIndex; int parent = (place – 1)/2; //ERROR HERE********** while ( (parent >=0) && (heap[place].compareTo(heap[parent])>0)){ T temp = heap[place]; heap[place] = heap[parent]; heap[parent] = temp; place = parent; parent = (place-1)/2; }else { throw new HeapException(“HeapException: Heap full”); } } } Eclipse complains that there is a: "Syntax error on token "Invalid Character", invalid AssignmentOperator" With the red line beneath the '(place-1)' There shouldn't be an error at all since it's just straight-forward arithmetic. Or is it not that simple?

    Read the article

  • How do I add an object to a binary tree based on the value of a member variable?

    - by Max
    How can I get a specific value from an object? I'm trying to get a value of an instance for eg. ListOfPpl newListOfPpl = new ListOfPpl(id, name, age); Object item = newListOfPpl; How can I get a value of name from an Object item?? Even if it is easy or does not interest you can anyone help me?? Edited: I was trying to build a binary tree contains the node of ListOfPpl, and need to sort it in the lexicographic. Here's my code for insertion on the node. Any clue?? public void insert(Object item){ Node current = root; Node follow = null; if(!isEmpty()){ root = new Node(item, null, null); return; }boolean left = false, right = false; while(current != null){ follow = current; left = false; right = false; //I need to compare and sort it if(item.compareTo(current.getFighter()) < 0){ current = current.getLeft(); left = true; }else { current = current.getRight(); right = true; } }if(left) follow.setLeft(new Node(item, null, null)); else follow.setRight(new Node(item, null, null)); }

    Read the article

  • How to update a row in Android database

    - by Sajan
    Hi all I want to update a row on clicking on update button,but its doesn't work. I have used following code. public void btnUpdate(View v) { handeler.updateData(updateName.getText().toString(), updatePhone .getText().toString(), updateEmail.getText().toString(),id); } public void updateData(String name, String phone, String email, String id) { ContentValues values = new ContentValues(); values.put(COLUMN_FIRST, name); values.put(COLUMN_SECOND, phone); values.put(COLUMN_THIRD, email); database.update(TABLE_NAME, values, id, null); } public void search() { Cursor cursor = handeler.getData(); if (cursor.moveToFirst()) { String phoneNo; phoneNo = updateByPhone.getText().toString(); do { String s1 = cursor.getString(2); if (phoneNo.compareTo(s1) == 0) { id = cursor.getString(0); updateName.setText(cursor.getString(1)); updateEmail.setText(cursor.getString(3)); updatePhone.setText(cursor.getString(2)); } } while (cursor.moveToNext()); } } So if any know please suggest me how to solve it. Thanks

    Read the article

  • 2 bucks for !! java basic question

    - by Max
    How can I get a specific value from an object? I'm trying to get a value of an instance for eg. ListOfPpl newListOfPpl = new ListOfPpl(id, name, age); Object item = newListOfPpl; How can I get a value of name from an Object item?? Even if it is easy or does not interest you can anyone help me?? Edited: I was trying to build a binary tree contains the node of ListOfPpl, and need to sort it in the lexicographic. Here's my code for insertion on the node. Any clue?? public void insert(Object item){ Node current = root; Node follow = null; if(!isEmpty()){ root = new Node(item, null, null); return; }boolean left = false, right = false; while(current != null){ follow = current; left = false; right = false; //I need to compare and sort it if(item.compareTo(current.getFighter()) < 0){ current = current.getLeft(); left = true; }else { current = current.getRight(); right = true; } }if(left) follow.setLeft(new Node(item, null, null)); else follow.setRight(new Node(item, null, null)); }

    Read the article

  • Manipulating existing XDocument (fails)

    - by Daemonfire3002nd
    Hi there, I got the following Code snippet from my Silverlight Application: var messages = from message in XcurrentMsg.Descendants("message") where DateTime.Parse(message.Attribute("timestamp").Value).CompareTo(DateTime.Parse(MessageCache.Last_Cached())) > 0 select new { ip = message.Attribute("ip").Value, timestamp = message.Attribute("timestamp").Value, text = message.Value, }; if (messages == null) throw new SystemException("No new messages recorded. Application tried to access non existing resources!"); foreach (var message in messages) { XElement temporaryElement = new XElement("message", message.text.ToString(), new XAttribute("ip", message.ip.ToString()), new XAttribute("timestamp", message.timestamp.ToString())); XcurrentMsg.Element("root").Element("messages").Add(temporaryElement); AddMessage(BuildMessage(message.ip, message.timestamp, message.text)); msgCount++; } MessageCache.CacheXML(XcurrentMsg); MessageCache.Refresh(); XcurrentMsg is a XDocument fetched from my server containing messages: Structure <root> <messages> <message ip="" timestamp=""> Text </message> </messages> </root> I want to get all "message" newer than the last time I cached the XcurrentMsg. This works fine as long as I cut out the "XElement temporaryElement" and the "XcurrentMsg.Element...." and simply use the currentMsg string as output. But I want to have "new messages" being saved in my XcurrentMsg / Cache. Now if I do not cut this part out, my Application gets awesome crazy. I think it writes infinite elements to the XcurrentMsg without stopping. I can not figure out what's the problem. regards,

    Read the article

  • Sort List <Rectangle>

    - by user1649498
    How do I sort a rectangle list by their area? Been looking into IComparable at msdn library, but can't figure it out... I wrote this: SortedL= new List<Rectangle>(); int count1 = 0; int count3 = redovi; while (count1 < count3) { int count2 = 0; while (count2 < count3) { int x = Oblici[count1].Width; int y = Oblici[count1].Height; int z = Oblici[count2].Width; int w = Oblici[count2].Height; int area1 = x * y; int area2 = z * w; int a = area1.CompareTo(area2); if (a < 0) { count1 = count2; if (count2 < (count3 - 1)) { count2++; } else break; } else if (a == 0) { if (count2 < (count3 - 1)) { count2++; } else break; } else if (a > 0) { if (count2 < count3 - 1) { count2++; } else break; } } SortedL.Add(Oblici[count1]); Oblici.RemoveAt(count1); count3 = (count3 - 1);}} And it works, but it's pretty ugly, and I know there is an easier way...

    Read the article

  • Android getSelectedItem, how to use?

    - by user1881184
    Im trying use the spinner control result in order to point it to another screen that would be on the app. For example in the spinner control if the user chose chevy it would then take you to another screen which is coded in chevy.xml and Chevy.class. This is what i have thus far and need some help, as our book only used getSelectedItem and the example was only for an output statement. Please help. import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Spinner; public class Mainpage extends Activity implements OnItemSelectedListener { String carChoice, chevy, ford, dodge, toyota; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /* carChoice = group.getSelectedItem().toString(); } if (carChoice.compareTo(chevy)==0) { startActivity(new Intent(Mainpage.this, Chevy.class)); */ } public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { final Spinner group = (Spinner) findViewById(R.id.carGroup); group.setOnItemSelectedListener(this); // TODO Auto-generated method stub String selected = group.getItemAtPosition(1).toString(); } public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }

    Read the article

  • Insertion into BST without header Node JAVA

    - by Petiatil
    I am working on a recursive insertion method for a BST. This function is suppose to be a recursive helper method and is in a private class called Node. The Node class is in a class called BinarySearchTree which contains an instance variable for the root. When I am trying to insert an element, I get a NullPointerException at : this.left = insert(((Node)left).element); I am unsure about why this occurs. If I understand correctly, in a BST, I am suppose to insert the item at the last spot on the path transversed. Any help is appreciated! private class Node implements BinaryNode<E> { E item; BinaryNode<E> left, right; public BinaryNode<E> insert(E item) { int compare = item.compareTo(((Node)root).item); if(root == null) { root = new Node(); ((Node)root).item = item; } else if(compare < 0) { this.left = insert(((Node)left).item); } else if(compare > 0) { this.right = insert(((Node)right).item); } return root; } }

    Read the article

  • Using a Predicate as a key to a Dictionary

    - by Tom Hines
    I really love Linq and Lambda Expressions in C#.  I also love certain community forums and programming websites like DaniWeb. A user on DaniWeb posted a question about comparing the results of a game that is like poker (5-card stud), but is played with dice. The question stemmed around determining what was the winning hand.  I looked at the question and issued some comments and suggestions toward a potential answer, but I thought it was a neat homework exercise. [A little explanation] I eventually realized not only could I compare the results of the hands (by name) with a certain construct – I could also compare the values of the individual dice with the same construct. That piece of code eventually became a Dictionary with the KEY as a Predicate<int> and the Value a Func<T> that returns a string from the another structure that contains the mapping of an ENUM to a string.  In one instance, that string is the name of the hand and in another instance, it is a string (CSV) representation of of the digits in the hand. An added benefit is that the digits re returned in the order they would be for a proper poker hand.  For instance the hand 1,2,5,3,1 would be returned as ONE_PAIR (1,1,5,3,2). [Getting to the point] 1: using System; 2: using System.Collections.Generic; 3:   4: namespace DicePoker 5: { 6: using KVP_E2S = KeyValuePair<CDicePoker.E_DICE_POKER_HAND_VAL, string>; 7: public partial class CDicePoker 8: { 9: /// <summary> 10: /// Magical construction to determine the winner of given hand Key/Value. 11: /// </summary> 12: private static Dictionary<Predicate<int>, Func<List<KVP_E2S>, string>> 13: map_prd2fn = new Dictionary<Predicate<int>, Func<List<KVP_E2S>, string>> 14: { 15: {new Predicate<int>(i => i.Equals(0)), PlayerTie},//first tie 16:   17: {new Predicate<int>(i => i > 0), 18: (m => string.Format("Player One wins\n1={0}({1})\n2={2}({3})", 19: m[0].Key, m[0].Value, m[1].Key, m[1].Value))}, 20:   21: {new Predicate<int>(i => i < 0), 22: (m => string.Format("Player Two wins\n2={2}({3})\n1={0}({1})", 23: m[0].Key, m[0].Value, m[1].Key, m[1].Value))}, 24:   25: {new Predicate<int>(i => i.Equals(0)), 26: (m => string.Format("Tie({0}) \n1={1}\n2={2}", 27: m[0].Key, m[0].Value, m[1].Value))} 28: }; 29: } 30: } When this is called, the code calls the Invoke method of the predicate to return a bool.  The first on matching true will have its value invoked. 1: private static Func<DICE_HAND, E_DICE_POKER_HAND_VAL> GetHandEval = dh => 2: map_dph2fn[map_dph2fn.Keys.Where(enm2fn => enm2fn(dh)).First()]; After coming up with this process, I realized (with a little modification) it could be called to evaluate the individual values in the dice hand in the event of a tie. 1: private static Func<List<KVP_E2S>, string> PlayerTie = lst_kvp => 2: map_prd2fn.Skip(1) 3: .Where(x => x.Key.Invoke(RenderDigits(dhPlayerOne).CompareTo(RenderDigits(dhPlayerTwo)))) 4: .Select(s => s.Value) 5: .First().Invoke(lst_kvp); After that, I realized I could now create a program completely without “if” statements or “for” loops! 1: static void Main(string[] args) 2: { 3: Dictionary<Predicate<int>, Action<Action<string>>> main = new Dictionary<Predicate<int>, Action<Action<string>>> 4: { 5: {(i => i.Equals(0)), PlayGame}, 6: {(i => true), Usage} 7: }; 8:   9: main[main.Keys.Where(m => m.Invoke(args.Length)).First()].Invoke(Display); 10: } …and there you have it. :) ZIPPED Project

    Read the article

  • Sorting Android ListView

    - by aeoth
    I'm only starting with Android dev, and while the Milestone is a nice device Java is not my natural language and I'm struggling with both the Google docs on Android SDK, Eclipse and Java itself. Anyway... I'm writing a microblog client for Android to go along with my Windows client (MahTweets). At the moment I've got Tweets coming and going without fail, the problem is with the UI. The initial call will order items correctly (as in highest to lowest) 3 2 1 When a refresh is made 3 2 1 6 5 4 After the tweets are processed, I'm calling adapter.notifyDataSetChanged(); Initially I thought that getItem() on the Adapter needed to be sorted (and the code below is what I ended up with), but I'm still not having any luck. public class TweetAdapter extends BaseAdapter { private List<IStatusUpdate> elements; private Context c; public TweetAdapter(Context c, List<IStatusUpdate> Tweets) { this.elements = Tweets; this.c = c; } public int getCount() { return elements.size(); } public Object getItem(int position) { Collections.sort(elements, new IStatusUpdateComparator()); return elements.get(position); } public long getItemId(int id) { return id; } public void Remove(int id) { notifyDataSetChanged(); } public View getView(int position, View convertView, ViewGroup parent) { RelativeLayout rowLayout; IStatusUpdate t = elements.get(position); rowLayout = t.GetParent().GetUI(t, parent, c); return rowLayout; } class IStatusUpdateComparator implements Comparator { public int compare(Object obj1, Object obj2) { IStatusUpdate update1 = (IStatusUpdate)obj1; IStatusUpdate update2 = (IStatusUpdate)obj2; int result = update1.getID().compareTo(update2.getID()); if (result == -1) return 1; else if (result == 1) return 0; return result; } } } Is there a better way to go about sorting ListViews in Android, while still being able to use the LayoutInflater? (rowLayout = t.GetParent().GetUI(t, parent, c) expands the UI to the specific view which the microblog implementation can provide)

    Read the article

  • Page expired issue with back button and wicket SortableDataProvider and DataTable

    - by David
    Hi, I've got an issue with SortableDataProvider and DataTable in wicket. I've defined my DataTable as such: IColumn<Column>[] columns = new IColumn[9]; //column values are mapped to the private attributes listed in ColumnImpl.java columns[0] = new PropertyColumn(new Model("#"), "columnPosition", "columnPosition"); columns[1] = new PropertyColumn(new Model("Description"), "description"); columns[2] = new PropertyColumn(new Model("Type"), "dataType", "dataType"); Adding it to the table: DataTable<Column> dataTable = new DataTable<Column>("columnsTable", columns, provider, maxRowsPerPage) { @Override protected Item<Column> newRowItem(String id, int index, IModel<Column> model) { return new OddEvenItem<Column>(id, index, model); } }; My data provider: public class ColumnSortableDataProvider extends SortableDataProvider<Column> { private static final long serialVersionUID = 1L; private List list = null; public ColumnSortableDataProvider(Table table, String sortProperty) { this.list = Arrays.asList(table.getColumns().toArray(new Column[0])); setSort(sortProperty, true); } public ColumnSortableDataProvider(List list, String sortProperty) { this.list = list; setSort(sortProperty, true); } @Override public Iterator iterator(int first, int count) { /* first - first row of data count - minimum number of elements to retrieve So this method returns an iterator capable of iterating over {first, first+count} items */ Iterator iterator = null; try { if(getSort() != null) { Collections.sort(list, new Comparator() { private static final long serialVersionUID = 1L; @Override public int compare(Column c1, Column c2) { int result=1; PropertyModel<Comparable> model1= new PropertyModel<Comparable>(c1, getSort().getProperty()); PropertyModel<Comparable> model2= new PropertyModel<Comparable>(c2, getSort().getProperty()); if(model1.getObject() == null && model2.getObject() == null) result = 0; else if(model1.getObject() == null) result = 1; else if(model2.getObject() == null) result = -1; else result = ((Comparable)model1.getObject()).compareTo(model2.getObject()); result = getSort().isAscending() ? result : -result; return result; } }); } if (list.size() (first+count)) iterator = list.subList(first, first+count).iterator(); else iterator = list.iterator(); } catch (Exception e) { e.printStackTrace(); } return iterator; } The problem is the following: - I click a column header to sort by that column. - I navigate to a different page - I click Back (or Forward if I do the opposite scenario) - Page has expired. It'd be nice to generate the page using PageParameters but I somehow need to intercept the sort event to do so. Any pointers would be greatly appreciated. Thanks a ton!! David

    Read the article

  • cannot evaluate expression because a native frame is on top of the call stack and system.accessviolationexception

    - by Joseph
    I have this code using c#. public partial class MainForm : Form { private CvCapture VideoCapture; private IplImage frame; private IplImage imgMain; public MainForm() { InitializeComponent(); } private void btnVideo_Click(object sender, EventArgs e) { double vidWidth, vidHeight; try { VideoCapture = highgui.CvCreateCameraCapture(0); } catch (Exception except) { MessageBox.Show(except.Message); } if (btnVideo.Text.CompareTo("Start Video") == 0) { if (VideoCapture.ptr == IntPtr.Zero) { MessageBox.Show("badtrip ah!!!"); return; } btnVideo.Text = "Stop Video"; highgui.CvSetCaptureProperty(ref VideoCapture, highgui.CV_CAP_PROP_FRAME_WIDTH, 640); highgui.CvSetCaptureProperty(ref VideoCapture, highgui.CV_CAP_PROP_FRAME_HEIGHT, 480); highgui.CvQueryFrame(ref VideoCapture); vidWidth = highgui.cvGetCaptureProperty(VideoCapture, highgui.CV_CAP_PROP_FRAME_WIDTH); vidHeight = highgui.cvGetCaptureProperty(VideoCapture, highgui.CV_CAP_PROP_FRAME_HEIGHT); picBoxMain.Width = (int)vidWidth; picBoxMain.Height = (int)vidHeight; timerGrab.Enabled = true; timerGrab.Interval = 42; timerGrab.Start(); } else { btnVideo.Text = "Start Video"; timerGrab.Enabled = false; if (VideoCapture.ptr == IntPtr.Zero) { highgui.CvReleaseCapture(ref VideoCapture); VideoCapture.ptr = IntPtr.Zero; } } } private void timerGrab_Tick(object sender, EventArgs e) { try { frame = highgui.CvQueryFrame(ref VideoCapture); if (frame.ptr == IntPtr.Zero) { timerGrab.Stop(); MessageBox.Show("??"); return; } imgMain = cxcore.CvCreateImage(cxcore.CvGetSize(ref frame), 8, 3); picBoxMain.Image = highgui.ToBitmap(imgMain, false); cxcore.CvReleaseImage(ref imgMain); //cxcore.CvReleaseImage(ref frame); } catch (Exception excpt) { MessageBox.Show(excpt.Message); } } } The problem is after i break all and step through the debugger the program stops at a certain code. the code where it stops is here: frame = highgui.CvQueryFrame(ref VideoCapture); the error is that it says that cannot evaluate expression because a native frame is on top of the call stack. and then when i try to shift+F11 it. there is another error saying that system.accessviolationexception. the stack trace says that: at System.Runtime.InteropServices.Marshal.CopyToManaged(IntPtr source, Object destination, Int32 startIndex, Int32 length) at CxCore.IplImage.get_ImageDataDb()

    Read the article

  • Java "compare cannot be resolved to a type" error

    - by King Triumph
    I'm getting a strange error when attempting to use a comparator with a binary search on an array. The error states that "compareArtist cannot be resolved to a type" and is thrown by Eclipse on this code: Comparator<Song> compare = new Song.compareArtist(); I've done some searching and found references to a possible bug with Eclipse, although I have tried the code on a different computer and the error persists. I've also found similar issues regarding the capitalization of the compare method, in this case compareArtist. I've seen examples where the first word in the method name is capitalized, although it was my understanding that method names are traditionally started with a lower case letter. I have experimented with changing the capitalization but nothing has changed. I have also found references to this error if the class doesn't import the correct package. I have imported java.util in both classes in question, which to my knowledge allows the use of the Comparator. I've experimented with writing the compareArtist method within the class that has the binary search call as well as in the "Song" class, which according to my homework assignment is where it should be. I've changed the constructor accordingly and the issue persists. Lastly, I've attempted to override the Comparator compare method by implementing Comparator in the Song class and creating my own method called "compare". This returns the same error. I've only moved to calling the comparator method something different than "compare" after finding several examples that do the same. Here is the relevant code for the class that calls the binary search that uses the comparator. This code also has a local version of the compareArtist method. While it is not being called currently, the code for this method is the same as the in the class Song, where I am trying to call it from. Thanks for any advice and insight. import java.io.*; import java.util.*; public class SearchByArtistPrefix { private Song[] songs; // keep a direct reference to the song array private Song[] searchResults; // holds the results of the search private ArrayList<Song> searchList = new ArrayList<Song>(); // hold results of search while being populated. Converted to searchResults array. public SearchByArtistPrefix(SongCollection sc) { songs = sc.getAllSongs(); } public int compareArtist (Song firstSong, Song secondSong) { return firstSong.getArtist().compareTo(secondSong.getArtist()); } public Song[] search(String artistPrefix) { String artistInput = artistPrefix; int searchLength = artistInput.length(); Song searchSong = new Song(artistInput, "", ""); Comparator<Song> compare = new Song.compareArtist(); int search = Arrays.binarySearch(songs, searchSong, compare);

    Read the article

  • Broadcast receiver, check status, turning off connection with F8

    - by yoann
    I am using eclipse with android sdk 3.2 I have some problems to make my broadcast receiver working when the connection is lost. first I have checked the type of network to make sure I understand well : ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); boolean is3g = manager.getNetworkInfo( ConnectivityManager.TYPE_MOBILE) .isConnectedOrConnecting(); boolean isWifi = manager.getNetworkInfo( ConnectivityManager.TYPE_WIFI) .isConnectedOrConnecting(); NetworkInfo info = manager.getActiveNetworkInfo(); if (info != null) Toast.makeText(getApplicationContext(), info.getTypeName(), Toast.LENGTH_LONG).show(); else Toast.makeText(getApplicationContext(), "Pas de connexion", Toast.LENGTH_LONG).show(); if (!is3g) Log.i("Network Listener", "DISCONNECTED"); else Log.i("Network Listener", "CONNECTED"); == this is a mobile network, I'm connected Then I press F8 or I make : telnet localhost 5554 gsm data off to stop the connection Here is my dynamic broadcast receiver in an activity : public class ActivityA extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.query); this.registerReceiver(this.networkStateReceiver, new IntentFilter( ConnectivityManager.CONNECTIVITY_ACTION)); } BroadcastReceiver networkStateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { ConnectivityManager connMgr = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); //i have tried several things : State networkState = networkInfo.getState(); // if (networkState.compareTo(State.DISCONNECTED) == 0) ... if (networkInfo != null && networkInfo.isConnected()) { Toast.makeText(getApplicationContext(), "CONNECTED", Toast.LENGTH_LONG).show(); Log.i("Network Listener", "Connected"); } else { Toast.makeText(getApplicationContext(), "DISCONNECTED", Toast.LENGTH_LONG).show(); Log.i("Network Listener", "Network Type Changed"); Intent offline = new Intent(AccountInfoActivity.this, OfflineWorkService.class); startService(offline); } }; My manifest : <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> The problem is : when the activityA is launched, my broadcast receive something and it displays "Connected"(Log) and my toast. When I turn off the connection manually, nothing happend. My service is not started, log message are not displayed, only toast messages work ... And even better, when I turn on the connection again (by pressing F8), I test again the type of connection, Toast messages are shown but this time Log messages don't work. Problems happend when I press F8. Anyway, I think I miss something with broadcast receivers, it's not totally clear. Please help me.

    Read the article

< Previous Page | 3 4 5 6 7 8  | Next Page >