How to create Linkedhashset using Hashset? - linkedhashset

I was asked this question during my interview "How to create Linkedhashset using Hashset ?" anyone knows the answer ?

The LinkedHashSet class has a public LinkedHashSet(Collection<? extends E> c) constructor, so you could do
HashSet<Foo> hs = new HashSet<Foo>();
// add items...
LinkedHashSet<Foo> lhs = new LinkedHashSet<Foo>(hs);
to get a LinkedHashSet instance with the same content as hs. Note that there is no guarantee that the items from hs are inserted into lhs in the same order they were inserted into hs, since that information was never saved by hs.
There is no way to make "an HashSet which behaves like LinkedHashSet", that is, an instance of runtime class HashSet that behaves like a LinkedHashSet instance. However, you could do
HashSet<Foo> hs = new LinkedHashSet<Foo>();
which would give you an instance that would be seen by the outside world as a plain HashSet but use the LinkedHashSet implementation internally. I fail to see why you would ever want to do that, though - you would only gain a bunch of overhead and no added functionality, since the declared type is HashSet. The reason you'd want to use a LinkedHashSet in the first place is to be guaranteed the predictable iteration order, but you still wouldn't be able to assume that for hs - you could assign hs = new HashSet<Foo>() at any time, for instance.

Related

How to add a copy of an object instead of reference to it

So - I am doping a loop in F# with some complex logic in it so I am using a System.Collections.Generic.List so I can add to it in the loop.
What I am finding though - is that when I add an item to the list - it still somehow has a reference to the variable so when I change the "currentPostCodeRange" variable, then all of the previous additions to the list are changed as well! is there a way I can assign a "copy" of the variable somehow so it doesn't reference every single item..?
let postcodeRanges: System.Collections.Generic.List<Postcode.PostcodeRange>
= new System.Collections.Generic.List<Postcode.PostcodeRange>()
let mutable currentPostCodeRange: Postcode.PostcodeRange = { RangeType = Postcode.RangeType.Normal; From="0001"; To="0001" }
Loop:
for postCode in 1 .. 9999 do
.....
if nextPostCodeisRural <> thisPostCodeisRural then
// this is the last one in this Range
currentPostCodeRange.To <- thisPostCodeString
postcodeRanges.Add(currentPostCodeRange)
.... etc, other logic
I think the easiest way to copy a record in F# is with a copy and update record expression. I strongly recommend against adding mutable objects to collections, though, precisely because it creates the aliasing problem you're seeing here. However, if you're determined to do it, you can add a copy like this:
postcodeRanges.Add({ currentPostCodeRange with To = currentPostCodeRange.To })
You have to include at least one field in the expression, so in this case, I've explicitly copied the To field, and implicitly copied the rest. It doesn't matter which one you pick.
Again, I strongly recommend against this sort of design. I think you're better off in the long run using a scan, or some other functional technique.

RxSwift - Class property's binding

I have an question about binding:
I have an array of objects of my custom class: Array. Every object can be updated (change his properties value) in bg.
Also I have separated Controller, which take and store one object from list as variable and can update it (object still the same, so in list it will be updated too)
Is there any way to bind all object.property -> UILabels on Controller in way, when property changes automatically call label update?
Of course, there are multiple ways how to do it, but from your description I would use some kind of subject (because u said there will be changes in background so you will probably need hot observable )....For example Variable or PublishSubject. So you can crate
let myArrayStream: Variable<[MyObject]> = Variable([])
you can pass this variable as dependency to wherever you want, on one side you can subscribe to it, on the other side you can update it's value.

How can I insert objects into a DOORS module via DXL?

