Search Results

Search found 3382 results on 136 pages for 'michael j gray'.

Page 10/136 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • Android HttpsURLConnection and JSON for new GCM

    - by Ryan Gray
    I'm overhauling certain parts of my app to use the new GCM service to replace C2DM. I simply want to create the JSON request from a Java program for testing and then read the response. As of right now I can't find ANY formatting issues with my JSON request and the google server always return code 400, which indicates a problem with my JSON. http://developer.android.com/guide/google/gcm/gcm.html#server JSONObject obj = new JSONObject(); obj.put("collapse_key", "collapse key"); JSONObject data = new JSONObject(); data.put("info1", "info_1"); data.put("info2", "info 2"); data.put("info3", "info_3"); obj.put("data", data); JSONArray ids = new JSONArray(); ids.add(REG_ID); obj.put("registration_ids", ids); System.out.println(obj.toJSONString()); I print my request to the eclipse console to check it's formatting byte[] postData = obj.toJSONString().getBytes(); try{ URL url = new URL("https://android.googleapis.com/gcm/send"); HttpsURLConnection.setDefaultHostnameVerifier(new JServerHostnameVerifier()); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Authorization", "key=" + API_KEY); System.out.println(conn.toString()); OutputStream out = conn.getOutputStream(); // exception thrown right here. no InputStream to get InputStream in = conn.getInputStream(); byte[] response = null; out.write(postData); out.close(); in.read(response); JSONParser parser = new JSONParser(); String temp = new String(response); JSONObject temp1 = (JSONObject) parser.parse(temp); System.out.println(temp1.toJSONString()); int responseCode = conn.getResponseCode(); System.out.println(responseCode + ""); } catch(Exception e){ System.out.println("Exception thrown\n"+ e.getMessage()); } } I'm sure my API key is correct as that would result in error 401, so says the google documentation. This is my first time doing JSON but it's easy to understand because of its simplicity. Anyone have any ideas on why I always receive code 400? update: I've tested the google server example classes provided with gcm so the problem MUST be with my code.

    Read the article

  • Python — How can I find the square matrix of a lower triangular numpy matrix? (with a symmetrical upper triangle)

    - by Dana Gray
    I generated a lower triangular matrix, and I want to complete the matrix using the values in the lower triangular matrix to form a square matrix, symmetrical around the diagonal zeros. lower_triangle = numpy.array([ [0,0,0,0], [1,0,0,0], [2,3,0,0], [4,5,6,0]]) I want to generate the following complete matrix, maintaining the zero diagonal: complete_matrix = numpy.array([ [0, 1, 2, 4], [1, 0, 3, 5], [2, 3, 0, 6], [4, 5, 6, 0]]) Thanks.

    Read the article

  • memory usage in C# (.NET) app is very high, until I call System.GC.Collect()

    - by Chris Gray
    I've written an app that spins a few threads each of which read several MB of memory. Each thread then connects to the Internet and uploads the data. this occurs thousands of times and each upload takes some time I'm seeing a situation where (verified with windbg/sos and !dumpheap) that the Byte[] are not getting collected automatically, causing 100/150MB of memory to be reported in task manager if I call System.GC.Collect() i'm seeing a huge drop in memory, a drop of over 100MB I dont like calling System.GC.Collect() and my PC has tons of free memory. however if anyone looks at TaskManager they're going to be concerned, thinking my app is leaking horribly. tips?

    Read the article

  • Please help with iPhone Memory & Images, memory usage crashing app

    - by Andrew Gray
    I have an issue with memory usage relating to images and I've searched the docs and watched the videos from cs193p and the iphone dev site on memory mgmt and performance. I've searched online and posted on forums, but I still can't figure it out. The app uses core data and simply lets the user associate text with a picture and stores the list of items in a table view that lets you add and delete items. Clicking on a row shows the image and related text. that's it. Everything runs fine on the simulator and on the device as well. I ran the analyzer and it looked good, so i then starting looking at performance. I ran leaks and everything looked good. My issue is when running Object Allocations as every time i select a row and the view with the image is shown, the live bytes jumps up a few MB and never goes down and my app eventually crashes due to memory usage. Sorting the live bytes column, i see 2 2.72MB mallocs (5.45Mb total), 14 CFDatas (3.58MB total), 1 2.74MB malloc and everything else is real small. the problem is all the related info in instruments is really technical and all the problem solving examples i've seen are just missing a release and nothing complicated. Instruments shows Core Data as the responsible library for all but one (libsqlite3.dylib the other) with [NSSQLCore _prepareResultsFromResultSet:usingFetchPlan:withMatchingRows:] as the caller for all but one (fetchResultSetReallocCurrentRow the other) and im just not sure how to track down what the problem is. i've looked at the stack traces and opened the last instance of my code and found 2 culprits (below). I havent been able to get any responses at all on this, so if anyone has any tips or pointers, I'd really appreciate it!!!! //this is from view controller that shows the title and image - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; self.title = item.title; self.itemTitleTextField.text = item.title; if ([item.notes length] == 0) { self.itemNotesTextView.hidden = YES; } else { self.itemNotesTextView.text = item.notes; } //this is the line instruments points to UIImage *image = item.photo.image; itemPhoto.image = image; } - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete the managed object for the given index path NSManagedObjectContext *context = [fetchedResultsController managedObjectContext]; [context deleteObject:[fetchedResultsController objectAtIndexPath:indexPath]]; // Save the context. NSError *error = nil; if (![context save:&error]) //this is the line instruments points to { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); exit(-1); } } }

    Read the article

  • ServicedComponent not being disposed in finaliser

    - by David Gray Wright
    Questions needing answers : Does the finalizer of the client side ServicedComponent call ServicedComponent.DisposeObject or Dispose? How should destruction (release of memory) occur in the com server in realtion to its usage in the client? Basically - we are reaching a 2 gig limit on process size (memory) of the COM server as memory is not being released - is the solution to call explicitly call Dispose or use the using statement in the client?

    Read the article

  • using Visual Studio 2008 to test an x64 .NET binary

    - by Chris Gray
    I have an x64 managed C++ class that needs to be tested using Visual Studio 2008. This class links to a x64 unmanaged lib I'm not able to run my my tests because vstesthost.exe (the exe Visual Studio hosts my test) is x86 and not x64. Ideas? the error generated is rror: System.BadImageFormatException: Could not load file or assembly ... or one of its dependencies. An attempt was made to load

    Read the article

  • Why is the compiler caching my "random" and NULLED variables?

    - by alex gray
    I am confounded by the fact that even using different programs (on the same machine) to run /compile, and after nilling the vaues (before and after) the function.. that NO MATTER WHAT.. I'll keep getting the SAME "random" numbers… each and every time I run it. I swear this is NOT how it's supposed to work.. I'm going to illustrate as simply as is possible… #import <Foundation/Foundation.h> int main(int argc, char *argv[]) { int rPrimitive = 0; rPrimitive = 1 + rand() % 50; NSNumber *rObject = nil; rObject = [NSNumber numberWithInt:rand() % 10]; NSLog(@"%i %@", rPrimitive, rObject); rPrimitive = 0; rObject = nil; NSLog(@"%i %@", rPrimitive, rObject); return 0; } Run it in TextMate: i686-apple-darwin11-llvm-gcc-4.2 8 9 0 (null) Run it in CodeRunner: i686-apple-darwin11-llvm-gcc-4.2 8 9 0 (null) Run it a million times, if you'd like. You can gues what it will always be. Why does this happen? Why oh why is this "how it is"?

    Read the article

  • MySQL specifying exact order with WHERE `id` IN (...)

    - by Gray Fox
    Is there an easy way to order MySQL results respectively by WHERE id IN (...) clause? Example: SELECT * FROM articles WHERE articles.id IN (4, 2, 5, 9, 3) to return Article with id = 4 Article with id = 2 Article with id = 5 Article with id = 9 Article with id = 3 and also SELECT * FROM articles WHERE articles.id IN (4, 2, 5, 9, 3) LIMIT 2,2 to return Article with id = 5 Article with id = 9

    Read the article

  • How to pass a value between Silverlight pages for WP7?

    - by Sebastian Gray
    I've got a MainPage.xaml page a Detail.xaml page. I've passed variables to the Detail.xaml from MainPage.xaml by using a static variable and referencing it in Detail.xaml (the detail page is acting like a dialog). However once I've updated the content of another object, I want to call a method in MainPage.xaml to refresh the content of that page using the updated object from the Detail.xaml page. I assume I am not using the correct paradigm for this and should probably be using MVVM or something but I'm not familiar with the implementation and was hoping there was a simple way to do this?

    Read the article

  • Create a variable which is named depending on an ID number?

    - by gray
    Is there any way to create a variable, and add an ID to the end of the actual variable name? I have a variable called 'gauge', used to create a new Gauge object: var gauge = new Gauge(target).setOptions(opts); I want to add an ID to the variable, so something like: var gauge+id = new Gauge(target).setOptions(opts); It's because I'm creating a number of these objects, and have a specific ID already for each one, which I want to attach to the gauge object if possible? All my code for this function is below, if it gives you a better idea of what i need to do: function go(id, votes) { var val = $('#votes_'+id).text(); var target = document.getElementById('foo_'+id); // your canvas element var gauge = new Gauge(target).setOptions(opts); // create sexy gauge! gauge.maxValue = 100; // set max gauge value gauge.animationSpeed = 20; // set animation speed (32 is default value) var a=votes+0.5; gauge.set(val); // set actual value } My main problem arises on the last line. It says gauge.set(val), and it only sets the last object, ignoring all the other ones...

    Read the article

  • C#/.NET Little Wonders: The Concurrent Collections (1 of 3)

    - by James Michael Hare
    Once again we consider some of the lesser known classes and keywords of C#.  In the next few weeks, we will discuss the concurrent collections and how they have changed the face of concurrent programming. This week’s post will begin with a general introduction and discuss the ConcurrentStack<T> and ConcurrentQueue<T>.  Then in the following post we’ll discuss the ConcurrentDictionary<T> and ConcurrentBag<T>.  Finally, we shall close on the third post with a discussion of the BlockingCollection<T>. For more of the "Little Wonders" posts, see the index here. A brief history of collections In the beginning was the .NET 1.0 Framework.  And out of this framework emerged the System.Collections namespace, and it was good.  It contained all the basic things a growing programming language needs like the ArrayList and Hashtable collections.  The main problem, of course, with these original collections is that they held items of type object which means you had to be disciplined enough to use them correctly or you could end up with runtime errors if you got an object of a type you weren't expecting. Then came .NET 2.0 and generics and our world changed forever!  With generics the C# language finally got an equivalent of the very powerful C++ templates.  As such, the System.Collections.Generic was born and we got type-safe versions of all are favorite collections.  The List<T> succeeded the ArrayList and the Dictionary<TKey,TValue> succeeded the Hashtable and so on.  The new versions of the library were not only safer because they checked types at compile-time, in many cases they were more performant as well.  So much so that it's Microsoft's recommendation that the System.Collections original collections only be used for backwards compatibility. So we as developers came to know and love the generic collections and took them into our hearts and embraced them.  The problem is, thread safety in both the original collections and the generic collections can be problematic, for very different reasons. Now, if you are only doing single-threaded development you may not care – after all, no locking is required.  Even if you do have multiple threads, if a collection is “load-once, read-many” you don’t need to do anything to protect that container from multi-threaded access, as illustrated below: 1: public static class OrderTypeTranslator 2: { 3: // because this dictionary is loaded once before it is ever accessed, we don't need to synchronize 4: // multi-threaded read access 5: private static readonly Dictionary<string, char> _translator = new Dictionary<string, char> 6: { 7: {"New", 'N'}, 8: {"Update", 'U'}, 9: {"Cancel", 'X'} 10: }; 11:  12: // the only public interface into the dictionary is for reading, so inherently thread-safe 13: public static char? Translate(string orderType) 14: { 15: char charValue; 16: if (_translator.TryGetValue(orderType, out charValue)) 17: { 18: return charValue; 19: } 20:  21: return null; 22: } 23: } Unfortunately, most of our computer science problems cannot get by with just single-threaded applications or with multi-threading in a load-once manner.  Looking at  today's trends, it's clear to see that computers are not so much getting faster because of faster processor speeds -- we've nearly reached the limits we can push through with today's technologies -- but more because we're adding more cores to the boxes.  With this new hardware paradigm, it is even more important to use multi-threaded applications to take full advantage of parallel processing to achieve higher application speeds. So let's look at how to use collections in a thread-safe manner. Using historical collections in a concurrent fashion The early .NET collections (System.Collections) had a Synchronized() static method that could be used to wrap the early collections to make them completely thread-safe.  This paradigm was dropped in the generic collections (System.Collections.Generic) because having a synchronized wrapper resulted in atomic locks for all operations, which could prove overkill in many multithreading situations.  Thus the paradigm shifted to having the user of the collection specify their own locking, usually with an external object: 1: public class OrderAggregator 2: { 3: private static readonly Dictionary<string, List<Order>> _orders = new Dictionary<string, List<Order>>(); 4: private static readonly _orderLock = new object(); 5:  6: public void Add(string accountNumber, Order newOrder) 7: { 8: List<Order> ordersForAccount; 9:  10: // a complex operation like this should all be protected 11: lock (_orderLock) 12: { 13: if (!_orders.TryGetValue(accountNumber, out ordersForAccount)) 14: { 15: _orders.Add(accountNumber, ordersForAccount = new List<Order>()); 16: } 17:  18: ordersForAccount.Add(newOrder); 19: } 20: } 21: } Notice how we’re performing several operations on the dictionary under one lock.  With the Synchronized() static methods of the early collections, you wouldn’t be able to specify this level of locking (a more macro-level).  So in the generic collections, it was decided that if a user needed synchronization, they could implement their own locking scheme instead so that they could provide synchronization as needed. The need for better concurrent access to collections Here’s the problem: it’s relatively easy to write a collection that locks itself down completely for access, but anything more complex than that can be difficult and error-prone to write, and much less to make it perform efficiently!  For example, what if you have a Dictionary that has frequent reads but in-frequent updates?  Do you want to lock down the entire Dictionary for every access?  This would be overkill and would prevent concurrent reads.  In such cases you could use something like a ReaderWriterLockSlim which allows for multiple readers in a lock, and then once a writer grabs the lock it blocks all further readers until the writer is done (in a nutshell).  This is all very complex stuff to consider. Fortunately, this is where the Concurrent Collections come in.  The Parallel Computing Platform team at Microsoft went through great pains to determine how to make a set of concurrent collections that would have the best performance characteristics for general case multi-threaded use. Now, as in all things involving threading, you should always make sure you evaluate all your container options based on the particular usage scenario and the degree of parallelism you wish to acheive. This article should not be taken to understand that these collections are always supperior to the generic collections. Each fills a particular need for a particular situation. Understanding what each container is optimized for is key to the success of your application whether it be single-threaded or multi-threaded. General points to consider with the concurrent collections The MSDN points out that the concurrent collections all support the ICollection interface. However, since the collections are already synchronized, the IsSynchronized property always returns false, and SyncRoot always returns null.  Thus you should not attempt to use these properties for synchronization purposes. Note that since the concurrent collections also may have different operations than the traditional data structures you may be used to.  Now you may ask why they did this, but it was done out of necessity to keep operations safe and atomic.  For example, in order to do a Pop() on a stack you have to know the stack is non-empty, but between the time you check the stack’s IsEmpty property and then do the Pop() another thread may have come in and made the stack empty!  This is why some of the traditional operations have been changed to make them safe for concurrent use. In addition, some properties and methods in the concurrent collections achieve concurrency by creating a snapshot of the collection, which means that some operations that were traditionally O(1) may now be O(n) in the concurrent models.  I’ll try to point these out as we talk about each collection so you can be aware of any potential performance impacts.  Finally, all the concurrent containers are safe for enumeration even while being modified, but some of the containers support this in different ways (snapshot vs. dirty iteration).  Once again I’ll highlight how thread-safe enumeration works for each collection. ConcurrentStack<T>: The thread-safe LIFO container The ConcurrentStack<T> is the thread-safe counterpart to the System.Collections.Generic.Stack<T>, which as you may remember is your standard last-in-first-out container.  If you think of algorithms that favor stack usage (for example, depth-first searches of graphs and trees) then you can see how using a thread-safe stack would be of benefit. The ConcurrentStack<T> achieves thread-safe access by using System.Threading.Interlocked operations.  This means that the multi-threaded access to the stack requires no traditional locking and is very, very fast! For the most part, the ConcurrentStack<T> behaves like it’s Stack<T> counterpart with a few differences: Pop() was removed in favor of TryPop() Returns true if an item existed and was popped and false if empty. PushRange() and TryPopRange() were added Allows you to push multiple items and pop multiple items atomically. Count takes a snapshot of the stack and then counts the items. This means it is a O(n) operation, if you just want to check for an empty stack, call IsEmpty instead which is O(1). ToArray() and GetEnumerator() both also take snapshots. This means that iteration over a stack will give you a static view at the time of the call and will not reflect updates. Pushing on a ConcurrentStack<T> works just like you’d expect except for the aforementioned PushRange() method that was added to allow you to push a range of items concurrently. 1: var stack = new ConcurrentStack<string>(); 2:  3: // adding to stack is much the same as before 4: stack.Push("First"); 5:  6: // but you can also push multiple items in one atomic operation (no interleaves) 7: stack.PushRange(new [] { "Second", "Third", "Fourth" }); For looking at the top item of the stack (without removing it) the Peek() method has been removed in favor of a TryPeek().  This is because in order to do a peek the stack must be non-empty, but between the time you check for empty and the time you execute the peek the stack contents may have changed.  Thus the TryPeek() was created to be an atomic check for empty, and then peek if not empty: 1: // to look at top item of stack without removing it, can use TryPeek. 2: // Note that there is no Peek(), this is because you need to check for empty first. TryPeek does. 3: string item; 4: if (stack.TryPeek(out item)) 5: { 6: Console.WriteLine("Top item was " + item); 7: } 8: else 9: { 10: Console.WriteLine("Stack was empty."); 11: } Finally, to remove items from the stack, we have the TryPop() for single, and TryPopRange() for multiple items.  Just like the TryPeek(), these operations replace Pop() since we need to ensure atomically that the stack is non-empty before we pop from it: 1: // to remove items, use TryPop or TryPopRange to get multiple items atomically (no interleaves) 2: if (stack.TryPop(out item)) 3: { 4: Console.WriteLine("Popped " + item); 5: } 6:  7: // TryPopRange will only pop up to the number of spaces in the array, the actual number popped is returned. 8: var poppedItems = new string[2]; 9: int numPopped = stack.TryPopRange(poppedItems); 10:  11: foreach (var theItem in poppedItems.Take(numPopped)) 12: { 13: Console.WriteLine("Popped " + theItem); 14: } Finally, note that as stated before, GetEnumerator() and ToArray() gets a snapshot of the data at the time of the call.  That means if you are enumerating the stack you will get a snapshot of the stack at the time of the call.  This is illustrated below: 1: var stack = new ConcurrentStack<string>(); 2:  3: // adding to stack is much the same as before 4: stack.Push("First"); 5:  6: var results = stack.GetEnumerator(); 7:  8: // but you can also push multiple items in one atomic operation (no interleaves) 9: stack.PushRange(new [] { "Second", "Third", "Fourth" }); 10:  11: while(results.MoveNext()) 12: { 13: Console.WriteLine("Stack only has: " + results.Current); 14: } The only item that will be printed out in the above code is "First" because the snapshot was taken before the other items were added. This may sound like an issue, but it’s really for safety and is more correct.  You don’t want to enumerate a stack and have half a view of the stack before an update and half a view of the stack after an update, after all.  In addition, note that this is still thread-safe, whereas iterating through a non-concurrent collection while updating it in the old collections would cause an exception. ConcurrentQueue<T>: The thread-safe FIFO container The ConcurrentQueue<T> is the thread-safe counterpart of the System.Collections.Generic.Queue<T> class.  The concurrent queue uses an underlying list of small arrays and lock-free System.Threading.Interlocked operations on the head and tail arrays.  Once again, this allows us to do thread-safe operations without the need for heavy locks! The ConcurrentQueue<T> (like the ConcurrentStack<T>) has some departures from the non-concurrent counterpart.  Most notably: Dequeue() was removed in favor of TryDequeue(). Returns true if an item existed and was dequeued and false if empty. Count does not take a snapshot It subtracts the head and tail index to get the count.  This results overall in a O(1) complexity which is quite good.  It’s still recommended, however, that for empty checks you call IsEmpty instead of comparing Count to zero. ToArray() and GetEnumerator() both take snapshots. This means that iteration over a queue will give you a static view at the time of the call and will not reflect updates. The Enqueue() method on the ConcurrentQueue<T> works much the same as the generic Queue<T>: 1: var queue = new ConcurrentQueue<string>(); 2:  3: // adding to queue is much the same as before 4: queue.Enqueue("First"); 5: queue.Enqueue("Second"); 6: queue.Enqueue("Third"); For front item access, the TryPeek() method must be used to attempt to see the first item if the queue.  There is no Peek() method since, as you’ll remember, we can only peek on a non-empty queue, so we must have an atomic TryPeek() that checks for empty and then returns the first item if the queue is non-empty. 1: // to look at first item in queue without removing it, can use TryPeek. 2: // Note that there is no Peek(), this is because you need to check for empty first. TryPeek does. 3: string item; 4: if (queue.TryPeek(out item)) 5: { 6: Console.WriteLine("First item was " + item); 7: } 8: else 9: { 10: Console.WriteLine("Queue was empty."); 11: } Then, to remove items you use TryDequeue().  Once again this is for the same reason we have TryPeek() and not Peek(): 1: // to remove items, use TryDequeue. If queue is empty returns false. 2: if (queue.TryDequeue(out item)) 3: { 4: Console.WriteLine("Dequeued first item " + item); 5: } Just like the concurrent stack, the ConcurrentQueue<T> takes a snapshot when you call ToArray() or GetEnumerator() which means that subsequent updates to the queue will not be seen when you iterate over the results.  Thus once again the code below will only show the first item, since the other items were added after the snapshot. 1: var queue = new ConcurrentQueue<string>(); 2:  3: // adding to queue is much the same as before 4: queue.Enqueue("First"); 5:  6: var iterator = queue.GetEnumerator(); 7:  8: queue.Enqueue("Second"); 9: queue.Enqueue("Third"); 10:  11: // only shows First 12: while (iterator.MoveNext()) 13: { 14: Console.WriteLine("Dequeued item " + iterator.Current); 15: } Using collections concurrently You’ll notice in the examples above I stuck to using single-threaded examples so as to make them deterministic and the results obvious.  Of course, if we used these collections in a truly multi-threaded way the results would be less deterministic, but would still be thread-safe and with no locking on your part required! For example, say you have an order processor that takes an IEnumerable<Order> and handles each other in a multi-threaded fashion, then groups the responses together in a concurrent collection for aggregation.  This can be done easily with the TPL’s Parallel.ForEach(): 1: public static IEnumerable<OrderResult> ProcessOrders(IEnumerable<Order> orderList) 2: { 3: var proxy = new OrderProxy(); 4: var results = new ConcurrentQueue<OrderResult>(); 5:  6: // notice that we can process all these in parallel and put the results 7: // into our concurrent collection without needing any external locking! 8: Parallel.ForEach(orderList, 9: order => 10: { 11: var result = proxy.PlaceOrder(order); 12:  13: results.Enqueue(result); 14: }); 15:  16: return results; 17: } Summary Obviously, if you do not need multi-threaded safety, you don’t need to use these collections, but when you do need multi-threaded collections these are just the ticket! The plethora of features (I always think of the movie The Three Amigos when I say plethora) built into these containers and the amazing way they acheive thread-safe access in an efficient manner is wonderful to behold. Stay tuned next week where we’ll continue our discussion with the ConcurrentBag<T> and the ConcurrentDictionary<TKey,TValue>. For some excellent information on the performance of the concurrent collections and how they perform compared to a traditional brute-force locking strategy, see this wonderful whitepaper by the Microsoft Parallel Computing Platform team here.   Tweet Technorati Tags: C#,.NET,Concurrent Collections,Collections,Multi-Threading,Little Wonders,BlackRabbitCoder,James Michael Hare

    Read the article

  • C#/.NET Little Wonders: The ConcurrentDictionary

    - by James Michael Hare
    Once again we consider some of the lesser known classes and keywords of C#.  In this series of posts, we will discuss how the concurrent collections have been developed to help alleviate these multi-threading concerns.  Last week’s post began with a general introduction and discussed the ConcurrentStack<T> and ConcurrentQueue<T>.  Today's post discusses the ConcurrentDictionary<T> (originally I had intended to discuss ConcurrentBag this week as well, but ConcurrentDictionary had enough information to create a very full post on its own!).  Finally next week, we shall close with a discussion of the ConcurrentBag<T> and BlockingCollection<T>. For more of the "Little Wonders" posts, see the index here. Recap As you'll recall from the previous post, the original collections were object-based containers that accomplished synchronization through a Synchronized member.  While these were convenient because you didn't have to worry about writing your own synchronization logic, they were a bit too finely grained and if you needed to perform multiple operations under one lock, the automatic synchronization didn't buy much. With the advent of .NET 2.0, the original collections were succeeded by the generic collections which are fully type-safe, but eschew automatic synchronization.  This cuts both ways in that you have a lot more control as a developer over when and how fine-grained you want to synchronize, but on the other hand if you just want simple synchronization it creates more work. With .NET 4.0, we get the best of both worlds in generic collections.  A new breed of collections was born called the concurrent collections in the System.Collections.Concurrent namespace.  These amazing collections are fine-tuned to have best overall performance for situations requiring concurrent access.  They are not meant to replace the generic collections, but to simply be an alternative to creating your own locking mechanisms. Among those concurrent collections were the ConcurrentStack<T> and ConcurrentQueue<T> which provide classic LIFO and FIFO collections with a concurrent twist.  As we saw, some of the traditional methods that required calls to be made in a certain order (like checking for not IsEmpty before calling Pop()) were replaced in favor of an umbrella operation that combined both under one lock (like TryPop()). Now, let's take a look at the next in our series of concurrent collections!For some excellent information on the performance of the concurrent collections and how they perform compared to a traditional brute-force locking strategy, see this wonderful whitepaper by the Microsoft Parallel Computing Platform team here. ConcurrentDictionary – the fully thread-safe dictionary The ConcurrentDictionary<TKey,TValue> is the thread-safe counterpart to the generic Dictionary<TKey, TValue> collection.  Obviously, both are designed for quick – O(1) – lookups of data based on a key.  If you think of algorithms where you need lightning fast lookups of data and don’t care whether the data is maintained in any particular ordering or not, the unsorted dictionaries are generally the best way to go. Note: as a side note, there are sorted implementations of IDictionary, namely SortedDictionary and SortedList which are stored as an ordered tree and a ordered list respectively.  While these are not as fast as the non-sorted dictionaries – they are O(log2 n) – they are a great combination of both speed and ordering -- and still greatly outperform a linear search. Now, once again keep in mind that if all you need to do is load a collection once and then allow multi-threaded reading you do not need any locking.  Examples of this tend to be situations where you load a lookup or translation table once at program start, then keep it in memory for read-only reference.  In such cases locking is completely non-productive. However, most of the time when we need a concurrent dictionary we are interleaving both reads and updates.  This is where the ConcurrentDictionary really shines!  It achieves its thread-safety with no common lock to improve efficiency.  It actually uses a series of locks to provide concurrent updates, and has lockless reads!  This means that the ConcurrentDictionary gets even more efficient the higher the ratio of reads-to-writes you have. ConcurrentDictionary and Dictionary differences For the most part, the ConcurrentDictionary<TKey,TValue> behaves like it’s Dictionary<TKey,TValue> counterpart with a few differences.  Some notable examples of which are: Add() does not exist in the concurrent dictionary. This means you must use TryAdd(), AddOrUpdate(), or GetOrAdd().  It also means that you can’t use a collection initializer with the concurrent dictionary. TryAdd() replaced Add() to attempt atomic, safe adds. Because Add() only succeeds if the item doesn’t already exist, we need an atomic operation to check if the item exists, and if not add it while still under an atomic lock. TryUpdate() was added to attempt atomic, safe updates. If we want to update an item, we must make sure it exists first and that the original value is what we expected it to be.  If all these are true, we can update the item under one atomic step. TryRemove() was added to attempt atomic, safe removes. To safely attempt to remove a value we need to see if the key exists first, this checks for existence and removes under an atomic lock. AddOrUpdate() was added to attempt an thread-safe “upsert”. There are many times where you want to insert into a dictionary if the key doesn’t exist, or update the value if it does.  This allows you to make a thread-safe add-or-update. GetOrAdd() was added to attempt an thread-safe query/insert. Sometimes, you want to query for whether an item exists in the cache, and if it doesn’t insert a starting value for it.  This allows you to get the value if it exists and insert if not. Count, Keys, Values properties take a snapshot of the dictionary. Accessing these properties may interfere with add and update performance and should be used with caution. ToArray() returns a static snapshot of the dictionary. That is, the dictionary is locked, and then copied to an array as a O(n) operation.  GetEnumerator() is thread-safe and efficient, but allows dirty reads. Because reads require no locking, you can safely iterate over the contents of the dictionary.  The only downside is that, depending on timing, you may get dirty reads. Dirty reads during iteration The last point on GetEnumerator() bears some explanation.  Picture a scenario in which you call GetEnumerator() (or iterate using a foreach, etc.) and then, during that iteration the dictionary gets updated.  This may not sound like a big deal, but it can lead to inconsistent results if used incorrectly.  The problem is that items you already iterated over that are updated a split second after don’t show the update, but items that you iterate over that were updated a split second before do show the update.  Thus you may get a combination of items that are “stale” because you iterated before the update, and “fresh” because they were updated after GetEnumerator() but before the iteration reached them. Let’s illustrate with an example, let’s say you load up a concurrent dictionary like this: 1: // load up a dictionary. 2: var dictionary = new ConcurrentDictionary<string, int>(); 3:  4: dictionary["A"] = 1; 5: dictionary["B"] = 2; 6: dictionary["C"] = 3; 7: dictionary["D"] = 4; 8: dictionary["E"] = 5; 9: dictionary["F"] = 6; Then you have one task (using the wonderful TPL!) to iterate using dirty reads: 1: // attempt iteration in a separate thread 2: var iterationTask = new Task(() => 3: { 4: // iterates using a dirty read 5: foreach (var pair in dictionary) 6: { 7: Console.WriteLine(pair.Key + ":" + pair.Value); 8: } 9: }); And one task to attempt updates in a separate thread (probably): 1: // attempt updates in a separate thread 2: var updateTask = new Task(() => 3: { 4: // iterates, and updates the value by one 5: foreach (var pair in dictionary) 6: { 7: dictionary[pair.Key] = pair.Value + 1; 8: } 9: }); Now that we’ve done this, we can fire up both tasks and wait for them to complete: 1: // start both tasks 2: updateTask.Start(); 3: iterationTask.Start(); 4:  5: // wait for both to complete. 6: Task.WaitAll(updateTask, iterationTask); Now, if I you didn’t know about the dirty reads, you may have expected to see the iteration before the updates (such as A:1, B:2, C:3, D:4, E:5, F:6).  However, because the reads are dirty, we will quite possibly get a combination of some updated, some original.  My own run netted this result: 1: F:6 2: E:6 3: D:5 4: C:4 5: B:3 6: A:2 Note that, of course, iteration is not in order because ConcurrentDictionary, like Dictionary, is unordered.  Also note that both E and F show the value 6.  This is because the output task reached F before the update, but the updates for the rest of the items occurred before their output (probably because console output is very slow, comparatively). If we want to always guarantee that we will get a consistent snapshot to iterate over (that is, at the point we ask for it we see precisely what is in the dictionary and no subsequent updates during iteration), we should iterate over a call to ToArray() instead: 1: // attempt iteration in a separate thread 2: var iterationTask = new Task(() => 3: { 4: // iterates using a dirty read 5: foreach (var pair in dictionary.ToArray()) 6: { 7: Console.WriteLine(pair.Key + ":" + pair.Value); 8: } 9: }); The atomic Try…() methods As you can imagine TryAdd() and TryRemove() have few surprises.  Both first check the existence of the item to determine if it can be added or removed based on whether or not the key currently exists in the dictionary: 1: // try add attempts an add and returns false if it already exists 2: if (dictionary.TryAdd("G", 7)) 3: Console.WriteLine("G did not exist, now inserted with 7"); 4: else 5: Console.WriteLine("G already existed, insert failed."); TryRemove() also has the virtue of returning the value portion of the removed entry matching the given key: 1: // attempt to remove the value, if it exists it is removed and the original is returned 2: int removedValue; 3: if (dictionary.TryRemove("C", out removedValue)) 4: Console.WriteLine("Removed C and its value was " + removedValue); 5: else 6: Console.WriteLine("C did not exist, remove failed."); Now TryUpdate() is an interesting creature.  You might think from it’s name that TryUpdate() first checks for an item’s existence, and then updates if the item exists, otherwise it returns false.  Well, note quite... It turns out when you call TryUpdate() on a concurrent dictionary, you pass it not only the new value you want it to have, but also the value you expected it to have before the update.  If the item exists in the dictionary, and it has the value you expected, it will update it to the new value atomically and return true.  If the item is not in the dictionary or does not have the value you expected, it is not modified and false is returned. 1: // attempt to update the value, if it exists and if it has the expected original value 2: if (dictionary.TryUpdate("G", 42, 7)) 3: Console.WriteLine("G existed and was 7, now it's 42."); 4: else 5: Console.WriteLine("G either didn't exist, or wasn't 7."); The composite Add methods The ConcurrentDictionary also has composite add methods that can be used to perform updates and gets, with an add if the item is not existing at the time of the update or get. The first of these, AddOrUpdate(), allows you to add a new item to the dictionary if it doesn’t exist, or update the existing item if it does.  For example, let’s say you are creating a dictionary of counts of stock ticker symbols you’ve subscribed to from a market data feed: 1: public sealed class SubscriptionManager 2: { 3: private readonly ConcurrentDictionary<string, int> _subscriptions = new ConcurrentDictionary<string, int>(); 4:  5: // adds a new subscription, or increments the count of the existing one. 6: public void AddSubscription(string tickerKey) 7: { 8: // add a new subscription with count of 1, or update existing count by 1 if exists 9: var resultCount = _subscriptions.AddOrUpdate(tickerKey, 1, (symbol, count) => count + 1); 10:  11: // now check the result to see if we just incremented the count, or inserted first count 12: if (resultCount == 1) 13: { 14: // subscribe to symbol... 15: } 16: } 17: } Notice the update value factory Func delegate.  If the key does not exist in the dictionary, the add value is used (in this case 1 representing the first subscription for this symbol), but if the key already exists, it passes the key and current value to the update delegate which computes the new value to be stored in the dictionary.  The return result of this operation is the value used (in our case: 1 if added, existing value + 1 if updated). Likewise, the GetOrAdd() allows you to attempt to retrieve a value from the dictionary, and if the value does not currently exist in the dictionary it will insert a value.  This can be handy in cases where perhaps you wish to cache data, and thus you would query the cache to see if the item exists, and if it doesn’t you would put the item into the cache for the first time: 1: public sealed class PriceCache 2: { 3: private readonly ConcurrentDictionary<string, double> _cache = new ConcurrentDictionary<string, double>(); 4:  5: // adds a new subscription, or increments the count of the existing one. 6: public double QueryPrice(string tickerKey) 7: { 8: // check for the price in the cache, if it doesn't exist it will call the delegate to create value. 9: return _cache.GetOrAdd(tickerKey, symbol => GetCurrentPrice(symbol)); 10: } 11:  12: private double GetCurrentPrice(string tickerKey) 13: { 14: // do code to calculate actual true price. 15: } 16: } There are other variations of these two methods which vary whether a value is provided or a factory delegate, but otherwise they work much the same. Oddities with the composite Add methods The AddOrUpdate() and GetOrAdd() methods are totally thread-safe, on this you may rely, but they are not atomic.  It is important to note that the methods that use delegates execute those delegates outside of the lock.  This was done intentionally so that a user delegate (of which the ConcurrentDictionary has no control of course) does not take too long and lock out other threads. This is not necessarily an issue, per se, but it is something you must consider in your design.  The main thing to consider is that your delegate may get called to generate an item, but that item may not be the one returned!  Consider this scenario: A calls GetOrAdd and sees that the key does not currently exist, so it calls the delegate.  Now thread B also calls GetOrAdd and also sees that the key does not currently exist, and for whatever reason in this race condition it’s delegate completes first and it adds its new value to the dictionary.  Now A is done and goes to get the lock, and now sees that the item now exists.  In this case even though it called the delegate to create the item, it will pitch it because an item arrived between the time it attempted to create one and it attempted to add it. Let’s illustrate, assume this totally contrived example program which has a dictionary of char to int.  And in this dictionary we want to store a char and it’s ordinal (that is, A = 1, B = 2, etc).  So for our value generator, we will simply increment the previous value in a thread-safe way (perhaps using Interlocked): 1: public static class Program 2: { 3: private static int _nextNumber = 0; 4:  5: // the holder of the char to ordinal 6: private static ConcurrentDictionary<char, int> _dictionary 7: = new ConcurrentDictionary<char, int>(); 8:  9: // get the next id value 10: public static int NextId 11: { 12: get { return Interlocked.Increment(ref _nextNumber); } 13: } Then, we add a method that will perform our insert: 1: public static void Inserter() 2: { 3: for (int i = 0; i < 26; i++) 4: { 5: _dictionary.GetOrAdd((char)('A' + i), key => NextId); 6: } 7: } Finally, we run our test by starting two tasks to do this work and get the results… 1: public static void Main() 2: { 3: // 3 tasks attempting to get/insert 4: var tasks = new List<Task> 5: { 6: new Task(Inserter), 7: new Task(Inserter) 8: }; 9:  10: tasks.ForEach(t => t.Start()); 11: Task.WaitAll(tasks.ToArray()); 12:  13: foreach (var pair in _dictionary.OrderBy(p => p.Key)) 14: { 15: Console.WriteLine(pair.Key + ":" + pair.Value); 16: } 17: } If you run this with only one task, you get the expected A:1, B:2, ..., Z:26.  But running this in parallel you will get something a bit more complex.  My run netted these results: 1: A:1 2: B:3 3: C:4 4: D:5 5: E:6 6: F:7 7: G:8 8: H:9 9: I:10 10: J:11 11: K:12 12: L:13 13: M:14 14: N:15 15: O:16 16: P:17 17: Q:18 18: R:19 19: S:20 20: T:21 21: U:22 22: V:23 23: W:24 24: X:25 25: Y:26 26: Z:27 Notice that B is 3?  This is most likely because both threads attempted to call GetOrAdd() at roughly the same time and both saw that B did not exist, thus they both called the generator and one thread got back 2 and the other got back 3.  However, only one of those threads can get the lock at a time for the actual insert, and thus the one that generated the 3 won and the 3 was inserted and the 2 got discarded.  This is why on these methods your factory delegates should be careful not to have any logic that would be unsafe if the value they generate will be pitched in favor of another item generated at roughly the same time.  As such, it is probably a good idea to keep those generators as stateless as possible. Summary The ConcurrentDictionary is a very efficient and thread-safe version of the Dictionary generic collection.  It has all the benefits of type-safety that it’s generic collection counterpart does, and in addition is extremely efficient especially when there are more reads than writes concurrently. Tweet Technorati Tags: C#, .NET, Concurrent Collections, Collections, Little Wonders, Black Rabbit Coder,James Michael Hare

    Read the article

  • no mails routed to/from new Exchange 2010

    - by Michael
    I have an Exchange Server 2003 up and running for years. Now I am in the mid of transition to Exchange Server 2010, I already installed it, put the latest Servicepack on it and everything seems fine, BUT: Mails do not get delivered to MailBoxes on the new Exchange 2010. e.g. when I create a new mailbox on the old server, Emails in and out to/from it work like a charm. But as soon as I move it to the new server, emails get stuck. Noe delivered from outside or old mailboxes, not send out from the new server to enywhere. Sending between Mailboxes on the new Server of course is working. I can see the connectors between old and new Server in the Exchange 2003 Admin Tool, but I cannot find these nowhere on the new server. I have also setup sending connectors at the new server to send out mails directly, but that does not work. In all other areas, the servers are perfectly working together - moving mailboxes between, seeing each other etc. "just" they dont exchange (!) any emails - Any ideas what I missed? I also followed the hints from: Upgrading from Exchange 2003 to Exchange 2010, routing works in one direction only There Emails were transported at least in one direction, in my case they are not transported at all. Both my connectors are up and valid abd have the correct source/target shown on Get-RoutingGroupConnector | FL Kind regards Michael

    Read the article

  • DNS issue for internal website routing internet connection from remote location

    - by Michael Paul
    I have an issue that I could use some help with. Our company has a main location and a remote location. Previously, the remote location was connected to the main location through an internet connection VPN tunnel. The connection was pitifully slow at 1.5Mbps, so we upgraded it with a 75Mbps direct link. That meant the remote location lost it's internet access, so we routed their access through the main office internet connection. Everything works perfect except for one thing. The website we host is not accessible from the remote location unless the IP address is used. If I do NSLOOKUP on our website address from a machine connected to the main location network, it resolves correctly to the inside IP address. However, if I do the same from a remote location machine, it resolves to the website's outside IP address. Our internal DNS server(s) have a pointer and CNAME records set up, and everything was working perfectly before the connection was upgraded. In addition, the remote location has a domain controller, DNS server and DHCP server to service these requests at the remote location and prevent these requests from getting routed back and forth over the link. So I think was it happening is that for some reason the DNS server at the remote location is not resolving our website name correctly and passing the requests on to the routers, which then push the request out to the internet DNS system. That resolves the name to our external IP. This is purely a DNS issue, everything else works just fine. I am just stumped on this one. Any ideas on how to fix this? Edit: I forgot to mention that at the remote side of the link is a Cisco ASA-5505 and at the main office there is a Cisco ASA-5510. The link is connected between these 2 devices and the routing is handled in the 5510. Thanks, Michael

    Read the article

  • STOP 0x7b booting from iSCSI

    - by Michael
    Hi, I've a Windows 2008 SBS running. It boots of iSCSI. That setup worked for months until yesterday. I intended to reboot and gained a: STOP 0x0000007b INACCESSIBLE_BOOT_DEVICE and no idea why. My setup hasn't changed. No new controller, no new or changed iSCSI targets, no new Network Card or IP address changes. I had all Windows Updates on it. Last known good: same STOP. Allow unsigned drivers: same STOP. Safe mode (all variants): same STOP. Mount target from a client: works. Filesystem check fine. I booted of the SBS DVD but in computer repair options my target doesn't appear. When i choose setup the target appears. So, how can i diagnose what's going wrong? Any helpful tools? Any hints? Thanks in advance Michael

    Read the article

  • Creating a Colormap Legend in Matplotlib

    - by Vince
    Hi fellow Stackers! I am using imshow() in matplotlib like so: import numpy as np import matplotlib.pyplot as plt mat = '''SOME MATRIX''' plt.imshow(mat, origin="lower", cmap='gray', interpolation='nearest') plt.show() How do I add a legend showing the numeric value for the different shades of gray. Sadly, my googling has not uncovered an answer :( Thank you in advance for the help. Vince

    Read the article

  • JQUERY Effect highlight, control the Start & End colors

    - by nobosh
    I have the following: $(".notifycell_email_dailydigest").effect('highlight'); The element I want to highlight is over a gray background. Problem is the highlight goes from Yellow to white, and has this ugly slow pause at the end on the white which makes the animation look horrible. How can I modify the highlighy to start with the yellow but end on the gray so it matches the background? Thanks

    Read the article

  • Blurry text in WPF even with ClearTypeHinting enabled?

    - by rFactor
    I have a grid with this template and styles in WPF/XAML: <Setter Property="TextOptions.TextFormattingMode" Value="Display" /> <Setter Property="RenderOptions.ClearTypeHint" Value="Enabled" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type DataGridCell}"> <Border Padding="{TemplateBinding Padding}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True"> <ContentPresenter x:Name="CellContent" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" RenderOptions.ClearTypeHint="Enabled" /> </Border> <ControlTemplate.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter TargetName="CellContent" Property="TextOptions.TextFormattingMode" Value="Display" /> <Setter TargetName="CellContent" Property="RenderOptions.ClearTypeHint" Value="Enabled" /> <Setter TargetName="CellContent" Property="Effect"> <Setter.Value> <DropShadowEffect ShadowDepth="2" BlurRadius="2" Color="Black" RenderingBias="Quality" /> </Setter.Value> </Setter> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> The DropShadowEffect I have when you select a grid row, seems to make the text rendering blurry (gray anti-aliasing): When I remove the drop shadow effect, it looks clear because it now uses ClearType and not gray sub-pixel anti-aliasing: I have tried applying RenderOptions.ClearTypeHint="Enabled" to the ContentPresenter as seen above, but it does not help. How do I force WPF to render the text that gets displayed with drop shadow effect to retain Cleartype anti-aliasing, instead of that ugly blurry gray sub-pixel anti-aliasing? Some believe it's blurry because of the drop shadow -- this is not true. It's blurry only because ClearType is not used. This is how it looks like in Firefox when shadow AND ClearType: ClearType enabled text is colorful -- but that blurry text is not, because it does not use ClearType -- it uses gray sub-pixel anti-aliasing and that's not how ClearType works: http://en.wikipedia.org/wiki/ClearType The question is: how do I enable ClearType for this text?

    Read the article

  • Header Div Position Edit according to Content Div

    - by Melih Mucuk
    I want to design my web site. I have two main div, one of them "header", other "content". I want to set width property:80% and I set center for both of them. But I don't do that. Other question about header div. I uploaded an image and I want to design like this. How can I do all of them? My CSS: #main { margin:0px auto; margin-left:50px; margin-right:50px; margin-top:25px; margin-bottom:25px; height:auto; text-align:center;} #content { width:80%; height:auto; margin:0px auto; } #header { width:80%; height:100px; top:20px; } #header_left { float:left ; height: 100px; text-align: center; } #header_right { margin:0px auto; height:30px; text-align:center; margin-top:35px; } #header_social { float:right; height:30px; text-align:center; margin-top:35px;} My client code: <div id="main"> <div id="content"> <div id="header"> <div id="header_left"> <asp:Image ID="Image1" runat="server" /> </div> <div id="header_right"> <asp:LinkButton ID="LinkButton5" runat="server" ForeColor="Gray"></asp:LinkButton>&nbsp;| <asp:LinkButton ID="LinkButton4" runat="server" ForeColor="Gray" ></asp:LinkButton>&nbsp;| <asp:LinkButton ID="LinkButton3" runat="server" ForeColor="#FF3300" ></asp:LinkButton>&nbsp;| <asp:LinkButton ID="LinkButton2" runat="server" ForeColor="Gray" ></asp:LinkButton>&nbsp;| <asp:LinkButton ID="LinkButton1" runat="server" ForeColor="Gray" ></asp:LinkButton> </div> <div id="header_social"> <asp:ImageButton ID="ImageButton1" runat="server"/> <asp:ImageButton ID="ImageButton2" runat="server"/> </div> </div> ******CONTENT FIELD***** </div> </div>

    Read the article

  • Creating a grid overlay over image.

    - by neteus
    Hi everybody, I made a script (using mootools library) that is supposed to overlay an image with a table grid and when each grid cell is clicked/dragged over its background color changes 'highlighting' the cell. Current code creates a table and positions it over the element (el, image in this case). Table was used since I am planning to add rectangle select tool later on, and it seemed easiest way to do it. <html> <head> <title></title> <script type="text/javascript" src="mootools.js"></script> <script type="text/javascript"> var SetGrid = function(el, sz, nr, nc){ //get number of rows/columns according to the 'grid' size numcols = el.getSize().x/sz; numrows = el.getSize().y/sz; //create table element for injecting cols/rows var gridTable = new Element('table', { 'id' : 'gridTable', 'styles' : { 'width' : el.getSize().x, 'height' : el.getSize().y, 'top' : el.getCoordinates().top, 'left' : el.getCoordinates().left } }); //inject rows/cols into gridTable for (row = 1; row<=numrows; row++){ thisRow = new Element('tr', { 'id' : row, 'class' : 'gridRow' }); for(col = 1; col<=numcols; col++){ thisCol = new Element('td', { 'id' : col, 'class' : 'gridCol0' }); //each cell gets down/up over event... down starts dragging|up stops|over draws area if down was fired thisCol.addEvents({ 'mousedown' : function(){ dragFlag = true; startRow = this.getParent().get('id'); startCol = this.get('id'); }, 'mouseup' : function(){ dragFlag = false; }, 'mouseover' : function(){ if (dragFlag==true){ this.set('class', 'gridCol'+$$('#lvlSelect .on').get('value')); } }, 'click' : function(){ //this.set('class', 'gridCol'+$$('#lvlSelect .on').get('id').substr(3, 1) ); str = $$('#lvlSelect .on').get('id'); alert(str.substr(2, 3)); } }); thisCol.inject(thisRow, 'bottom'); }; thisRow.inject(gridTable, 'bottom'); }; gridTable.inject(el.getParent()); } //sens level selector func var SetSensitivitySelector = function(el, sz, nr, nc){ $$('#lvlSelect ul li').each(function(el){ el.addEvents({ 'click' : function(){ $$('#lvlSelect ul li').set('class', ''); this.set('class', 'on'); }, 'mouseover' : function(){ el.setStyle('cursor','pointer'); }, 'mouseout' : function(){ el.setStyle('cursor',''); } }); }); } //execute window.addEvent('load', function(){ SetGrid($('imagetomap'), 32); SetSensitivitySelector(); }); </script> <style> #imagetomapdiv { float:left; display: block; } #gridTable { border:1px solid red; border-collapse:collapse; position:absolute; z-index:5; } #gridTable td { opacity:0.2; filter:alpha(opacity=20); } #gridTable .gridCol0 { border:1px solid gray; background-color: none; } #gridTable .gridCol1 { border:1px solid gray; background-color: green; } #gridTable .gridCol2 { border:1px solid gray; background-color: blue; } #gridTable .gridCol3 { border:1px solid gray; background-color: yellow; } #gridTable .gridCol4 { border:1px solid gray; background-color: orange; } #gridTable .gridCol5 { border:1px solid gray; background-color: red; } #lvlSelect ul {float: left; display:block; position:relative; margin-left: 20px; padding: 10px; } #lvlSelect ul li { width:40px; text-align:center; display:block; border:1px solid black; position:relative; padding: 10px; list-style:none; opacity:0.2; filter:alpha(opacity=20); } #lvlSelect ul li.on { opacity:1; filter:alpha(opacity=100); } #lvlSelect ul #li0 { background-color: none; } #lvlSelect ul #li1 { background-color: green; } #lvlSelect ul #li2 { background-color: blue; } #lvlSelect ul #li3 { background-color: yellow; } #lvlSelect ul #li4 { background-color: orange; } #lvlSelect ul #li5 { background-color: red; } </style> </head> <body> <div id="imagetomapdiv"> <img id="imagetomap" src="1.png"> </div> <div id="lvlSelect"> <ul> <li value="0" id="li0">0</li> <li value="1" id="li1">1</li> <li value="2" id="li2">2</li> <li value="3" id="li3">3</li> <li value="4" id="li4">4</li> <li value="5" id="li5" class="on">5</li> </ul> </div> </body> </html> A 'working' example: http://72.14.186.218/~alex/motion.php There are two problems: while it works just fine in FF, IE and Chrome do not create the table if the page is refreshed. If you go back to directory root and click on the link to the file the grid table is displayed, if you hit 'refresh' button -- the script runs but the table is not injected. Secondly, although the table HTML is injected in IE, it does not display it. I tried adding nbsp's to make sure its not ignored -- to no avail. Any suggestions on improving code or help with the issues is appreciated. Thanks!

    Read the article

  • need prefuse graph edges like arrows

    - by merve
    Hello, I did my homework and searched both google for a sample and a topic that is answered before on stackoverflow. But nothing has been found. My problem is ordinary edges who does not have a view like arrows. Here is what i do to hope there is forward arrows from target to destination: LabelRenderer nameLabel = new LabelRenderer("name"); nameLabel.setRoundedCorner(8, 8); DefaultRendererFactory rendererFactory = new DefaultRendererFactory(nameLabel); EdgeRenderer edgeRenderer; edgeRenderer = new EdgeRenderer(prefuse.Constants.EDGE_TYPE_LINE, prefuse.Constants.EDGE_ARROW_FORWARD); rendererFactory.setDefaultEdgeRenderer(edgeRenderer); vis.setRendererFactory(rendererFactory); Here is what i see about colour of edges, hoping these must not be transparent: int[] palette = new int[]{ColorLib.rgb(255, 180, 180), ColorLib.rgb(190, 190, 255)}; DataColorAction fill = new DataColorAction("socialnet.nodes", "gender", Constants.NOMINAL, VisualItem.FILLCOLOR, palette); ColorAction text = new ColorAction("socialnet.nodes", VisualItem.TEXTCOLOR, ColorLib.gray(0)); ColorAction edges = new ColorAction("socialnet.edges", VisualItem.STROKECOLOR, ColorLib.gray(200)); ColorAction arrow = new ColorAction("socialnet.edges", VisualItem.FILLCOLOR, ColorLib.gray(200)); ActionList colour = new ActionList(); colour.add(fill); colour.add(text); colour.add(edges); colour.add(arrow); vis.putAction("colour", colour); Thus, i wonder where am i wrong? Why my edges do not seem like arrows? Thanks for any idea. For more detail, i want to paste all of the code: /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package prefusedeneme; import javax.swing.JFrame; import prefuse.data.*; import prefuse.data.io.*; import prefuse.Display; import prefuse.Visualization; import prefuse.render.*; import prefuse.util.*; import prefuse.action.assignment.*; import prefuse.Constants; import prefuse.visual.*; import prefuse.action.*; import prefuse.activity.*; import prefuse.action.layout.graph.*; import prefuse.controls.*; import prefuse.data.expression.Predicate; import prefuse.data.expression.parser.ExpressionParser; public class SocialNetworkVis { public static void main(String argv[]) { // 1. Load the data Graph graph = null; /* graph will contain the core data */ try { graph = new GraphMLReader().readGraph("socialnet.xml"); /* load the data from an XML file */ } catch (DataIOException e) { e.printStackTrace(); System.err.println("Error loading graph. Exiting..."); System.exit(1); } // 2. prepare the visualization Visualization vis = new Visualization(); /* vis is the main object that will run the visualization */ vis.add("socialnet", graph); /* add our data to the visualization */ // 3. setup the renderers and the render factory // labels for name LabelRenderer nameLabel = new LabelRenderer("name"); nameLabel.setRoundedCorner(8, 8); /* nameLabel decribes how to draw the data elements labeled as "name" */ // create the render factory DefaultRendererFactory rendererFactory = new DefaultRendererFactory(nameLabel); EdgeRenderer edgeRenderer; edgeRenderer = new EdgeRenderer(prefuse.Constants.EDGE_TYPE_LINE, prefuse.Constants.EDGE_ARROW_FORWARD); rendererFactory.setDefaultEdgeRenderer(edgeRenderer); vis.setRendererFactory(rendererFactory); // 4. process the actions // colour palette for nominal data type int[] palette = new int[]{ColorLib.rgb(255, 180, 180), ColorLib.rgb(190, 190, 255)}; /* ColorLib.rgb converts the colour values to integers */ // map data to colours in the palette DataColorAction fill = new DataColorAction("socialnet.nodes", "gender", Constants.NOMINAL, VisualItem.FILLCOLOR, palette); /* fill describes what colour to draw the graph based on a portion of the data */ // node text ColorAction text = new ColorAction("socialnet.nodes", VisualItem.TEXTCOLOR, ColorLib.gray(0)); /* text describes what colour to draw the text */ // edge ColorAction edges = new ColorAction("socialnet.edges", VisualItem.STROKECOLOR, ColorLib.gray(200)); ColorAction arrow = new ColorAction("socialnet.edges", VisualItem.FILLCOLOR, ColorLib.gray(200)); /* edge describes what colour to draw the edges */ // combine the colour assignments into an action list ActionList colour = new ActionList(); colour.add(fill); colour.add(text); colour.add(edges); colour.add(arrow); vis.putAction("colour", colour); /* add the colour actions to the visualization */ // create a separate action list for the layout ActionList layout = new ActionList(Activity.INFINITY); layout.add(new ForceDirectedLayout("socialnet")); /* use a force-directed graph layout with default parameters */ layout.add(new RepaintAction()); /* repaint after each movement of the graph nodes */ vis.putAction("layout", layout); /* add the laout actions to the visualization */ // 5. add interactive controls for visualization Display display = new Display(vis); display.setSize(700, 700); display.pan(350, 350); // pan to the middle display.addControlListener(new DragControl()); /* allow items to be dragged around */ display.addControlListener(new PanControl()); /* allow the display to be panned (moved left/right, up/down) (left-drag)*/ display.addControlListener(new ZoomControl()); /* allow the display to be zoomed (right-drag) */ // 6. launch the visualizer in a JFrame JFrame frame = new JFrame("prefuse tutorial: socialnet"); /* frame is the main window */ frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(display); /* add the display (which holds the visualization) to the window */ frame.pack(); frame.setVisible(true); /* start the visualization working */ vis.run("colour"); vis.run("layout"); } }

    Read the article

  • Grid overlayed on image using javascript, need help getting grid coordinates.

    - by Alos
    Hi I am fairly new to javascript and could use some help, I am trying to overlay a grid on top of an image and then be able to have the user click on the grid and get the grid coordinate from the box that the user clicked. I have been working with the code from the following stackoverflow question: Creating a grid overlay over image. link text Here is the code that I have so far: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> </script> <script type="text/javascript"> var SetGrid = function(el, sz, nr, nc){ //get number of rows/columns according to the 'grid' size //numcols = el.getSize().x/sz; //numrows = el.getSize().y/sz; numcols = 48; numrows = 32; //create table element for injecting cols/rows var gridTable = new Element('table', { 'id' : 'gridTable', 'styles' : { 'width' : el.getSize().x, 'height' : el.getSize().y, 'top' : el.getCoordinates().top, 'left' : el.getCoordinates().left } }); //inject rows/cols into gridTable for (row = 1; row<=numrows; row++){ thisRow = new Element('tr', { 'id' : row, 'class' : 'gridRow' }); for(col = 1; col<=numcols; col++){ thisCol = new Element('td', { 'id' : col, 'class' : 'gridCol0' }); //each cell gets down/up over event... down starts dragging|up stops|over draws area if down was fired thisCol.addEvents({ 'mousedown' : function(){ dragFlag = true; startRow = this.getParent().get('id'); startCol = this.get('id'); }, 'mouseup' : function(){ dragFlag = false; }, 'mouseover' : function(){ if (dragFlag==true){ this.set('class', 'gridCol'+$$('#lvlSelect .on').get('value')); } }, 'click' : function(){ //this.set('class', 'gridCol'+$$('#lvlSelect .on').get('id').substr(3, 1) ); str = $$('#lvlSelect .on').get('id'); alert(str.substr(2, 3)); } }); thisCol.inject(thisRow, 'bottom'); }; thisRow.inject(gridTable, 'bottom'); }; gridTable.inject(el.getParent()); } //sens level selector func var SetSensitivitySelector = function(el, sz, nr, nc){ $$('#lvlSelect ul li').each(function(el){ el.addEvents({ 'click' : function(){ $$('#lvlSelect ul li').set('class', ''); this.set('class', 'on'); }, 'mouseover' : function(){ el.setStyle('cursor','pointer'); }, 'mouseout' : function(){ el.setStyle('cursor',''); } }); }); } //execute window.addEvent('load', function(){ SetGrid($('imagetomap'), 32); SetSensitivitySelector(); }); var gridSize = { x: 48, y: 32 }; var img = document.getElementById('imagetomap'); img.onclick = function(e) { if (!e) e = window.event; alert(Math.floor(e.offsetX/ gridSize.x) + ', ' + Math.floor(e.offsetY / gridSize.y)); } </script> <style> #imagetomapdiv { float:left; display: block; } #gridTable { border:1px solid red; border-collapse:collapse; position:absolute; z-index:5; } #gridTable td { opacity:0.2; filter:alpha(opacity=20); } #gridTable .gridCol0 { border:1px solid gray; background-color: none; } #gridTable .gridCol1 { border:1px solid gray; background-color: green; } #gridTable .gridCol2 { border:1px solid gray; background-color: blue; } #gridTable .gridCol3 { border:1px solid gray; background-color: yellow; } #gridTable .gridCol4 { border:1px solid gray; background-color: orange; } #gridTable .gridCol5 { border:1px solid gray; background-color: red; } #lvlSelect ul {float: left; display:block; position:relative; margin-left: 20px; padding: 10px; } #lvlSelect ul li { width:40px; text-align:center; display:block; border:1px solid black; position:relative; padding: 10px; list-style:none; opacity:0.2; filter:alpha(opacity=20); } #lvlSelect ul li.on { opacity:1; filter:alpha(opacity=100); } #lvlSelect ul #li0 { background-color: none; } #lvlSelect ul #li1 { background-color: green; } #lvlSelect ul #li2 { background-color: blue; } #lvlSelect ul #li3 { background-color: yellow; } #lvlSelect ul #li4 { background-color: orange; } #lvlSelect ul #li5 { background-color: red; } </style> </div> <div id="lvlSelect"> <ul> <li value="0" id="li0">0</li> <li value="1" id="li1">1</li> <li value="2" id="li2">2</li> <li value="3" id="li3">3</li> <li value="4" id="li4">4</li> <li value="5" id="li5" class="on">5</li> </ul> </div> In this example the grid box changes color when the image is grid box is clicked, but I would like to be able to have the coordinates of the box. Any help would be great. Thank you

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >