EzDevInfo.com

mapping interview questions

Top mapping frequently asked interview questions

What is the ideal data type to use when storing latitude / longitudes in a MySQL database?

Bearing in mind that I'll be performing calculations on lat / long pairs, what datatype is best suited for use with a MySQL database?


Source: (StackOverflow)

What is the difference between the remap, noremap, nnoremap and vnoremap mapping commands in vim?

What is the difference between the remap, noremap, nnoremap and vnoremap mapping commands in vim?


Source: (StackOverflow)

Advertisements

How do I map ctrl x ctrl o to ctrl space in terminal vim?

After searching a bit on the net it seems that I can't map CtrlSpace to anything/alot. Is there a way to do it today, what I found was usually 2 years old.


Source: (StackOverflow)

How to introduce multi-column constraint with JPA annotations?

I am trying to introduce a multi-key constraint on a JPA-mapped entity:

public class InventoryItem {
    @Id
    private Long id;

    @Version 
    private Long version;

    @ManyToOne
    @JoinColumn("productId")
    private Product product;

    @Column(nullable=false);
    private long serial;
}

Basically (product, serial) pair should be unique, but I only found a way to say that serial should be unique. This obviously isn't a good idea since different products might have same serial numbers.

Is there a way to generate this constraint via JPA or am I forced to manually create it to DB?


Source: (StackOverflow)

Mapping object to dictionary and vice versa

Are there any elegant quick way to map object to a dictionary and vice versa?

Example:

IDictionary<string,object> a = new Dictionary<string,object>();
a["Id"]=1;
a["Name"]="Ahmad";
// .....

becomes

SomeClass b = new SomeClass();
b.Id=1;
b.Name="Ahmad";
// ..........

Source: (StackOverflow)

How to force Hibernate to return dates as java.util.Date instead of Timestamp?

Situation:

I have a persistable class with variable of java.util.Date type:

import java.util.Date;

@Entity
@Table(name = "prd_period")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Period extends ManagedEntity implements Interval {

   @Column(name = "startdate_", nullable = false)
   private Date startDate;

}

Corresponding table in DB:

CREATE TABLE 'prd_period' (
  'id_' bigint(20) NOT NULL AUTO_INCREMENT,
 ...
  'startdate_' datetime NOT NULL
)

Then I save my Period object to DB:

Period p = new Period();
Date d = new Date();
p.setStartDate();
myDao.save(p);

After then if I'm trying to extract my object from DB, it is returned with variable startDate of Timestamp type - and all the places where I'm trying to use equals(...) are returning false.

Question: are there any means to force Hibernate to return dates as object of java.util.Date type instead of Timestamp without explicit modification of every such variable (e.g it must be able just work, without explicit modification of existed variables of java.util.Date type)?

NOTE:

I found number of explicit solutions, where annotations are used or setter is modified - but I have many classes with Date-variables - so I need some centralized solution and all that described below is not good enough:

  1. Using annotation @Type: - java.sql.Date will be returned

    @Column
    @Type(type="date")
    private Date startDate;
    
  2. Using annotation @Temporal(TemporalType.DATE) - java.sql.Date will be returned

    @Temporal(TemporalType.DATE)
    @Column(name=”CREATION_DATE”)
    private Date startDate;
    
  3. By modifying setter (deep copy) - java.util.Date will be returned

    public void setStartDate(Date startDate) {
        if (startDate != null) {
            this.startDate = new Date(startDate.getTime());
        } else {
            this.startDate = null;
        }
    }
    
  4. By creation of my own type: - java.util.Date will be returned

Details are given here: http://blogs.sourceallies.com/2012/02/hibernate-date-vs-timestamp/


Source: (StackOverflow)

python class that acts as mapping for **unpacking

Without subclassing dict, what would a class need to be considered a mapping so that it can be passed to a method with **

from abc import ABCMeta

class uobj:
    __metaclass__ = ABCMeta

uobj.register(dict)

def f(**k): return k

o = uobj()
f(**o)

# outputs: f() argument after ** must be a mapping, not uobj

At least to the point where it throws errors of missing functionality of mapping, so I can begin implementing.

I reviewed emulating container types but simply defining magic methods has no effect, and using ABCMeta to override and register it as a dict validates assertions as subclass, but fails isinstance(o, dict). Ideally, I dont even want to use ABCMeta.


Source: (StackOverflow)

Entity Framework 4.1 InverseProperty Attribute and ForeignKey

I will create two references between Employee and Team entities with foreign keys. So I defined two entities as follow

public class Employee
{
    public int EmployeeId { get; set; }
    public string Name { get; set; }

    [ForeignKey("FirstTeam")]
    public int FirstTeamId { get; set; }

    [InverseProperty("FirstEmployees")]
    public virtual Team FirstTeam { get; set; }

    [ForeignKey("SecondTeam")]
    public int SecondTeamId { get; set; }

    [InverseProperty("SecondEmployees")]
    public virtual Team SecondTeam { get; set; }
}

public class Team
{
    public int Id { get; set; }
    public string TeamName { get; set; }