I read through the DOORS Reference Manual but couldn't find a simple insert method. I'm looking to insert an object, which was created within my DXL script, into a module.
I was hoping to find something intuitive like
insert_object_after(Module m, Object o, string object_identifier)
which would scan the module for the specified object identifier and insert the object after finding that identifier. Does such a function exist? If not how could I go about performing the action I've described?
Some basic example code would be awesome.
Chapter „Object management“. Use one of the commands
Object create(Module m)
Object create(Object o)
Object create(after(Object o))
Object create(before(Object o))
Object create(below(Object o))
Object create(first(below(Object o)))
Object create(last(below(Object o)))
For these functions, you need a variable of type Object. There are several ways to fill such a variable, look at the chapters „Finding objects“ and „Navigation from an object“. Probably the easiest way would be to use the function Object object(int absno[,Module m]) (with absno being the absolute number of the „source“ object. But beware that object only works if the current filter allows to navigate to this object, so, if the function "Go To“ from the menu works in your current view with your source object, then object should work as well

Lazy fetching of objects using FindAllBy , for the first time

When I use criteria queries, the result contains array list of lazy initialized objects. that is, the list has values with handler org.codehaus.groovy.grails.orm.hibernate.proxy.GroovyAwareJavassistLazyInitializer.
This prevent me from doing any array operation (minus, remove etc) in it. When I use, GORM methods, I get array list of actual object types. How can I get the actual objects in criteria query?
The code is listed below.
availableTypes = Type.withCriteria() {
'in'("roleFrom", from)
'in'("roleTo", to)
}
availableTypes (an array list) has one value , but not actual object but value with a handler of GroovyAwareJavassistLazyInitializer
availableTypes (an array list) has values with type Type
availableTypes = Type.findByRoleFrom(from)
---------- Update ----------
I did further troubleshooting, and this is what I found. Probably the above description might be misleading, but I kept it in case it helps.
When using findAllBy for the first time, I get proxy objects rather than the actual instance. Then, I invoke the method through an ajax call, the actual instance is loaded (anything to do with cache loading??). When I refresh the page, it again loads the proxy
def typeFrom = Type.findAllByParty(partyFrom)
there is another use of findAllBy in the same method, which always returns actual instances.
def relFrom = Relation.findAllByParty(partyFrom)
When compared the two classes, the attribute 'party' of class Roles is part of a 1-m relation. like
class Role {
RoleType roleType
LocalDate validFrom
LocalDate validTo
static belongsTo = [party : Party ]
...
}
I know if I do statement like Party.findAll(), the role instances would be proxy till they access. But, when using gorm directly on the class (Role), why I am getting the proxy objects ???
thanks for the help.
thanks.
Turns out are a couple of possible solutions which I came across but didn't try, such as
Overloading the equals method so that the proxy and the domain
object use a primary key instead of the hashCode for equality
Using a join query so that you get actual instances back and not proxies
GrailsHibernateUtil.unwrapProxy(o)
HibernateProxyHelper.getClassWithoutInitializingProxy(object)
One solution that worked for me was to specify lazy loading to be false in the domain object mapping.
History of this problem seems to be discussed here: GRAILS-4614
See also: eager load

Code re-use with Linq-to-Sql - Creating 'generic' look-up tables

I'm working on an application at the moment in ASP.NET MVC which has a number of look-up tables, all of the form
LookUp {
Id
Text
}
As you can see, this just maps the Id to a textual value. These are used for things such as Colours. I now have a number of these, currently 6 and probably soon to be more.
I'm trying to put together an API that can be used via AJAX to allow the user to add/list/remove values from these lookup tables, so for example I could have something like:
http://example.com/Attributes/Colours/[List/Add/Delete]
My current problem is that clearly, regardless of which lookup table I'm using, everything else happens exactly the same. So really there should be no repetition of code whatsoever.
I currently have a custom route which points to an 'AttributeController', which figures out the attribute/look-up table in question based upon the URL (ie http://example.com/Attributes/Colours/List would want the 'Colours' table). I pass the attribute (Colours - a string) and the operation (List/Add/Delete), as well as any other parameters required (say "Red" if I want to add red to the list) back to my repository where the actual work is performed.
Things start getting messy here, as at the moment I've resorted to doing a switch/case on the attribute string, which can then grab the Linq-to-Sql entity corresponding to the particular lookup table. I find this pretty dirty though as I find myself having to write the same operations on each of the look-up entities, ugh!
What I'd really like to do is have some sort of mapping, which I could simply pass in the attribute name and get out some form of generic lookup object, which I could perform the desired operations on without having to care about type.
Is there some way to do this to my Linq-To-Sql entities? I've tried making them implement a basic interface (IAttribute), which simply specifies the Id/Text properties, however doing things like this fails:
System.Data.Linq.Table<IAttribute> table = GetAttribute("Colours");
As I cannot convert System.Data.Linq.Table<Colour> to System.Data.Linq.Table<IAttribute>.
Is there a way to make these look-up tables 'generic'?
Apologies that this is a bit of a brain-dump. There's surely imformation missing here, so just let me know if you'd like any further details. Cheers!
You have 2 options.
Use Expression Trees to dynamically create your lambda expression
Use Dynamic LINQ as detailed on Scott Gu's blog
I've looked at both options and have successfully implemented Expression Trees as my preferred approach.
Here's an example function that i created: (NOT TESTED)
private static bool ValueExists<T>(String Value) where T : class
{
ParameterExpression pe = Expression.Parameter(typeof(T), "p");
Expression value = Expression.Equal(Expression.Property(pe, "ColumnName"), Expression.Constant(Value));
Expression<Func<T, bool>> predicate = Expression.Lambda<Func<T, bool>>(value, pe);
return MyDataContext.GetTable<T>().Where(predicate).Count() > 0;
}
Instead of using a switch statement, you can use a lookup dictionary. This is psuedocode-ish, but this is one way to get your table in question. You'll have to manually maintain the dictionary, but it should be much easier than a switch.
It looks like the DataContext.GetTable() method could be the answer to your problem. You can get a table if you know the type of the linq entity that you want to operate upon.
Dictionary<string, Type> lookupDict = new Dictionary<string, Type>
{
"Colour", typeof(MatchingLinqEntity)
...
}
Type entityType = lookupDict[AttributeFromRouteValue];
YourDataContext db = new YourDataContext();
var entityTable = db.GetTable(entityType);
var entity = entityTable.Single(x => x.Id == IdFromRouteValue);
// or whatever operations you need
db.SubmitChanges()
The Suteki Shop project has some very slick work in it. You could look into their implementation of IRepository<T> and IRepositoryResolver for a generic repository pattern. This really works well with an IoC container, but you could create them manually with reflection if the performance is acceptable. I'd use this route if you have or can add an IoC container to the project. You need to make sure your IoC container supports open generics if you go this route, but I'm pretty sure all the major players do.

Resources