Search Results

Search found 2563 results on 103 pages for 'collections'.

Page 26/103 | < Previous Page | 22 23 24 25 26 27 28 29 30 31 32 33  | Next Page >

  • Microsoft VDI 2012 - VDI Personal collection vs Session-based deployment

    - by Vazgen
    I have a small confusion about the differences between the 2 types of set ups: When deploying using Add Roles and Features the Wizard requests to choose from one of two Deployment Scenarios: Virtual machine-based desktop deployment : Virtual machine-based desktop deployment allows users to connect to virtual desktop collections that include published RemoteApp programs and virtual desktops. Session-based desktop deployment : Session-based desktop deployment allows users to connect to session collections that include published RemoteApp programs and session-based desktops. Although this seems intuitive now, if I continue with "Virtual machine-based desktop deployment" I later have another two options when creating a collection: Pooled virtual desktop collection Personal virtual desktop collection This is where my confusion lies. What is the differences between a Session-based deployment and Virtual machine-based deployment with Personal virtual desktop collections? I'm mostly finding information pertaining to Windows Server 2008 but I know there are some core improvements in VDI 2012 so would someone please comment on that. Thank you

    Read the article

  • How to reserve public API to internal usage in .NET?

    - by mark
    Dear ladies and sirs. Let me first present the case, which will explain my question. This is going to be a bit long, so I apologize in advance :-). I have objects and collections, which should support the Merge API (it is my custom API, the signature of which is immaterial for this question). This API must be internal, meaning only my framework should be allowed to invoke it. However, derived types should be able to override the basic implementation. The natural way to implement this pattern as I see it, is this: The Merge API is declared as part of some internal interface, let us say IMergeable. Because the interface is internal, derived types would not be able to implement it directly. Rather they must inherit it from a common base type. So, a common base type is introduced, which would implement the IMergeable interface explicitly, where the interface methods delegate to respective protected virtual methods, providing the default implementation. This way the API is only callable by my framework, but derived types may override the default implementation. The following code snippet demonstrates the concept: internal interface IMergeable { void Merge(object obj); } public class BaseFrameworkObject : IMergeable { protected virtual void Merge(object obj) { // The default implementation. } void IMergeable.Merge(object obj) { Merge(obj); } } public class SomeThirdPartyObject : BaseFrameworkObject { protected override void Merge(object obj) { // A derived type implementation. } } All is fine, provided a single common base type suffices, which is usually true for non collection types. The thing is that collections must be mergeable as well. Collections do not play nicely with the presented concept, because developers do not develop collections from the scratch. There are predefined implementations - observable, filtered, compound, read-only, remove-only, ordered, god-knows-what, ... They may be developed from scratch in-house, but once finished, they serve wide range of products and should never be tailored to some specific product. Which means, that either: they do not implement the IMergeable interface at all, because it is internal to some product the scope of the IMergeable interface is raised to public and the API becomes open and callable by all. Let us refer to these collections as standard collections. Anyway, the first option screws my framework, because now each possible standard collection type has to be paired with the respective framework version, augmenting the standard with the IMergeable interface implementation - this is so bad, I am not even considering it. The second option breaks the framework as well, because the IMergeable interface should be internal for a reason (whatever it is) and now this interface has to open to all. So what to do? My solution is this. make IMergeable public API, but add an extra parameter to the Merge method, I call it a security token. The interface implementation may check that the token references some internal object, which is never exposed to the outside. If this is the case, then the method was called from within the framework, otherwise - some outside API consumer attempted to invoke it and so the implementation can blow up with a SecurityException. Here is the modified code snippet demonstrating this concept: internal static class InternalApi { internal static readonly object Token = new object(); } public interface IMergeable { void Merge(object obj, object token); } public class BaseFrameworkObject : IMergeable { protected virtual void Merge(object obj) { // The default implementation. } public void Merge(object obj, object token) { if (!object.ReferenceEquals(token, InternalApi.Token)) { throw new SecurityException("bla bla bla"); } Merge(obj); } } public class SomeThirdPartyObject : BaseFrameworkObject { protected override void Merge(object obj) { // A derived type implementation. } } Of course, this is less explicit than having an internally scoped interface and the check is moved from the compile time to run time, yet this is the best I could come up with. Now, I have a gut feeling that there is a better way to solve the problem I have presented. I do not know, may be using some standard Code Access Security features? I have only vague understanding of it, but can LinkDemand attribute be somehow related to it? Anyway, I would like to hear other opinions. Thanks.

    Read the article

  • Silverlight Cream for November 21, 2011 -- #1171

    - by Dave Campbell
    In this Issue: Colin Eberhardt, Sumit Dutta, Morten Nielsen, Jesse Liberty, Jeff Blankenburg(-2-), Brian Noyes, and Tony Champion. Above the Fold: Silverlight: "PV Basics : Client-side Collections" Tony Champion WP7: "Pushpin Clustering with the Windows Phone 7 Bing Map control" Colin Eberhardt Shoutouts: Michael Palermo's latest Desert Mountain Developers is up Michael Washington's latest Visual Studio #LightSwitch Daily is up From SilverlightCream.com: Pushpin Clustering with the Windows Phone 7 Bing Map control Colin Eberhardt is back discussing Pushpins for a BingMaps app on WP7 and provides a utility class that clusters pushpins, allowing you to render 1000s of pins on an app ... all the explanation and all the code Part 22 - Windows Phone 7 - Tile Push Notification Part 22 in Sumit Dutta's WP7 series is about Tile Push Notification... nice tutorial with all the code listed Correctly displaying your current location Morten Nielsen demonstrates formatting the information from the GPS on your WP7 into something intelligible and useful Spiking the Pomodoro Timer Jesse Liberty put up a quick and dirty version of a Pomodoro timer for WP7.1 to explore the technical challenges of the Full Stack Phase 2 he's cranking up 31 Days of Mango | Day #11: Network Jeff Blankenburg's Number 10 in his 31 Days quest of WP7.1 is about the NetworkInformation namespace which gives you all sorts of info on the user's device network connection availability, type, etc. 31 Days of Mango | Day #11: Live Tiles Jeff Blankenburg takes off on Live Tiles for Day 11... big topic for a 1 day post, but he takes off on it... updating and Live Tiles too Working with Prism 4 Part 2: MVVM Basics and Commands Brian Noyes has part 2 of his Prism/MVVM series up at SilverlightShow... very nice tutorial on the basics of getting a view and viewmodel up, and setting up an ICommand to launch an Edit View... plus the code to peruse. PV Basics : Client-side Collections Tony Champion is startig a series on Silverlight 5 and Pivot Viewer... First up is some basics in dealing with the control in SL5 and talking about Client-side Collections... great informative tutorial and all the code Stay in the 'Light! Twitter SilverlightNews | Twitter WynApse | WynApse.com | Tagged Posts | SilverlightCream Join me @ SilverlightCream | Phoenix Silverlight User Group Technorati Tags: Silverlight    Silverlight 3    Silverlight 4    Windows Phone MIX10

    Read the article

  • java.util.ConcurrentModificationException when serializing non thread-safe maps

    - by [email protected]
    We have got some questions related to exceptions thrown during a map serialization like the following one (in this example, for a LRUMap): java.util.ConcurrentModificationExceptionat org.apache.commons.collections.SequencedHashMap$OrderedIterator.next(Unknown Source)at org.apache.commons.collections.LRUMap.writeExternal(Unknown Source)at java.io.ObjectOutputStream.writeExternalData(ObjectOutputStream.java(Compiled Code))at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java(Compiled Code))at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java(Compiled Code))at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java(Inlined CompiledCode))at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java(Compiled Code))at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java(Compiled Code))at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java(Compiled Code))at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java(Inlined CompiledCode))at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java(Compiled Code))at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java(Compiled Code))at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java(Compiled Code))at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java(Inlined CompiledCode))at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java(Compiled Code))at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java(Compiled Code))at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java(Compiled Code))at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java(Compiled Code))at com.tangosol.util.ExternalizableHelper.writeSerializable(ExternalizableHelper.java(InlinedCompiled Code))at com.tangosol.util.ExternalizableHelper.writeObjectInternal(ExternalizableHelper.java(Compiled Code))at com.tangosol.util.ExternalizableHelper.serializeInternal(ExternalizableHelper.java(Compiled Code))at com.tangosol.util.ExternalizableHelper.toBinary(ExternalizableHelper.java(InlinedCompiled Code))at com.tangosol.util.ExternalizableHelper.toBinary(ExternalizableHelper.java(InlinedCompiled Code))at com.tangosol.coherence.servlet.TraditionalHttpSessionModel$OptimizedHolder.serializeValue(TraditionalHttpSessionModel.java(Inlined Compiled Code))at com.tangosol.coherence.servlet.TraditionalHttpSessionModel$OptimizedHolder.getBinary(TraditionalHttpSessionModel.java(Compiled Code)) This is caused because LRUMap is not thread safe, so if another thread is modifying the content of that same map while serialization is in progress, then the ConcurrentModificationException will be thrown. Also, the map must be synchronized. Other structures like java.util.HashMap are not thread safe too. To avoid this kind of problems, it is recommended to use a thread-safe and synchronized map such as java.util.Map, java.util.Hashtable or com.tangosol.util.SafeHashMap. You may also need to use the synchronizedMap(Map) method from Class java.util.Collections.  

    Read the article

  • Workaround: build FBX in XNA raise OutOfMemoryException

    - by Vitus
    If you try to add large FBX 3D model to the XNA project, and build it, you can get an OutOfMemoryException build error like following: Error    1    Building content threw OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.    at System.Collections.Generic.List`1.set_Capacity(Int32 value)    at System.Collections.Generic.List`1.EnsureCapacity(Int32 min)    at System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection)    at Microsoft.Xna.Framework.Content.Pipeline.Graphics.VertexChannel`1.InsertRange(Int32 index, Int32 count)    at Microsoft.Xna.Framework.Content.Pipeline.Graphics.VertexContent.InsertRange(Int32 index, IEnumerable`1 positionIndexCollection)    at Microsoft.Xna.Framework.Content.Pipeline.Graphics.MeshBuilder.AddTriangleVertex(Int32 indexIntoVertexCollection)    at Microsoft.Xna.Framework.Content.Pipeline.MeshConverter.FillNodeWithInfoFromMesh(KFbxNode* fbxNode, String name, KFbxGeometryConverter* geometryConverter)    at Microsoft.Xna.Framework.Content.Pipeline.FbxImporter.ProcessInformationInNode(KFbxNode* fbxNode, String name, Boolean* partOfMainSkeleton, Boolean* warnIfBoneButNotChild)    at Microsoft.Xna.Framework.Content.Pipeline.FbxImporter.ProcessNode(ValueType parentAbsoluteTransform, NodeContent potentialParent, KFbxNode* fbxNode, Boolean partOfMainSkeleton, Boolean warnIfBoneButNotChild)    at Microsoft.Xna.Framework.Content.Pipeline.FbxImporter.ProcessNode(ValueType parentAbsoluteTransform, NodeContent potentialParent, KFbxNode* fbxNode, Boolean partOfMainSkeleton, Boolean warnIfBoneButNotChild)    at Microsoft.Xna.Framework.Content.Pipeline.FbxImporter.Import(String filename, ContentImporterContext context)    at Microsoft.Xna.Framework.Content.Pipeline.ContentImporter`1.Microsoft.Xna.Framework.Content.Pipeline.IContentImporter.Import(String filename, ContentImporterContext context)    //additional calls here …   My desktop PC have 8Gb RAM, and Visual Studio’s process devenv.exe use under 2Gb of it while build process (about 3.5-4Gb of RAM is always free). It’s obvious, that VS can’t address more than 2Gb of RAM, and when that limit is over, build process is fail. OS on my PC is Win x64,  so I “charge” devenv.exe by using editbin.exe utility – in the VS Command prompt I run following: editbin "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe" /LARGEADDRESSAWARE This command edits the image to indicate that the application can handle addresses larger than 2 gigabytes. After that FBX file successfully built! Of course, you must put proper path to devenv.exe, depend on your installation path. If you are on Win x86, you need to do additional action – more info here.   P.S.: although now you can build a bigger files, than usual, keep in mind, that XNA have some restrictions on vertex buffer size etc., depend on your current XNA project profile (Reach or HiDef). And if your model’s vertexbuffer size more than 64Mb (with Reach profile), that model can’t be built and raise an error.

    Read the article

  • error in C# code

    - by user318068
    hi all . I have a problem with my code in C# . if i click in compiler button , I get the following errors 'System.Collections.Generic.LinkedList' does not contain a definition for 'removeFirst' and no extension method 'removeFirst' accepting a first argument of type 'System.Collections.Generic.LinkedList' could be found (are you missing a using directive or an assembly reference?). and 'System.Collections.Generic.LinkedList' does not contain a definition for 'addLast' and no extension method 'addLast' accepting a first argument of type 'System.Collections.Generic.LinkedList' could be found (are you missing a using directive or an assembly reference?) This is part of a simple program using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Hanoi { public class Sol { public LinkedList<int?> t1 = new LinkedList<int?>(); public LinkedList<int?> t2 =new LinkedList<int?>(); public LinkedList<int?> t3 =new LinkedList<int?>(); public int depth; public LinkedList<Sol> neighbors; public Sol(LinkedList<int?> t1, LinkedList<int?> t2, LinkedList<int?> t3) { this.t1 = t1; this.t2 = t2; this.t3 = t3; neighbors = new LinkedList<Sol>(); } public virtual void getneighbors() { Sol temp = this.copy(); Sol neighbor1 = this.copy(); Sol neighbor2 = this.copy(); Sol neighbor3 = this.copy(); Sol neighbor4 = this.copy(); Sol neighbor5 = this.copy(); Sol neighbor6 = this.copy(); if (temp.t1.Count != 0) { if (neighbor1.t2.Count != 0) { if (neighbor1.t1.First.Value < neighbor1.t2.First.Value) { neighbor1.t2.AddFirst(neighbor1.t1.RemoveFirst()); neighbors.AddLast(neighbor1); } } else { neighbor1.t2.AddFirst(neighbor1.t1.RemoveFirst()); neighbors.AddLast(neighbor1); } if (neighbor2.t3.Count != 0) { if (neighbor2.t1.First.Value < neighbor2.t3.First.Value) { neighbor2.t3.AddFirst(neighbor2.t1.RemoveFirst()); neighbors.AddLast(neighbor2); } } else I hope that you find someone to help me

    Read the article

  • Converting a GameObject method call from UnityScript to C#

    - by Crims0n_
    Here is the UnityScript implementation of the method i use to generate a randomly tiled background, the problem i'm having relates to how to translate the call to the newTile method in c#, so far i've had no luck fiddling... can anyone point me in the correct direction? Thanks #pragma strict import System.Collections.Generic; var mapSizeX : int; var mapSizeY : int; var xOffset : float; var yOffset : float; var tilePrefab : GameObject; var tilePrefab2 : GameObject; var tiles : List.<Transform> = new List.<Transform>(); function Start () { var i : int = 0; var xIndex : int = 0; var yIndex : int = 0; xOffset = 2.69; yOffset = -1.97; while(yIndex < mapSizeY){ xIndex = 0; while(xIndex < mapSizeX){ var z = Random.Range(0, 5); if (z > 2) { var newTile : GameObject = Instantiate (tilePrefab, Vector3(xIndex*0.64 - (xOffset * (mapSizeX/10)), yIndex*-0.64 - (yOffset * (mapSizeY/10)), 0), Quaternion.identity); tiles.Add(newTile.transform); newTile.transform.parent = transform; newTile.transform.name = "tile_"+i; i++; xIndex++; } if (z < 2) { var newTile2 : GameObject = Instantiate (tilePrefab2, Vector3(xIndex*0.64 - (xOffset * (mapSizeX/10)), yIndex*-0.64 - (yOffset * (mapSizeY/10)), 0), Quaternion.identity); tiles.Add(newTile2.transform); newTile2.transform.parent = transform; newTile2.transform.name = "Ztile_"+i; i++; xIndex++; } } yIndex++; } } C# Version [Fixed] using UnityEngine; using System.Collections; public class LevelGen : MonoBehaviour { public int mapSizeX; public int mapSizeY; public float xOffset; public float yOffset; public GameObject tilePrefab; public GameObject tilePrefab2; int i; public System.Collections.Generic.List<Transform> tiles = new System.Collections.Generic.List<Transform>(); // Use this for initialization void Start () { int i = 0; int xIndex = 0; int yIndex = 0; xOffset = 1.58f; yOffset = -1.156f; while (yIndex < mapSizeY) { xIndex = 0; while(xIndex < mapSizeX) { int z = Random.Range(0, 5); if (z > 5) { GameObject newTile = (GameObject)Instantiate(tilePrefab, new Vector3(xIndex*0.64f - (xOffset * (mapSizeX/10.0f)), yIndex*-0.64f - (yOffset * (mapSizeY/10.0f)), 0), Quaternion.identity); tiles.Add(newTile.transform); newTile.transform.parent = transform; newTile.transform.name = "tile_"+i; i++; xIndex++; } if (z < 5) { GameObject newTile2 = (GameObject)Instantiate(tilePrefab, new Vector3(xIndex*0.64f - (xOffset * (mapSizeX/10.0f)), yIndex*-0.64f - (yOffset * (mapSizeY/10.0f)), 0), Quaternion.identity); tiles.Add(newTile2.transform); newTile2.transform.parent = transform; newTile2.transform.name = "tile2_"+i; i++; xIndex++; } } yIndex++; } } // Update is called once per frame void Update () { } }

    Read the article

  • Followup: Python 2.6, 3 abstract base class misunderstanding

    - by Aaron
    I asked a question at Python 2.6, 3 abstract base class misunderstanding. My problem was that python abstract base classes didn't work quite the way I expected them to. There was some discussion in the comments about why I would want to use ABCs at all, and Alex Martelli provided an excellent answer on why my use didn't work and how to accomplish what I wanted. Here I'd like to address why one might want to use ABCs, and show my test code implementation based on Alex's answer. tl;dr: Code after the 16th paragraph. In the discussion on the original post, statements were made along the lines that you don't need ABCs in Python, and that ABCs don't do anything and are therefore not real classes; they're merely interface definitions. An abstract base class is just a tool in your tool box. It's a design tool that's been around for many years, and a programming tool that is explicitly available in many programming languages. It can be implemented manually in languages that don't provide it. An ABC is always a real class, even when it doesn't do anything but define an interface, because specifying the interface is what an ABC does. If that was all an ABC could do, that would be enough reason to have it in your toolbox, but in Python and some other languages they can do more. The basic reason to use an ABC is when you have a number of classes that all do the same thing (have the same interface) but do it differently, and you want to guarantee that that complete interface is implemented in all objects. A user of your classes can rely on the interface being completely implemented in all classes. You can maintain this guarantee manually. Over time you may succeed. Or you might forget something. Before Python had ABCs you could guarantee it semi-manually, by throwing NotImplementedError in all the base class's interface methods; you must implement these methods in derived classes. This is only a partial solution, because you can still instantiate such a base class. A more complete solution is to use ABCs as provided in Python 2.6 and above. Template methods and other wrinkles and patterns are ideas whose implementation can be made easier with full-citizen ABCs. Another idea in the comments was that Python doesn't need ABCs (understood as a class that only defines an interface) because it has multiple inheritance. The implied reference there seems to be Java and its single inheritance. In Java you "get around" single inheritance by inheriting from one or more interfaces. Java uses the word "interface" in two ways. A "Java interface" is a class with method signatures but no implementations. The methods are the interface's "interface" in the more general, non-Java sense of the word. Yes, Python has multiple inheritance, so you don't need Java-like "interfaces" (ABCs) merely to provide sets of interface methods to a class. But that's not the only reason in software development to use ABCs. Most generally, you use an ABC to specify an interface (set of methods) that will likely be implemented differently in different derived classes, yet that all derived classes must have. Additionally, there may be no sensible default implementation for the base class to provide. Finally, even an ABC with almost no interface is still useful. We use something like it when we have multiple except clauses for a try. Many exceptions have exactly the same interface, with only two differences: the exception's string value, and the actual class of the exception. In many exception clauses we use nothing about the exception except its class to decide what to do; catching one type of exception we do one thing, and another except clause catching a different exception does another thing. According to the exception module's doc page, BaseException is not intended to be derived by any user defined exceptions. If ABCs had been a first class Python concept from the beginning, it's easy to imagine BaseException being specified as an ABC. But enough of that. Here's some 2.6 code that demonstrates how to use ABCs, and how to specify a list-like ABC. Examples are run in ipython, which I like much better than the python shell for day to day work; I only wish it was available for python3. Your basic 2.6 ABC: from abc import ABCMeta, abstractmethod class Super(): __metaclass__ = ABCMeta @abstractmethod def method1(self): pass Test it (in ipython, python shell would be similar): In [2]: a = Super() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() TypeError: Can't instantiate abstract class Super with abstract methods method1 Notice the end of the last line, where the TypeError exception tells us that method1 has not been implemented ("abstract methods method1"). That was the method designated as @abstractmethod in the preceding code. Create a subclass that inherits Super, implement method1 in the subclass and you're done. My problem, which caused me to ask the original question, was how to specify an ABC that itself defines a list interface. My naive solution was to make an ABC as above, and in the inheritance parentheses say (list). My assumption was that the class would still be abstract (can't instantiate it), and would be a list. That was wrong; inheriting from list made the class concrete, despite the abstract bits in the class definition. Alex suggested inheriting from collections.MutableSequence, which is abstract (and so doesn't make the class concrete) and list-like. I used collections.Sequence, which is also abstract but has a shorter interface and so was quicker to implement. First, Super derived from Sequence, with nothing extra: from abc import abstractmethod from collections import Sequence class Super(Sequence): pass Test it: In [6]: a = Super() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() TypeError: Can't instantiate abstract class Super with abstract methods __getitem__, __len__ We can't instantiate it. A list-like full-citizen ABC; yea! Again, notice in the last line that TypeError tells us why we can't instantiate it: __getitem__ and __len__ are abstract methods. They come from collections.Sequence. But, I want a bunch of subclasses that all act like immutable lists (which collections.Sequence essentially is), and that have their own implementations of my added interface methods. In particular, I don't want to implement my own list code, Python already did that for me. So first, let's implement the missing Sequence methods, in terms of Python's list type, so that all subclasses act as lists (Sequences). First let's see the signatures of the missing abstract methods: In [12]: help(Sequence.__getitem__) Help on method __getitem__ in module _abcoll: __getitem__(self, index) unbound _abcoll.Sequence method (END) In [14]: help(Sequence.__len__) Help on method __len__ in module _abcoll: __len__(self) unbound _abcoll.Sequence method (END) __getitem__ takes an index, and __len__ takes nothing. And the implementation (so far) is: from abc import abstractmethod from collections import Sequence class Super(Sequence): # Gives us a list member for ABC methods to use. def __init__(self): self._list = [] # Abstract method in Sequence, implemented in terms of list. def __getitem__(self, index): return self._list.__getitem__(index) # Abstract method in Sequence, implemented in terms of list. def __len__(self): return self._list.__len__() # Not required. Makes printing behave like a list. def __repr__(self): return self._list.__repr__() Test it: In [34]: a = Super() In [35]: a Out[35]: [] In [36]: print a [] In [37]: len(a) Out[37]: 0 In [38]: a[0] --------------------------------------------------------------------------- IndexError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() /home/aaron/projects/test/test.py in __getitem__(self, index) 10 # Abstract method in Sequence, implemented in terms of list. 11 def __getitem__(self, index): ---> 12 return self._list.__getitem__(index) 13 14 # Abstract method in Sequence, implemented in terms of list. IndexError: list index out of range Just like a list. It's not abstract (for the moment) because we implemented both of Sequence's abstract methods. Now I want to add my bit of interface, which will be abstract in Super and therefore required to implement in any subclasses. And we'll cut to the chase and add subclasses that inherit from our ABC Super. from abc import abstractmethod from collections import Sequence class Super(Sequence): # Gives us a list member for ABC methods to use. def __init__(self): self._list = [] # Abstract method in Sequence, implemented in terms of list. def __getitem__(self, index): return self._list.__getitem__(index) # Abstract method in Sequence, implemented in terms of list. def __len__(self): return self._list.__len__() # Not required. Makes printing behave like a list. def __repr__(self): return self._list.__repr__() @abstractmethod def method1(): pass class Sub0(Super): pass class Sub1(Super): def __init__(self): self._list = [1, 2, 3] def method1(self): return [x**2 for x in self._list] def method2(self): return [x/2.0 for x in self._list] class Sub2(Super): def __init__(self): self._list = [10, 20, 30, 40] def method1(self): return [x+2 for x in self._list] We've added a new abstract method to Super, method1. This makes Super abstract again. A new class Sub0 which inherits from Super but does not implement method1, so it's also an ABC. Two new classes Sub1 and Sub2, which both inherit from Super. They both implement method1 from Super, so they're not abstract. Both implementations of method1 are different. Sub1 and Sub2 also both initialize themselves differently; in real life they might initialize themselves wildly differently. So you have two subclasses which both "is a" Super (they both implement Super's required interface) although their implementations are different. Also remember that Super, although an ABC, provides four non-abstract methods. So Super provides two things to subclasses: an implementation of collections.Sequence, and an additional abstract interface (the one abstract method) that subclasses must implement. Also, class Sub1 implements an additional method, method2, which is not part of Super's interface. Sub1 "is a" Super, but it also has additional capabilities. Test it: In [52]: a = Super() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() TypeError: Can't instantiate abstract class Super with abstract methods method1 In [53]: a = Sub0() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() TypeError: Can't instantiate abstract class Sub0 with abstract methods method1 In [54]: a = Sub1() In [55]: a Out[55]: [1, 2, 3] In [56]: b = Sub2() In [57]: b Out[57]: [10, 20, 30, 40] In [58]: print a, b [1, 2, 3] [10, 20, 30, 40] In [59]: a, b Out[59]: ([1, 2, 3], [10, 20, 30, 40]) In [60]: a.method1() Out[60]: [1, 4, 9] In [61]: b.method1() Out[61]: [12, 22, 32, 42] In [62]: a.method2() Out[62]: [0.5, 1.0, 1.5] [63]: a[:2] Out[63]: [1, 2] In [64]: a[0] = 5 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() TypeError: 'Sub1' object does not support item assignment Super and Sub0 are abstract and can't be instantiated (lines 52 and 53). Sub1 and Sub2 are concrete and have an immutable Sequence interface (54 through 59). Sub1 and Sub2 are instantiated differently, and their method1 implementations are different (60, 61). Sub1 includes an additional method2, beyond what's required by Super (62). Any concrete Super acts like a list/Sequence (63). A collections.Sequence is immutable (64). Finally, a wart: In [65]: a._list Out[65]: [1, 2, 3] In [66]: a._list = [] In [67]: a Out[67]: [] Super._list is spelled with a single underscore. Double underscore would have protected it from this last bit, but would have broken the implementation of methods in subclasses. Not sure why; I think because double underscore is private, and private means private. So ultimately this whole scheme relies on a gentleman's agreement not to reach in and muck with Super._list directly, as in line 65 above. Would love to know if there's a safer way to do that.

    Read the article

  • ArgumentError: Error #2004: One of the parameters is invalid.

    - by Florian
    I got the following stack trace while running a piece of code in my flex application: ArgumentError: Error #2004: One of the parameters is invalid. at ObjectOutput/writeObject() at mx.collections::ArrayList/writeExternal()[C:\autobuild\galaga\frameworks\projects\framework\src\mx\collections\ArrayList.as:470] at mx.collections::ArrayCollection/writeExternal()[C:\autobuild\galaga\frameworks\projects\framework\src\mx\collections\ArrayCollection.as:144] at flash.utils::ByteArray/writeObject() at mx.utils::ObjectUtil$/copy()[C:\autobuild\galaga\frameworks\projects\framework\src\mx\utils\ObjectUtil.as:100] at components::SettingsHandler/saveOpenNodes()[C:\workspaces\Intranets\UniqueInbox\flex_src\components\SettingsHandler.as:153] at components::soapjira/getIssuesByFilters()[C:\workspaces\Intranets\UniqueInbox\flex_src\components\soapjira.as:295] at components.tabs::JiraAllActions/loadData()[C:\workspaces\Intranets\UniqueInbox\flex_src\components\tabs\JiraAllActions.mxml:193] at components::SettingsHandler/settingsClosed()[C:\workspaces\Intranets\UniqueInbox\flex_src\components\SettingsHandler.as:114] at flash.events::EventDispatcher/dispatchEventFunction() at flash.events::EventDispatcher/dispatchEvent() at mx.core::UIComponent/dispatchEvent()[C:\autobuild\galaga\frameworks\projects\framework\src\mx\core\UIComponent.as:9408] at components.general::JiraSettings/closeSettings()[C:\workspaces\Intranets\UniqueInbox\flex_src\components\general\JiraSettings.mxml:58] at components.general::JiraSettings/__save_click()[C:\workspaces\Intranets\UniqueInbox\flex_src\components\general\JiraSettings.mxml:107] That stack comes up when running the following line (SettingsHandler.as:153): var tmp:Object = parentComponent.dataGrid.dataProvider.openNodes; I am actually copying the open nodes of a datagrid's provider. Has been working until now and just started going wrong, no idea what I have changed that could interfere with this. On debug mode, I see that openNodes is accessible and contains the open nodes, as expected. Doing tmp:Object = parentComponent.dataGrid.dataProvider.openNodes works, but not with ObjectUtil. (parentComponent is the reference to the component which contains the DG).

    Read the article

  • Error executing child request for handler in plugin

    - by user1348351
    I'm using nop commerce open source. I wanted to show the recently add products in home page. so what I did is I activated plugin Nop JCarousel in the admin panel. But if I select "Recently view product" as a Data source type it is working fine.But if I select "recently add product" Data source type there is error coming up. it says Server Error in '/' Application. Method not found: 'Nop.Core.IPagedList`1<Nop.Core.Domain.Catalog.Product> Nop.Services.Catalog.IProductService.SearchProducts(Int32, Int32, System.Nullable`1<Boolean>, System.Nullable`1<System.Decimal>, System.Nullable`1<System.Decimal>, Int32, System.String, Boolean, Int32, System.Collections.Generic.IList`1<Int32>, Nop.Core.Domain.Catalog.ProductSortingEnum, Int32, Int32, Boolean, System.Collections.Generic.IList`1<Int32> ByRef, Boolean)'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.MissingMethodException: Method not found: 'Nop.Core.IPagedList`1<Nop.Core.Domain.Catalog.Product> Nop.Services.Catalog.IProductService.SearchProducts(Int32, Int32, System.Nullable`1<Boolean>, System.Nullable`1<System.Decimal>, System.Nullable`1<System.Decimal>, Int32, System.String, Boolean, Int32, System.Collections.Generic.IList`1<Int32>, Nop.Core.Domain.Catalog.ProductSortingEnum, Int32, Int32, Boolean, System.Collections.Generic.IList`1<Int32> ByRef, Boolean)'. Source Error: Line 3: @foreach (var widget in Model) Line 4: { Line 5: @Html.Action(widget.ActionName, widget.ControllerName, widget.RouteValues) Line 6: } Any idea on how to solve this?

    Read the article

  • Generics vs inheritance (whenh no collection classes are involved)

    - by Ram
    This is an extension of this questionand probably might even be a duplicate of some other question(If so, please forgive me). I see from MSDN that generics are usually used with collections The most common use for generic classes is with collections like linked lists, hash tables, stacks, queues, trees and so on where operations such as adding and removing items from the collection are performed in much the same way regardless of the type of data being stored. The examples I have seen also validate the above statement. Can someone give a valid use of generics in a real-life scenario which does not involve any collections ? Pedantically, I was thinking about making an example which does not involve collections public class Animal<T> { public void Speak() { Console.WriteLine("I am an Animal and my type is " + typeof(T).ToString()); } public void Eat() { //Eat food } } public class Dog { public void WhoAmI() { Console.WriteLine(this.GetType().ToString()); } } and "An Animal of type Dog" will be Animal<Dog> magic = new Animal<Dog>(); It is entirely possible to have Dog getting inherited from Animal (Assuming a non-generic version of Animal)Dog:Animal Therefore Dog is an Animal Another example I was thinking was a BankAccount. It can be BankAccount<Checking>,BankAccount<Savings>. This can very well be Checking:BankAccount and Savings:BankAccount. Are there any best practices to determine if we should go with generics or with inheritance ?

    Read the article

  • How can I implement an interface member in protected ?

    - by Nicolas Dorier
    Hi, I've been quite surprise when I saw the metadata of ReadOnlyObservableCollection in VS 2008... public class ReadOnlyObservableCollection<T> : ReadOnlyCollection<T>, INotifyCollectionChanged, INotifyPropertyChanged { // Summary: // Initializes a new instance of the System.Collections.ObjectModel.ReadOnlyObservableCollection<T> // class that serves as a wrapper for the specified System.Collections.ObjectModel.ObservableCollection<T>. // // Parameters: // list: // The collection to wrap. public ReadOnlyObservableCollection(ObservableCollection<T> list); // Summary: // Occurs when an item is added or removed. protected virtual event NotifyCollectionChangedEventHandler CollectionChanged; // // Summary: // Occurs when a property value changes. protected virtual event PropertyChangedEventHandler PropertyChanged; // Summary: // Raises the System.Collections.ObjectModel.ReadOnlyObservableCollection<T>.CollectionChanged // event. // // Parameters: // args: // The event data. protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs args); // // Summary: // Raises the System.Collections.ObjectModel.ReadOnlyObservableCollection<T>.PropertyChanged // event. // // Parameters: // args: // The event data. protected virtual void OnPropertyChanged(PropertyChangedEventArgs args); } As you can see, CollectionChanged, a member of INotifyCollectionChanged is implemented in protected... and I can't do that in my own class. .NET framework should not compile ! Does someone has an explanation of this mystery ?

    Read the article

  • Data Structures for Junior Java Developer

    - by user1639637
    Ok,still learning Arrays. I wrote this code which fills the array named "rand" with random numbers between 0 and 1( exclusive). I want to start learning Complexity. the For loop executes n times (100 times) ,every time it takes O(1) time,so the worse case scenario is O(n),am I right? Also,I used ArrayList to store the 100 elements and I imported "Collections" and used Collections.sort() method to sort the elements. import java.util.Arrays; public class random { public static void main(String args[]) { double[] rand=new double[10]; for(int i=0;i<rand.length;i++) { rand[i]=(double) Math.random(); System.out.println(rand[i]); } Arrays.sort(rand); System.out.println(Arrays.toString(rand)); } } ArrayList: import java.util.ArrayList; import java.util.Collections; public class random { public static void main(String args[]) { ArrayList<Double> MyArrayList=new ArrayList<Double>(); for(int i=0;i<100;i++) { MyArrayList.add(Math.random()); } Collections.sort(MyArrayList); for(int j=0;j<MyArrayList.size();j++) { System.out.println(MyArrayList.get(j)); } } }

    Read the article

  • Generics vs inheritance (when no collection classes are involved)

    - by Ram
    This is an extension of this questionand probably might even be a duplicate of some other question(If so, please forgive me). I see from MSDN that generics are usually used with collections The most common use for generic classes is with collections like linked lists, hash tables, stacks, queues, trees and so on where operations such as adding and removing items from the collection are performed in much the same way regardless of the type of data being stored. The examples I have seen also validate the above statement. Can someone give a valid use of generics in a real-life scenario which does not involve any collections ? Pedantically, I was thinking about making an example which does not involve collections public class Animal<T> { public void Speak() { Console.WriteLine("I am an Animal and my type is " + typeof(T).ToString()); } public void Eat() { //Eat food } } public class Dog { public void WhoAmI() { Console.WriteLine(this.GetType().ToString()); } } and "An Animal of type Dog" will be Animal<Dog> magic = new Animal<Dog>(); It is entirely possible to have Dog getting inherited from Animal (Assuming a non-generic version of Animal)Dog:Animal Therefore Dog is an Animal Another example I was thinking was a BankAccount. It can be BankAccount<Checking>,BankAccount<Savings>. This can very well be Checking:BankAccount and Savings:BankAccount. Are there any best practices to determine if we should go with generics or with inheritance ?

    Read the article

  • Presenting collection of structures of strings in grid or similar in WPF - Example? Ideas?

    - by Andrew
    Hi, I have a collection of structures. The structure is just some strings. Example public struct ReportLine { public string Name; public string Address; public string Phone; ...// about 10 other strings } I can't change this part. What I want to do is display it in a simple grid or simlar in WPF. My only requirements are: a) need column headers b) rows must alternate in color c) columns big enough to hold largest datum (which is not know until run time) Can someone point me to an example to get me started? Is the GridView the way to go? Or DataGrid? Or perhaps just the grid? I have the book Pro WPF in C# 2008 and it covers binding ListBox's to collections, but the collections always seem to be collections of one field (ex. a collection of 40 names). Here I have a collection (an array in fact) of a structure. How do I setup the databinding? As you can see, I'm new to this and probably would most benefit from a reference to an article. I've found articles covering collections of 1 field, but no examples covering binding to an array of structures. Also, my intitial research indicates c) can't be easily done, if you demand that the column is big enough for all the data in that column, not just the visible data. Thanks, dave

    Read the article

  • Class library reference problem

    - by Anindya Chatterjee
    I am building a class library and using its default namespace as "System". There suppose I am creating a generic data structure say PriorityQueue and putting it under System.Collections.Generic namespace. Now when I am referencing that library from another project, I can't see PriorityQueue under "System.Collections.Generic" namespace anymore. Though the library is referenced in that project I can not access any of the classes in it. My question was mscorlib and System.dll share similar namespaces, but still classes from both the assembly is accessible, but why can't mine? If I put a public class under System.Collections.Generic namespace in my class library and refer that library in a project and use a statement like "using System.Collections.Generic", still why I can't access my class there? This was an experimentation I did, I know using System namespace is not encouraged in custom class library, but I want to know the reason behind why I can't access my class in this special case? Please someone shed some light on it. PS: Last time I asked similar question but put it wrongly, so people got misunderstood and I didn't get my answer. This time I am trying to put it correctly as far as I can. Sorry for the misunderstanding.

    Read the article

  • How to Implement an Interface that Requires Duplicate Member Names?

    - by Will Marcouiller
    I often have to implement some interfaces such as IEnumerable<T> in my code. Each time, when implementing automatically, I encounter the following: public IEnumerator<T> GetEnumerator() { // Code here... } public IEnumerator GetEnumerator1() { // Code here... } Though I have to implement both GetEnumerator() methods, they impossibly can have the same name, even if we understand that they do the same, somehow. The compiler can't treat them as one being the overload of the other, because only the return type differs. When doing so, I manage to set the GetEnumerator1() accessor to private. This way, the compiler doesn't complaint about not implementing the interface member, and I simply throw a NotImplementedException within the method's body. However, I wonder whether it is a good practice, or if I shall proceed differently, as perhaps a method alias or something like so. What is the best approach while implementing an interface such as IEnumerable<T> that requires the implementation of two different methods with the same name? EDIT #1 Does VB.NET reacts differently from C# while implementing interfaces, since in VB.NET it is explicitly implemented, thus forcing the GetEnumerator1(). Here's the code: Public Function GetEnumerator() As System.Collections.Generic.IEnumerator(Of T) Implements System.Collections.Generic.IEnumerable(Of T).GetEnumerator // Code here... End Function Public Function GetEnumerator1() As System.Collections.Generic.IEnumerator Implements System.Collections.Generic.IEnumerable.GetEnumerator // Code here... End Function Both GetEnumerator() methods are explicitly implemented, and the compile will refuse them to have the same name. Why?

    Read the article

  • Hibernate: fetching multiple bags efficiently

    - by Jens Jansson
    Hi! I'm developing a multilingual application. For this reason many objects have in their name and description fields collections of something I call LocalizedStrings instead of plain strings. Every LocalizedString is basically a pair of a locale and a string localized to that locale. Let's take an example an entity, let's say a book -object. public class Book{ @OneToMany private List<LocalizedString> names; @OneToMany private List<LocalizedString> description; //and so on... } When a user asks for a list of books, it does a query to get all the books, fetches the name and description of every book in the locale the user has selected to run the app in, and displays it back to the user. This works but it is a major performance issue. For the moment hibernate makes one query to fetch all the books, and after that it goes through every single object and asks hibernate for the localized strings for that specific object, resulting in a "n+1 select problem". Fetching a list of 50 entities produces about 6000 rows of sql commands in my server log. I tried making the collections eager but that lead me to the "cannot simultaneously fetch multiple bags"-issue. Then I tried setting the fetch strategy on the collections to subselect, hoping that it would do one query for all books, and after that do one query that fetches all LocalizedStrings for all the books. Subselects didn't work in this case how i would have hoped and it basically just did exactly the same as my first case. I'm starting to run out of ideas on how to optimize this. So in short, what fetching strategy alternatives are there when you are fetching a collection and every element in that collection has one or multiple collections in itself, which has to be fetch simultaneously.

    Read the article

  • C# 4: The Curious ConcurrentDictionary

    - by James Michael Hare
    In my previous post (here) I did a comparison of the new ConcurrentQueue versus the old standard of a System.Collections.Generic Queue with simple locking.  The results were exactly what I would have hoped, that the ConcurrentQueue was faster with multi-threading for most all situations.  In addition, concurrent collections have the added benefit that you can enumerate them even if they're being modified. So I set out to see what the improvements would be for the ConcurrentDictionary, would it have the same performance benefits as the ConcurrentQueue did?  Well, after running some tests and multiple tweaks and tunes, I have good and bad news. But first, let's look at the tests.  Obviously there's many things we can do with a dictionary.  One of the most notable uses, of course, in a multi-threaded environment is for a small, local in-memory cache.  So I set about to do a very simple simulation of a cache where I would create a test class that I'll just call an Accessor.  This accessor will attempt to look up a key in the dictionary, and if the key exists, it stops (i.e. a cache "hit").  However, if the lookup fails, it will then try to add the key and value to the dictionary (i.e. a cache "miss").  So here's the Accessor that will run the tests: 1: internal class Accessor 2: { 3: public int Hits { get; set; } 4: public int Misses { get; set; } 5: public Func<int, string> GetDelegate { get; set; } 6: public Action<int, string> AddDelegate { get; set; } 7: public int Iterations { get; set; } 8: public int MaxRange { get; set; } 9: public int Seed { get; set; } 10:  11: public void Access() 12: { 13: var randomGenerator = new Random(Seed); 14:  15: for (int i=0; i<Iterations; i++) 16: { 17: // give a wide spread so will have some duplicates and some unique 18: var target = randomGenerator.Next(1, MaxRange); 19:  20: // attempt to grab the item from the cache 21: var result = GetDelegate(target); 22:  23: // if the item doesn't exist, add it 24: if(result == null) 25: { 26: AddDelegate(target, target.ToString()); 27: Misses++; 28: } 29: else 30: { 31: Hits++; 32: } 33: } 34: } 35: } Note that so I could test different implementations, I defined a GetDelegate and AddDelegate that will call the appropriate dictionary methods to add or retrieve items in the cache using various techniques. So let's examine the three techniques I decided to test: Dictionary with mutex - Just your standard generic Dictionary with a simple lock construct on an internal object. Dictionary with ReaderWriterLockSlim - Same Dictionary, but now using a lock designed to let multiple readers access simultaneously and then locked when a writer needs access. ConcurrentDictionary - The new ConcurrentDictionary from System.Collections.Concurrent that is supposed to be optimized to allow multiple threads to access safely. So the approach to each of these is also fairly straight-forward.  Let's look at the GetDelegate and AddDelegate implementations for the Dictionary with mutex lock: 1: var addDelegate = (key,val) => 2: { 3: lock (_mutex) 4: { 5: _dictionary[key] = val; 6: } 7: }; 8: var getDelegate = (key) => 9: { 10: lock (_mutex) 11: { 12: string val; 13: return _dictionary.TryGetValue(key, out val) ? val : null; 14: } 15: }; Nothing new or fancy here, just your basic lock on a private object and then query/insert into the Dictionary. Now, for the Dictionary with ReadWriteLockSlim it's a little more complex: 1: var addDelegate = (key,val) => 2: { 3: _readerWriterLock.EnterWriteLock(); 4: _dictionary[key] = val; 5: _readerWriterLock.ExitWriteLock(); 6: }; 7: var getDelegate = (key) => 8: { 9: string val; 10: _readerWriterLock.EnterReadLock(); 11: if(!_dictionary.TryGetValue(key, out val)) 12: { 13: val = null; 14: } 15: _readerWriterLock.ExitReadLock(); 16: return val; 17: }; And finally, the ConcurrentDictionary, which since it does all it's own concurrency control, is remarkably elegant and simple: 1: var addDelegate = (key,val) => 2: { 3: _concurrentDictionary[key] = val; 4: }; 5: var getDelegate = (key) => 6: { 7: string s; 8: return _concurrentDictionary.TryGetValue(key, out s) ? s : null; 9: };                    Then, I set up a test harness that would simply ask the user for the number of concurrent Accessors to attempt to Access the cache (as specified in Accessor.Access() above) and then let them fly and see how long it took them all to complete.  Each of these tests was run with 10,000,000 cache accesses divided among the available Accessor instances.  All times are in milliseconds. 1: Dictionary with Mutex Locking 2: --------------------------------------------------- 3: Accessors Mostly Misses Mostly Hits 4: 1 7916 3285 5: 10 8293 3481 6: 100 8799 3532 7: 1000 8815 3584 8:  9:  10: Dictionary with ReaderWriterLockSlim Locking 11: --------------------------------------------------- 12: Accessors Mostly Misses Mostly Hits 13: 1 8445 3624 14: 10 11002 4119 15: 100 11076 3992 16: 1000 14794 4861 17:  18:  19: Concurrent Dictionary 20: --------------------------------------------------- 21: Accessors Mostly Misses Mostly Hits 22: 1 17443 3726 23: 10 14181 1897 24: 100 15141 1994 25: 1000 17209 2128 The first test I did across the board is the Mostly Misses category.  The mostly misses (more adds because data requested was not in the dictionary) shows an interesting trend.  In both cases the Dictionary with the simple mutex lock is much faster, and the ConcurrentDictionary is the slowest solution.  But this got me thinking, and a little research seemed to confirm it, maybe the ConcurrentDictionary is more optimized to concurrent "gets" than "adds".  So since the ratio of misses to hits were 2 to 1, I decided to reverse that and see the results. So I tweaked the data so that the number of keys were much smaller than the number of iterations to give me about a 2 to 1 ration of hits to misses (twice as likely to already find the item in the cache than to need to add it).  And yes, indeed here we see that the ConcurrentDictionary is indeed faster than the standard Dictionary here.  I have a strong feeling that as the ration of hits-to-misses gets higher and higher these number gets even better as well.  This makes sense since the ConcurrentDictionary is read-optimized. Also note that I tried the tests with capacity and concurrency hints on the ConcurrentDictionary but saw very little improvement, I think this is largely because on the 10,000,000 hit test it quickly ramped up to the correct capacity and concurrency and thus the impact was limited to the first few milliseconds of the run. So what does this tell us?  Well, as in all things, ConcurrentDictionary is not a panacea.  It won't solve all your woes and it shouldn't be the only Dictionary you ever use.  So when should we use each? Use System.Collections.Generic.Dictionary when: You need a single-threaded Dictionary (no locking needed). You need a multi-threaded Dictionary that is loaded only once at creation and never modified (no locking needed). You need a multi-threaded Dictionary to store items where writes are far more prevalent than reads (locking needed). And use System.Collections.Concurrent.ConcurrentDictionary when: You need a multi-threaded Dictionary where the writes are far more prevalent than reads. You need to be able to iterate over the collection without locking it even if its being modified. Both Dictionaries have their strong suits, I have a feeling this is just one where you need to know from design what you hope to use it for and make your decision based on that criteria.

    Read the article

  • Having trouble returning a value from a method call when sending an array and the program is error out when run in reference to the sort

    - by programmerNOOB
    I am getting the following output when this program is run: Please enter the Social Security Number for taxpayer 0: 111111111 Please enter the gross income for taxpayer 0: 20000 Please enter the Social Security Number for taxpayer 1: 555555555 Please enter the gross income for taxpayer 1: 50000 Please enter the Social Security Number for taxpayer 2: 333333333 Please enter the gross income for taxpayer 2: 5464166 Please enter the Social Security Number for taxpayer 3: 222222222 Please enter the gross income for taxpayer 3: 645641 Please enter the Social Security Number for taxpayer 4: 444444444 Please enter the gross income for taxpayer 4: 29000 Taxpayer # 1 SSN: 111111111, Income is $20,000.00, Tax is $0.00 Taxpayer # 2 SSN: 555555555, Income is $50,000.00, Tax is $0.00 Taxpayer # 3 SSN: 333333333, Income is $5,464,166.00, Tax is $0.00 Taxpayer # 4 SSN: 222222222, Income is $645,641.00, Tax is $0.00 Taxpayer # 5 SSN: 444444444, Income is $29,000.00, Tax is $0.00 Unhandled Exception: System.InvalidOperationException: Failed to compare two elements in the array. --- System.ArgumentException: At least one object must implement IComparable. at System.Collections.Comparer.Compare(Object a, Object b) at System.Collections.Generic.ObjectComparer`1.Compare(T x, T y) at System.Collections.Generic.ArraySortHelper`1.SwapIfGreaterWithItems(T[] keys, IComparer`1 comparer, Int32 a, Int32 b) at System.Collections.Generic.ArraySortHelper`1.QuickSort(T[] keys, Int32 left, Int32 right, IComparer`1 comparer) at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer) --- End of inner exception stack trace --- at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer) at System.Array.Sort[T](T[] array, Int32 index, Int32 length, IComparer`1 comparer) at System.Array.Sort[T](T[] array) at Assignment5.Taxpayer.Main(String[] args) in Program.cs:line 150 Notice the 0s at the end of the line that should be the tax amount??? Here is the code: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace taxes { class Rates { // Create a class named rates that has the following data members: private int incLimit; private double lowTaxRate; private double highTaxRate; // use read-only accessor public int IncomeLimit { get { return incLimit; } } public double LowTaxRate { get { return lowTaxRate; } } public double HighTaxRate { get { return highTaxRate; } } //A class constructor that assigns default values public Rates() { int limit = 30000; double lowRate = .15; double highRate = .28; incLimit = limit; lowTaxRate = lowRate; highTaxRate = highRate; } //A class constructor that takes three parameters to assign input values for limit, low rate and high rate. public Rates(int limit, double lowRate, double highRate) { } // A CalculateTax method that takes an income parameter and computes the tax as follows: public int CalculateTax(int income) { int limit = 0; double lowRate = 0; double highRate = 0; int taxOwed = 0; // If income is less than the limit then return the tax as income times low rate. if (income < limit) taxOwed = Convert.ToInt32(income * lowRate); // If income is greater than or equal to the limit then return the tax as income times high rate. if (income >= limit) taxOwed = Convert.ToInt32(income * highRate); return taxOwed; } } //end class Rates // Create a class named Taxpayer that has the following data members: public class Taxpayer { //Use get and set accessors. string SSN { get; set; } int grossIncome { get; set; } // Use read-only accessor. public int taxOwed { get { return taxOwed; } } // The Taxpayer class should be set up so that its objects are comparable to each other based on tax owed. class taxpayer : IComparable { public int taxOwed { get; set; } public int income { get; set; } int IComparable.CompareTo(Object o) { int returnVal; taxpayer temp = (taxpayer)o; if (this.taxOwed > temp.taxOwed) returnVal = 1; else if (this.taxOwed < temp.taxOwed) returnVal = -1; else returnVal = 0; return returnVal; } // End IComparable.CompareTo } //end taxpayer IComparable class // **The tax should be calculated whenever the income is set. // The Taxpayer class should have a getRates class method that has the following. public static void GetRates() { // Local method data members for income limit, low rate and high rate. int incLimit = 0; double lowRate; double highRate; string userInput; // Prompt the user to enter a selection for either default settings or user input of settings. Console.Write("Would you like the default values (D) or would you like to enter the values (E)?: "); /* If the user selects default the default values you will instantiate a rates object using the default constructor * and set the Taxpayer class data member for tax equal to the value returned from calling the rates object CalculateTax method.*/ userInput = Convert.ToString(Console.ReadLine()); if (userInput == "D" || userInput == "d") { Rates rates = new Rates(); rates.CalculateTax(incLimit); } // end if /* If the user selects to enter the rates data then prompt the user to enter values for income limit, low rate and high rate, * instantiate a rates object using the three-argument constructor passing those three entries as the constructor arguments and * set the Taxpayer class data member for tax equal to the valuereturned from calling the rates object CalculateTax method. */ if (userInput == "E" || userInput == "e") { Console.Write("Please enter the income limit: "); incLimit = Convert.ToInt32(Console.ReadLine()); Console.Write("Please enter the low rate: "); lowRate = Convert.ToDouble(Console.ReadLine()); Console.Write("Please enter the high rate: "); highRate = Convert.ToDouble(Console.ReadLine()); Rates rates = new Rates(incLimit, lowRate, highRate); rates.CalculateTax(incLimit); } } static void Main(string[] args) { Taxpayer[] taxArray = new Taxpayer[5]; Rates taxRates = new Rates(); // Implement a for-loop that will prompt the user to enter the Social Security Number and gross income. for (int x = 0; x < taxArray.Length; ++x) { taxArray[x] = new Taxpayer(); Console.Write("Please enter the Social Security Number for taxpayer {0}: ", x + 1); taxArray[x].SSN = Console.ReadLine(); Console.Write("Please enter the gross income for taxpayer {0}: ", x + 1); taxArray[x].grossIncome = Convert.ToInt32(Console.ReadLine()); } Taxpayer.GetRates(); // Implement a for-loop that will display each object as formatted taxpayer SSN, income and calculated tax. for (int i = 0; i < taxArray.Length; ++i) { Console.WriteLine("Taxpayer # {0} SSN: {1}, Income is {2:c}, Tax is {3:c}", i + 1, taxArray[i].SSN, taxArray[i].grossIncome, taxRates.CalculateTax(taxArray[i].grossIncome)); } // end for // Implement a for-loop that will sort the five objects in order by the amount of tax owed Array.Sort(taxArray); Console.WriteLine("Sorted by tax owed"); for (int i = 0; i < taxArray.Length; ++i) { Console.WriteLine("Taxpayer # {0} SSN: {1}, Income is {2:c}, Tax is {3:c}", i + 1, taxArray[i].SSN, taxArray[i].grossIncome, taxRates.CalculateTax(taxArray[i].grossIncome)); } } //end main } // end Taxpayer class } //end Any clues as to why the dollar amount is coming up as 0 and why the sort is not working?

    Read the article

  • Differences Between NHibernate and Entity Framework

    - by Ricardo Peres
    Introduction NHibernate and Entity Framework are two of the most popular O/RM frameworks on the .NET world. Although they share some functionality, there are some aspects on which they are quite different. This post will describe this differences and will hopefully help you get started with the one you know less. Mind you, this is a personal selection of features to compare, it is by no way an exhaustive list. History First, a bit of history. NHibernate is an open-source project that was first ported from Java’s venerable Hibernate framework, one of the first O/RM frameworks, but nowadays it is not tied to it, for example, it has .NET specific features, and has evolved in different ways from those of its Java counterpart. Current version is 3.3, with 3.4 on the horizon. It currently targets .NET 3.5, but can be used as well in .NET 4, it only makes no use of any of its specific functionality. You can find its home page at NHForge. Entity Framework 1 came out with .NET 3.5 and is now on its second major version, despite being version 4. Code First sits on top of it and but came separately and will also continue to be released out of line with major .NET distributions. It is currently on version 4.3.1 and version 5 will be released together with .NET Framework 4.5. All versions will target the current version of .NET, at the time of their release. Its home location is located at MSDN. Architecture In NHibernate, there is a separation between the Unit of Work and the configuration and model instances. You start off by creating a Configuration object, where you specify all global NHibernate settings such as the database and dialect to use, the batch sizes, the mappings, etc, then you build an ISessionFactory from it. The ISessionFactory holds model and metadata that is tied to a particular database and to the settings that came from the Configuration object, and, there will typically be only one instance of each in a process. Finally, you create instances of ISession from the ISessionFactory, which is the NHibernate representation of the Unit of Work and Identity Map. This is a lightweight object, it basically opens and closes a database connection as required and keeps track of the entities associated with it. ISession objects are cheap to create and dispose, because all of the model complexity is stored in the ISessionFactory and Configuration objects. As for Entity Framework, the ObjectContext/DbContext holds the configuration, model and acts as the Unit of Work, holding references to all of the known entity instances. This class is therefore not lightweight as its NHibernate counterpart and it is not uncommon to see examples where an instance is cached on a field. Mappings Both NHibernate and Entity Framework (Code First) support the use of POCOs to represent entities, no base classes are required (or even possible, in the case of NHibernate). As for mapping to and from the database, NHibernate supports three types of mappings: XML-based, which have the advantage of not tying the entity classes to a particular O/RM; the XML files can be deployed as files on the file system or as embedded resources in an assembly; Attribute-based, for keeping both the entities and database details on the same place at the expense of polluting the entity classes with NHibernate-specific attributes; Strongly-typed code-based, which allows dynamic creation of the model and strongly typing it, so that if, for example, a property name changes, the mapping will also be updated. Entity Framework can use: Attribute-based (although attributes cannot express all of the available possibilities – for example, cascading); Strongly-typed code mappings. Database Support With NHibernate you can use mostly any database you want, including: SQL Server; SQL Server Compact; SQL Server Azure; Oracle; DB2; PostgreSQL; MySQL; Sybase Adaptive Server/SQL Anywhere; Firebird; SQLLite; Informix; Any through OLE DB; Any through ODBC. Out of the box, Entity Framework only supports SQL Server, but a number of providers exist, both free and commercial, for some of the most used databases, such as Oracle and MySQL. See a list here. Inheritance Strategies Both NHibernate and Entity Framework support the three canonical inheritance strategies: Table Per Type Hierarchy (Single Table Inheritance), Table Per Type (Class Table Inheritance) and Table Per Concrete Type (Concrete Table Inheritance). Associations Regarding associations, both support one to one, one to many and many to many. However, NHibernate offers far more collection types: Bags of entities or values: unordered, possibly with duplicates; Lists of entities or values: ordered, indexed by a number column; Maps of entities or values: indexed by either an entity or any value; Sets of entities or values: unordered, no duplicates; Arrays of entities or values: indexed, immutable. Querying NHibernate exposes several querying APIs: LINQ is probably the most used nowadays, and really does not need to be introduced; Hibernate Query Language (HQL) is a database-agnostic, object-oriented SQL-alike language that exists since NHibernate’s creation and still offers the most advanced querying possibilities; well suited for dynamic queries, even if using string concatenation; Criteria API is an implementation of the Query Object pattern where you create a semi-abstract conceptual representation of the query you wish to execute by means of a class model; also a good choice for dynamic querying; Query Over offers a similar API to Criteria, but using strongly-typed LINQ expressions instead of strings; for this, although more refactor-friendlier that Criteria, it is also less suited for dynamic queries; SQL, including stored procedures, can also be used; Integration with Lucene.NET indexer is available. As for Entity Framework: LINQ to Entities is fully supported, and its implementation is considered very complete; it is the API of choice for most developers; Entity-SQL, HQL’s counterpart, is also an object-oriented, database-independent querying language that can be used for dynamic queries; SQL, of course, is also supported. Caching Both NHibernate and Entity Framework, of course, feature first-level cache. NHibernate also supports a second-level cache, that can be used among multiple ISessionFactorys, even in different processes/machines: Hashtable (in-memory); SysCache (uses ASP.NET as the cache provider); SysCache2 (same as above but with support for SQL Server SQL Dependencies); Prevalence; SharedCache; Memcached; Redis; NCache; Appfabric Caching. Out of the box, Entity Framework does not have any second-level cache mechanism, however, there are some public samples that show how we can add this. ID Generators NHibernate supports different ID generation strategies, coming from the database and otherwise: Identity (for SQL Server, MySQL, and databases who support identity columns); Sequence (for Oracle, PostgreSQL, and others who support sequences); Trigger-based; HiLo; Sequence HiLo (for databases that support sequences); Several GUID flavors, both in GUID as well as in string format; Increment (for single-user uses); Assigned (must know what you’re doing); Sequence-style (either uses an actual sequence or a single-column table); Table of ids; Pooled (similar to HiLo but stores high values in a table); Native (uses whatever mechanism the current database supports, identity or sequence). Entity Framework only supports: Identity generation; GUIDs; Assigned values. Properties NHibernate supports properties of entity types (one to one or many to one), collections (one to many or many to many) as well as scalars and enumerations. It offers a mechanism for having complex property types generated from the database, which even include support for querying. It also supports properties originated from SQL formulas. Entity Framework only supports scalars, entity types and collections. Enumerations support will come in the next version. Events and Interception NHibernate has a very rich event model, that exposes more than 20 events, either for synchronous pre-execution or asynchronous post-execution, including: Pre/Post-Load; Pre/Post-Delete; Pre/Post-Insert; Pre/Post-Update; Pre/Post-Flush. It also features interception of class instancing and SQL generation. As for Entity Framework, only two events exist: ObjectMaterialized (after loading an entity from the database); SavingChanges (before saving changes, which include deleting, inserting and updating). Tracking Changes For NHibernate as well as Entity Framework, all changes are tracked by their respective Unit of Work implementation. Entities can be attached and detached to it, Entity Framework does, however, also support self-tracking entities. Optimistic Concurrency Control NHibernate supports all of the imaginable scenarios: SQL Server’s ROWVERSION; Oracle’s ORA_ROWSCN; A column containing date and time; A column containing a version number; All/dirty columns comparison. Entity Framework is more focused on Entity Framework, so it only supports: SQL Server’s ROWVERSION; Comparing all/some columns. Batching NHibernate has full support for insertion batching, but only if the ID generator in use is not database-based (for example, it cannot be used with Identity), whereas Entity Framework has no batching at all. Cascading Both support cascading for collections and associations: when an entity is deleted, their conceptual children are also deleted. NHibernate also offers the possibility to set the foreign key column on children to NULL instead of removing them. Flushing Changes NHibernate’s ISession has a FlushMode property that can have the following values: Auto: changes are sent to the database when necessary, for example, if there are dirty instances of an entity type, and a query is performed against this entity type, or if the ISession is being disposed; Commit: changes are sent when committing the current transaction; Never: changes are only sent when explicitly calling Flush(). As for Entity Framework, changes have to be explicitly sent through a call to AcceptAllChanges()/SaveChanges(). Lazy Loading NHibernate supports lazy loading for Associated entities (one to one, many to one); Collections (one to many, many to many); Scalar properties (thing of BLOBs or CLOBs). Entity Framework only supports lazy loading for: Associated entities; Collections. Generating and Updating the Database Both NHibernate and Entity Framework Code First (with the Migrations API) allow creating the database model from the mapping and updating it if the mapping changes. Extensibility As you can guess, NHibernate is far more extensible than Entity Framework. Basically, everything can be extended, from ID generation, to LINQ to SQL transformation, HQL native SQL support, custom column types, custom association collections, SQL generation, supported databases, etc. With Entity Framework your options are more limited, at least, because practically no information exists as to what can be extended/changed. It features a provider model that can be extended to support any database. Integration With Other Microsoft APIs and Tools When it comes to integration with Microsoft technologies, it will come as no surprise that Entity Framework offers the best support. For example, the following technologies are fully supported: ASP.NET (through the EntityDataSource); ASP.NET Dynamic Data; WCF Data Services; WCF RIA Services; Visual Studio (through the integrated designer). Documentation This is another point where Entity Framework is superior: NHibernate lacks, for starters, an up to date API reference synchronized with its current version. It does have a community mailing list, blogs and wikis, although not much used. Entity Framework has a number of resources on MSDN and, of course, several forums and discussion groups exist. Conclusion Like I said, this is a personal list. I may come as a surprise to some that Entity Framework is so behind NHibernate in so many aspects, but it is true that NHibernate is much older and, due to its open-source nature, is not tied to product-specific timeframes and can thus evolve much more rapidly. I do like both, and I chose whichever is best for the job I have at hands. I am looking forward to the changes in EF5 which will add significant value to an already interesting product. So, what do you think? Did I forget anything important or is there anything else worth talking about? Looking forward for your comments!

    Read the article

  • C# convert an IOrderedEnumerable<KeyValuePair<string, int>> into a Dictionary<string, int>

    - by Kache4
    I was following the answer to another question, and I got: // itemCounter is a Dictionary<string, int>, and I only want to keep // key/value pairs with the top maxAllowed values if (itemCounter.Count > maxAllowed) { IEnumerable<KeyValuePair<string, int>> sortedDict = from entry in itemCounter orderby entry.Value descending select entry; sortedDict = sortedDict.Take(maxAllowed); itemCounter = sortedDict.ToDictionary<string, int>(/* what do I do here? */); } Visual Studio's asking for a parameter Func<string, int> keySelector. I tried following a few semi-relevant examples I've found online and put in k => k.Key, but that gives a compiler error: 'System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string,int>>' does not contain a definition for 'ToDictionary' and the best extension method overload 'System.Linq.Enumerable.ToDictionary<TSource,TKey>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,TKey>)' has some invalid arguments

    Read the article

  • LIST<> AddRange throwing ArgumentException

    - by Tim
    Hi all, I have a particular method that is occasionally crashing with an ArgumentException: Destination array was not long enough. Check destIndex and length, and the array's lower bounds.: at System.Array.Copy(Array sourceArray, Int32 sourceIndex, Array destinationArray, Int32 destinationIndex, Int32 length, Boolean reliable) at System.Collections.Generic.List`1.CopyTo(T[] array, Int32 arrayIndex) at System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection) at System.Collections.Generic.List`1.AddRange(IEnumerable`1 collection) The code that is causing this crash looks something like this: List<MyType> objects = new List<MyType>(100); objects = FindObjects(someParam); objects.AddRange(FindObjects(someOtherParam); According to MSDN, List<.AddRange() should automatically resize itself as needed: If the new Count (the current Count plus the size of the collection) will be greater than Capacity, the capacity of the List<(Of <(T)) is increased by automatically reallocating the internal array to accommodate the new elements, and the existing elements are copied to the new array before the new elements are added. Can someone think of a circumstance in which AddRange could throw this type of exception?

    Read the article

  • Convert Java Arraylist return from Java WebService to C# Arraylist

    - by TTCG
    In my C# program, I would like to consume the Java Web Service Method which replies the java.Util.ArrayList. I don't know how to convert the Java ArrayList to C# ArrayList. This is Java Codes @WebMethod @WebResult(name = "GetLastMessages") @SuppressWarnings("unchecked") public ArrayList<Message> getLastMessages(@WebParam(name = "MessageCount")int count) { .... .... return messages; } This is C# Codes MessagesService.MessagesService service = new MessagesService.MessagesService(); System.Collections.ArrayList arr = (System.Collections.ArrayList)service.getLastMessages(10); I got the following Error in C# Cannot convert type 'WindowsFormsApplication1.MessagesService.arrayList' to 'System.Collections.ArrayList' How can I cast these Java ArrayList to C# ArrayList

    Read the article

  • java.lang.NoSuchMethodError: javax.persistence.OneToMany.orphanRemoval()Z

    - by Panayiotis Karabassis
    I am getting this error: java.lang.NoSuchMethodError: javax.persistence.OneToMany.orphanRemoval()Z These are the jars in my classpath: com.sun.faces/jsf-api/jars/jsf-api-2.0.0.jar com.sun.faces/jsf-impl/jars/jsf-impl-2.0.0.jar org.apache.myfaces.orchestra/myfaces-orchestra-core20/jars/myfaces-orchestra-core20-1.5-SNAPSHOT.jar commons-lang/commons-lang/jars/commons-lang-2.1.jar commons-logging/commons-logging/jars/commons-logging-1.1.1.jar org.springframework/spring/jars/spring-2.5.6.jar commons-el/commons-el/jars/commons-el-1.0.jar org.richfaces.ui/richfaces-ui/jars/richfaces-ui-3.3.3.Final.jar org.richfaces.framework/richfaces-api/jars/richfaces-api-3.3.3.Final.jar commons-collections/commons-collections/jars/commons-collections-3.2.jar commons-beanutils/commons-beanutils/jars/commons-beanutils-1.8.0.jar org.richfaces.framework/richfaces-impl-jsf2/jars/richfaces-impl-jsf2-3.3.3.Final.jar com.sun.facelets/jsf-facelets/jars/jsf-facelets-1.1.14.jar org.hibernate/hibernate-core/jars/hibernate-core-3.6.0.Final.jar antlr/antlr/jars/antlr-2.7.6.jar dom4j/dom4j/jars/dom4j-1.6.1.jar org.hibernate/hibernate-commons-annotations/jars/hibernate-commons-annotations-3.2.0.Final.jar org.slf4j/slf4j-api/jars/slf4j-api-1.6.1.jar org.hibernate.javax.persistence/hibernate-jpa-2.0-api/jars/hibernate-jpa-2.0-api-1.0.0.Final.jar javax.transaction/jta/jars/jta-1.1.jar org.hibernate/hibernate-c3p0/jars/hibernate-c3p0-3.6.0.Final.jar c3p0/c3p0/jars/c3p0-0.9.1.jar org.hibernate/hibernate-entitymanager/jars/hibernate-entitymanager-3.6.0.Final.jar cglib/cglib/jars/cglib-2.2.jar asm/asm/jars/asm-3.1.jar javassist/javassist/jars/javassist-3.12.0.GA.jar org.hibernate/hibernate-search/jars/hibernate-search-3.3.0.Final.jar org.hibernate/hibernate-search-analyzers/jars/hibernate-search-analyzers-3.3.0.Final.jar org.apache.lucene/lucene-core/jars/lucene-core-3.0.3.jar org.apache.lucene/lucene-analyzers/jars/lucene-analyzers-3.0.3.jar mysql/mysql-connector-java/jars/mysql-connector-java-5.1.13.jar com.ocpsoft/prettyfaces-jsf2/jars/prettyfaces-jsf2-3.0.1.jar commons-digester/commons-digester/jars/commons-digester-2.0.jar org.slf4j/slf4j-log4j12/jars/slf4j-log4j12-1.6.1.jar log4j/log4j/bundles/log4j-1.2.16.jar xom/xom/jars/xom-1.2.5.jar xml-apis/xml-apis/jars/xml-apis-1.3.03.jar xerces/xercesImpl/jars/xercesImpl-2.8.0.jar xalan/xalan/jars/xalan-2.7.0.jar org.jboss.jsfunit/jboss-jsfunit-core/jars/jboss-jsfunit-core-1.3.0.Final.jar net.sourceforge.htmlunit/htmlunit/jars/htmlunit-2.8.jar xalan/xalan/jars/xalan-2.7.1.jar xalan/serializer/jars/serializer-2.7.1.jar xml-apis/xml-apis/jars/xml-apis-1.3.04.jar commons-collections/commons-collections/jars/commons-collections-3.2.1.jar commons-lang/commons-lang/jars/commons-lang-2.4.jar org.apache.httpcomponents/httpclient/jars/httpclient-4.0.1.jar org.apache.httpcomponents/httpcore/jars/httpcore-4.0.1.jar commons-codec/commons-codec/jars/commons-codec-1.4.jar org.apache.httpcomponents/httpmime/jars/httpmime-4.0.1.jar org.apache.james/apache-mime4j/jars/apache-mime4j-0.6.jar net.sourceforge.htmlunit/htmlunit-core-js/jars/htmlunit-core-js-2.8.jar xerces/xercesImpl/jars/xercesImpl-2.9.1.jar net.sourceforge.nekohtml/nekohtml/jars/nekohtml-1.9.14.jar net.sourceforge.cssparser/cssparser/jars/cssparser-0.9.5.jar org.w3c.css/sac/jars/sac-1.3.jar commons-io/commons-io/jars/commons-io-1.4.jar cactus/cactus/jars/cactus-13-1.7.1.jar cactus/cactus-ant/jars/cactus-ant-13-1.7.1.jar commons-httpclient/commons-httpclient/jars/commons-httpclient-2.0.2.jar junit/junit/jars/junit-3.8.1.jar aspectj/aspectjrt/jars/aspectjrt-1.2.1.jar cargo/cargo/jars/cargo-0.5.jar ant/ant/jars/ant-1.5.4.jar and this is my ivy.xml: <dependencies> <!-- JSF 2.0 RI --> <dependency org="com.sun.faces" name="jsf-api" rev="2.0.0"/> <dependency org="com.sun.faces" name="jsf-impl" rev="2.0.0"/> <!-- MyFaces Orchestra --> <dependency org="org.apache.myfaces.orchestra" name="myfaces-orchestra-core20" rev="1.5-SNAPSHOT"/> <dependency org="org.springframework" name="spring" rev="2.5.6"/> <dependency org="commons-el" name="commons-el" rev="1.0"/> <!-- RichFaces --> <dependency org="org.richfaces.ui" name="richfaces-ui" rev="3.3.3.Final"/> <dependency org="org.richfaces.framework" name="richfaces-impl-jsf2" rev="3.3.3.Final"/> <dependency org="com.sun.facelets" name="jsf-facelets" rev="1.1.14"/> <!-- Hibernate --> <dependency org="org.hibernate" name="hibernate-core" rev="3.6.0.Final"/> <dependency org="org.hibernate" name="hibernate-c3p0" rev="3.6.0.Final"/> <dependency org="org.hibernate" name="hibernate-entitymanager" rev="3.6.0.Final"/> <dependency org="org.hibernate" name="hibernate-search" rev="3.3.0.Final"/> <dependency org="mysql" name="mysql-connector-java" rev="5.1.13"/> <!-- PrettyFaces --> <dependency org="com.ocpsoft" name="prettyfaces-jsf2" rev="3.0.1"/> <!-- SLF4J --> <dependency org="org.slf4j" name="slf4j-api" rev="1.6.1"/> <dependency org="org.slf4j" name="slf4j-log4j12" rev="1.6.1"/> <!-- XOM --> <dependency org="xom" name="xom" rev="1.2.5"/> <!-- JSF Unit --> <dependency org="org.jboss.jsfunit" name="jboss-jsfunit-core" rev="1.3.0.Final" conf="development"/> </dependencies> I am deploying to tomcat 6.0 Update After the answer below, I solved this by adding the following dependency to my ivy.xml: <dependency org="org.hibernate.javax.persistence" name="hibernate-jpa-2.0-api" rev="1.0.0.Final"/> then putting this jar above everything else under Eclipse's build order tab. I was using JRE/JDK 6.

    Read the article

< Previous Page | 22 23 24 25 26 27 28 29 30 31 32 33  | Next Page >