EzDevInfo.com

Set

An implementation of Multiset and PredicateSet in Swift.

What is the difference between Set and List?

What is the fundamental difference between the Set<E> and List<E> interfaces?


Source: (StackOverflow)

Advertisements

Convert Set to List without creating new List

I am using this code to convert a Set to a List:

Map<String, List> mainMap = new HashMap<String, List>();

for(int i=0; i<something.size(); i++){
  Set set = getSet(...); //return different result each time
  List listOfNames = new ArrayList(set);
  mainMap.put(differentKeyName,listOfNames);
}

I want to avoid creating a new list in each iteration of the loop. Is that possible?


Source: (StackOverflow)

Is there any kind of hash code function in JavaScript?

Basically, I'm trying to create an object of unique objects, a set. I had the brilliant idea of just using a JavaScript object with objects for the property names. Such as,

set[obj] = true;

This works, up to a point. It works great with string and numbers, but with other objects, they all seem to "hash" to the same value and access the same property. Is there some kind of way I can generate a unique hash value for an object? How do strings and numbers do it, can I override the same behavior?


Source: (StackOverflow)

Empty set literal in Python?

[] = empty list

() = empty tuple

{} = empty dict

Is there a similar notation for an empty set? Or do I have to write set()?


Source: (StackOverflow)

Difference between Iterator and Listiterator?

Iterator ite = Set.iterator();
Iterator ite = List.iterator();

ListIterator listite = List.listIterator();

We can use Iterator to traverse a Set or a List or a Map. But ListIterator can only be used to traverse a List, it can't traverse a Set. Why?

I know that the main difference is that with iterator we can travel in only one direction but with ListIterator we can travel both directions. Are there any other differences? And any advantages of ListIterator over Iterator?


Source: (StackOverflow)

How is set() implemented?

I've seen people say that set objects in python have O(1) membership-checking. How are they implemented internally to allow this? What sort of data structure does it use? What other implications does that implementation have?

Every answer here was really enlightening, but I can only accept one, so I'll go with the closest answer to my original question. Thanks all for the info!


Source: (StackOverflow)

Python: Add list to set?

Tested on Python 2.6 interpreter:

>>> a=set('abcde')
>>> a
set(['a', 'c', 'b', 'e', 'd'])
>>> l=['f','g']
>>> l
['f', 'g']
>>> a.add(l)
Traceback (most recent call last):
  File "<pyshell#35>", line 1, in <module>
    a.add(l)
TypeError: list objects are unhashable

I think that I can't add the list to the set because there's no way Python can tell If I have added the same list twice. Is there a workaround?

EDIT: I want to add the list itself, not its elements.


Source: (StackOverflow)

Getting an element from a Set

Why doesn't Set povide an operation to get an element that equals another element?

Set<Foo> set = ...;
...
Foo foo = new Foo(1, 2, 3);
Foo bar = set.get(foo);   // get the Foo element from the Set that equals foo

I can ask whether the Set contains an element equal to bar, so why can't I get that element? :(

To clarify, the equals method is overriden, but it only checks one of the fields, not all. So two Foo objects that are considered equal can actually have different values, that's why I can't just use foo.


Source: (StackOverflow)

Python: How to "perfectly" override a dict

How can I make as "perfect" a subclass of dict as possible? The end goal is to have a simple dict in which the keys are lowercase.

It would seem that should be some tiny set of primitives I can override to make this work, but all my research and attempts have made it seem like this isn't the case:

Here is my first go at it, get() doesn't work at least, and no doubt there are many minor subtle problems:

class arbitrary_dict(dict):
    """A dictionary that applies an arbitrary key-altering function
       before accessing the keys."""

    def __keytransform__(self, key):
        return key

    # Overridden methods. List from 
    # http://stackoverflow.com/questions/2390827/how-to-properly-subclass-dict

    def __init__(self, *args, **kwargs):
        self.update(*args, **kwargs)

    # Note: I'm using dict directly, since super(dict, self) doesn't work.
    # I'm not sure why, perhaps dict is not a new-style class.

    def __getitem__(self, key):
        return dict.__getitem__(self, self.__keytransform__(key))

    def __setitem__(self, key, value):
        return dict.__setitem__(self, self.__keytransform__(key), value)

    def __delitem__(self, key):
        return dict.__delitem__(self, self.__keytransform__(key))

    def __contains__(self, key):
        return dict.__contains__(self, self.__keytransform__(key))


class lcdict(arbitrary_dict):
    def __keytransform__(self, key):
        return str(key).lower()

Source: (StackOverflow)

Different types of thread-safe Sets in Java

There seems to be a lot of different implementations and ways to generate thread-safe Sets in Java. Some examples include

1) CopyOnWriteArraySet

2) Collections.synchronizedSet(Set set)

3) ConcurrentSkipListSet

4) Collections.newSetFromMap(new ConcurrentHashMap())

5) Other Sets generated in a way similar to (4)

These examples come from Concurrency Pattern: Concurrent Set implementations in Java 6

Could someone please simply explain the differences, advantages, and disadvantage of these examples and others? I'm having trouble understanding and keeping straight everything from the Java Std Docs.


Source: (StackOverflow)

Set value of hidden field in a form using jQuery's ".val()" doesn't work

I've been trying to set the value of a hidden field in a form using jQuery, but without success.

Here is a sample code that explains the problem. If I keep the input type to "text", it works without any trouble. But, changing the input type to "hidden", doesn't work !

<html>

    <head>
        <script type="text/javascript" src="jquery.js">
        </script>
        <script type="text/javascript">
            $(document).ready(function() {
                $("button").click(function() {
                    $("#texens").val("tinkumaster");
                });
            });
        </script>
    </head>

    <body>
        <p>
            Name:
            <input type="hidden" id="texens" name="user" value="texens" />
        </p>
        <button>
            Change value for the text field
        </button>
    </body>

</html>

I also tried the following workaround, by setting the input type to "text" and then using a "display:none" style for the input box. But, this also fails ! It seems jQuery has some trouble setting hidden or invisible input fields.

Any ideas? Is there a workaround for this that actually works?


Source: (StackOverflow)

how best do I find the intersection of multiple sets in python?

I have a list of sets:

setlist = [s1,s2,s3...]

I want s1 ∩ s2 ∩ s3 ...

I can write a function to do it by performing a series of pairwise s1.intersection(s2), etc.

Is there a recommended, better, or built-in way?


Source: (StackOverflow)

How to set background color of a View

I'm trying to set the background color of a View (in this case a Button).

I use this code:

// set the background to green
v.setBackgroundColor(0x0000FF00 );
v.invalidate();

It causes the Button to disappear from the screen. What am I doing wrong, and what is the correct way to change the background color on any View?

Thanks.


Source: (StackOverflow)

How to Iterate over a Set/HashSet without a Iterator?

How can iterate over a Set/HashSet without this?

Iterator iter = set.iterator();
while (iter.hasNext()) {
    System.out.println(iter.next());
}

Source: (StackOverflow)