    [InverseProperty("FirstTeam")]
    public virtual ICollection<Employee> FirstEmployees { get; set; }

    [InverseProperty("SecondTeam")]
    public virtual ICollection<Employee> SecondEmployees { get; set; }
}

I thought it is correct theoretically, but it shows the Exception as follow :

{"Introducing FOREIGN KEY constraint 'Employee_SecondTeam' on table 'Employees' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.\r\nCould not create constraint. See previous errors."}

Can anybody help me?

Thanks in advance Kwon


Source: (StackOverflow)

Object to object mapper

I've used plenty of ORM tools in the past, NHibernate, .netTiers, LLBLGen and more and they always do a pretty good job of mapping data from a database to objects in code.

What I'm looking for though is a framework or a pattern or something that will allow me to transform objects from one type to another.

An example is I have a two web services, one has Investors another has Members. I want to convert an Investor object to a Member object by defining a set of rules that maps the Investor properties to the Member properties and back again.

NHibernate mappings are the closest I can get to doing this, but it only seems to work for Database -> Object mappings. I was wondering if anyone knew of any products that allowed me to do obejct -> object mapping?


Source: (StackOverflow)

EF Mapping and metadata information could not be found for EntityType Error

I have encountered an exception when I using Entity Framework 4.0 RC. My Entity Framework model is encapsulated in a private assembly whos name is Procurement.EFDataProvider and my POCO are inside of another assembly Procurement.Core The relation between Core(Business Logic)and EFDataProvider(Data Access) is with a factory named DataProvider

so when I try to create an objectset

objectSet = ObjectContext.CreateObjectSet<TEntity>();

I got an error:

Mapping and metadata information could not be found for EntityType 'Procurement.Core.Entities.OrganizationChart'.


Source: (StackOverflow)

Simple way to subset SpatialPolygonsDataFrame (i.e. delete polygons) by attribute in R

I would like simply delete some polygons from a SpatialPolygonsDataFrame object based on corresponding attribute values in the @data data frame so that I can plot a simplified/subsetted shapefile. So far I haven't found a way to do this.

For example, let's say I want to delete all polygons from this world shapefile that have an area of less than 30000. How would I go about doing this?

Or, similarly, how can I delete Antartica?

require(maptools)

getinfo.shape("TM_WORLD_BORDERS_SIMPL-0.3.shp") 
# Shapefile type: Polygon, (5), # of Shapes: 246
world.map <- readShapeSpatial("TM_WORLD_BORDERS_SIMPL-0.3.shp")

class(world.map)
# [1] "SpatialPolygonsDataFrame"
# attr(,"package")
# [1] "sp"

head(world.map@data)
#   FIPS ISO2 ISO3 UN                NAME   AREA  POP2005 REGION SUBREGION     LON     LAT
# 0   AC   AG  ATG 28 Antigua and Barbuda     44    83039     19        29 -61.783  17.078
# 1   AG   DZ  DZA 12             Algeria 238174 32854159      2        15   2.632  28.163
# 2   AJ   AZ  AZE 31          Azerbaijan   8260  8352021    142       145  47.395  40.430
# 3   AL   AL  ALB  8             Albania   2740  3153731    150        39  20.068  41.143
# 4   AM   AM  ARM 51             Armenia   2820  3017661    142       145  44.563  40.534
# 5   AO   AO  AGO 24              Angola 124670 16095214      2        17  17.544 -12.296

If I do something like this, the plot does not reflect any changes.

world.map@data = world.map@data[world.map@data$AREA > 30000,]
plot(world.map)

same result if I do this:

world.map@data = world.map@data[world.map@data$NAME != "Antarctica",]
plot(world.map)

Any help is appreciated!


Source: (StackOverflow)

No mapping found for field in order to sort on in ElasticSearch

Elasticsearch throws a SearchParseException while parsing query if there are some documents found not containing field used in sort criteria.

SearchParseException: Parse Failure [No mapping found for [price] in order to sort on]

How can I successfully search these documents, even if some are missing the price field?


Source: (StackOverflow)

any tool for java object to object mapping? [closed]

Friends, I am trying to convert DO to DTO using java and looking for automated tool before start writing my own. I just wanted to know if there any free tool available for the same.


Source: (StackOverflow)

How can I merge two Python dictionaries in a single expression?

I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The update() method would be what I need, if it returned its result instead of modifying a dict in-place.

>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = x.update(y)
>>> print z
None
>>> x
{'a': 1, 'b': 10, 'c': 11}

How can I get that final merged dict in z, not x?

(To be extra-clear, the last-one-wins conflict-handling of dict.update() is what I'm looking for as well.)


Source: (StackOverflow)

Mapping a NumPy array in place

Is it possible to map a NumPy array in place? If yes, how?

Given a_values - 2D array - this is the bit of code that does the trick for me at the moment:

for row in range(len(a_values)):
    for col in range(len(a_values[0])):
        a_values[row][col] = dim(a_values[row][col])

But it's so ugly that I suspect that somewhere within NumPy there must be a function that does the same with something looking like:

a_values.map_in_place(dim)

but if something like the above exists, I've been unable to find it.


Source: (StackOverflow)