Search Results

Search found 547 results on 22 pages for 'hashmap'.

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

  • Response Time is different for mulitiple execution of the application with the same request Performa

    - by sivananda
    My java application functionality is to provide reference data (basically loads lots of data from xml files into hashmap) and hence we request for one such data from the hashmap based on a id and we have such multiple has map for different set of business data. The problem is that when i tried executing the java application for the same request multiple times, the response times are different like 31ms, 48ms, 72ms, 120ms, 63ms etc. hence there is a considerable gap between the min and max time taken for the execution to complete. Ideally, i would expect the response times to be like, 63ms, 65ms, 61ms, 70ms, 61ms, but in my case the variation of the response time for the same request is varying hugely. I had used a opensource profile to understand if there is any extra execution of the methods or memory leak, but as per my understanding there was no problem. Please let me know what could be the reasons and how can i address this problem.

    Read the article

  • Error when call 'qb.query(db, projection, selection, selectionArgs, null, null, orderBy);'

    - by smalltalk1960s
    Hi all, I make a content provider named 'DictionaryProvider' (Based on NotepadProvider). When my program run to command 'qb.query(db, projection, selection, selectionArgs, null, null, orderBy);', error happen. I don't know how to fix. please help me. Below is my code // file main calling DictionnaryProvider @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dictionary); final String[] PROJECTION = new String[] { DicColumns._ID, // 0 DicColumns.KEY_WORD, // 1 DicColumns.KEY_DEFINITION // 2 }; Cursor c = managedQuery(DicColumns.CONTENT_URI, PROJECTION, null, null, DicColumns.DEFAULT_SORT_ORDER); String str = ""; if (c.moveToFirst()) { int wordColumn = c.getColumnIndex("KEY_WORD"); int defColumn = c.getColumnIndex("KEY_DEFINITION"); do { // Get the field values str = ""; str += c.getString(wordColumn); str +="\n"; str +=c.getString(defColumn); } while (c.moveToNext()); } Toast.makeText(this, str, Toast.LENGTH_SHORT).show(); } // file DictionaryProvider.java package com.example.helloandroid; import java.util.HashMap; import android.content.ContentProvider; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; import com.example.helloandroid.Dictionary.DicColumns; public class DictionaryProvider extends ContentProvider { //private static final String TAG = "DictionaryProvider"; private DictionaryOpenHelper dbdic; static final int DATABASE_VERSION = 1; static final String DICTIONARY_DATABASE_NAME = "dictionarydb"; static final String DICTIONARY_TABLE_NAME = "dictionary"; private static final UriMatcher sUriMatcher; private static HashMap<String, String> sDicProjectionMap; @Override public int delete(Uri arg0, String arg1, String[] arg2) { // TODO Auto-generated method stub return 0; } @Override public String getType(Uri arg0) { // TODO Auto-generated method stub return null; } @Override public Uri insert(Uri arg0, ContentValues arg1) { // TODO Auto-generated method stub return null; } @Override public boolean onCreate() { // TODO Auto-generated method stub dbdic = new DictionaryOpenHelper(getContext(), DICTIONARY_DATABASE_NAME, null, DATABASE_VERSION); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); qb.setTables(DICTIONARY_TABLE_NAME); switch (sUriMatcher.match(uri)) { case 1: qb.setProjectionMap(sDicProjectionMap); break; case 2: qb.setProjectionMap(sDicProjectionMap); qb.appendWhere(DicColumns._ID + "=" + uri.getPathSegments().get(1)); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } // If no sort order is specified use the default String orderBy; if (TextUtils.isEmpty(sortOrder)) { orderBy = DicColumns.DEFAULT_SORT_ORDER; } else { orderBy = sortOrder; } // Get the database and run the query SQLiteDatabase db = dbdic.getReadableDatabase(); Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy); // Tell the cursor what uri to watch, so it knows when its source data changes c.setNotificationUri(getContext().getContentResolver(), uri); return c; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { // TODO Auto-generated method stub return 0; } static { sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); sUriMatcher.addURI(Dictionary.AUTHORITY, "dictionary", 1); sUriMatcher.addURI(Dictionary.AUTHORITY, "dictionary/#", 2); sDicProjectionMap = new HashMap<String, String>(); sDicProjectionMap.put(DicColumns._ID, DicColumns._ID); sDicProjectionMap.put(DicColumns.KEY_WORD, DicColumns.KEY_WORD); sDicProjectionMap.put(DicColumns.KEY_DEFINITION, DicColumns.KEY_DEFINITION); // Support for Live Folders. /*sLiveFolderProjectionMap = new HashMap<String, String>(); sLiveFolderProjectionMap.put(LiveFolders._ID, NoteColumns._ID + " AS " + LiveFolders._ID); sLiveFolderProjectionMap.put(LiveFolders.NAME, NoteColumns.TITLE + " AS " + LiveFolders.NAME);*/ // Add more columns here for more robust Live Folders. } } // file Dictionary.java package com.example.helloandroid; import android.net.Uri; import android.provider.BaseColumns; /** * Convenience definitions for DictionaryProvider */ public final class Dictionary { public static final String AUTHORITY = "com.example.helloandroid.provider.Dictionary"; // This class cannot be instantiated private Dictionary() {} /** * Dictionary table */ public static final class DicColumns implements BaseColumns { // This class cannot be instantiated private DicColumns() {} /** * The content:// style URL for this table */ public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/dictionary"); /** * The MIME type of {@link #CONTENT_URI} providing a directory of notes. */ //public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.note"; /** * The MIME type of a {@link #CONTENT_URI} sub-directory of a single note. */ //public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.google.note"; /** * The default sort order for this table */ public static final String DEFAULT_SORT_ORDER = "modified DESC"; /** * The key_word of the dictionary * <P>Type: TEXT</P> */ public static final String KEY_WORD = "KEY_WORD"; /** * The key_definition of word * <P>Type: TEXT</P> */ public static final String KEY_DEFINITION = "KEY_DEFINITION"; } } thanks so much

    Read the article

  • Scala, make my loop more functional

    - by Pengin
    I'm trying to reduce the extent to which I write Scala (2.8) like Java. Here's a simplification of a problem I came across. Can you suggest improvements on my solutions that are "more functional"? Transform the map val inputMap = mutable.LinkedHashMap(1->'a',2->'a',3->'b',4->'z',5->'c') by discarding any entries with value 'z' and indexing the characters as they are encountered First try var outputMap = new mutable.HashMap[Char,Int]() var counter = 0 for(kvp <- inputMap){ val character = kvp._2 if(character !='z' && !outputMap.contains(character)){ outputMap += (character -> counter) counter += 1 } } Second try (not much better, but uses an immutable map and a 'foreach') var outputMap = new immutable.HashMap[Char,Int]() var counter = 0 inputMap.foreach{ case(number,character) => { if(character !='z' && !outputMap.contains(character)){ outputMap2 += (character -> counter) counter += 1 } } }

    Read the article

  • && (AND) and || (OR) in Java IF statements

    - by Azimuth
    My question might be very basic but still I think it worths to ask. I have the following code: if(!partialHits.get(req_nr).containsKey(z) || partialHits.get(req_nr).get(z) < tmpmap.get(z)){ partialHits.get(z).put(z, tmpmap.get(z)); } where partialHits is a HashMap. What will happen if the first statement is true? Will Java still check the second statement? Because in order the first statement to be true, the HashMap should not contain the given key, so if the second statement is checked, I will get NullPointerException. So in simple words, if we have the following code if(a && b) if(a || b) would Java check b if a is false in the first case and if a is true in the second case?

    Read the article

  • parse json news feed array android

    - by user1827260
    I have an json feed from bbc in this format { "name": "ticker", "entries": [ { "headline": "text", "prompt": "LATEST", "isBreaking": "false", "mediaType": "Standard", "url": "" }, { "headline": "text", "prompt": "LATEST", "isBreaking": "false", "mediaType": "Standard", "url": "" }, etc........... My code is as follows: ArrayList mylist = new ArrayList(); JSONObject json = JSONfunctions.getJSONfromURL("http:/......"); try{ JSONArray item = json.getJSONArray("entries"); for (int i = 0; i<item.length(); i++) { HashMap<String, String> map = new HashMap<String, String>(); JSONObject e = item.getJSONObject(i); JSONObject title = e.JSONObject("headline"); map.put("title", "Title:" + e.getString("headline"); } It gives me the error "java.lang.String cannot be converted to JSONObject" I also tried leaving out JSONObject title = e.JSONObject("headline"); and it gives me a path error (note

    Read the article

  • Space partitioning when everything is moving

    - by Roy T.
    Background Together with a friend I'm working on a 2D game that is set in space. To make it as immersive and interactive as possible we want there to be thousands of objects freely floating around, some clustered together, others adrift in empty space. Challenge To unburden the rendering and physics engine we need to implement some sort of spatial partitioning. There are two challenges we have to overcome. The first challenge is that everything is moving so reconstructing/updating the data structure has to be extremely cheap since it will have to be done every frame. The second challenge is the distribution of objects, as said before there might be clusters of objects together and vast bits of empty space and to make it even worse there is no boundary to space. Existing technologies I've looked at existing techniques like BSP-Trees, QuadTrees, kd-Trees and even R-Trees but as far as I can tell these data structures aren't a perfect fit since updating a lot of objects that have moved to other cells is relatively expensive. What I've tried I made the decision that I need a data structure that is more geared toward rapid insertion/update than on giving back the least amount of possible hits given a query. For that purpose I made the cells implicit so each object, given it's position, can calculate in which cell(s) it should be. Then I use a HashMap that maps cell-coordinates to an ArrayList (the contents of the cell). This works fairly well since there is no memory lost on 'empty' cells and its easy to calculate which cells to inspect. However creating all those ArrayLists (worst case N) is expensive and so is growing the HashMap a lot of times (although that is slightly mitigated by giving it a large initial capacity). Problem OK so this works but still isn't very fast. Now I can try to micro-optimize the JAVA code. However I'm not expecting too much of that since the profiler tells me that most time is spent in creating all those objects that I use to store the cells. I'm hoping that there are some other tricks/algorithms out there that make this a lot faster so here is what my ideal data structure looks like: The number one priority is fast updating/reconstructing of the entire data structure Its less important to finely divide the objects into equally sized bins, we can draw a few extra objects and do a few extra collision checks if that means that updating is a little bit faster Memory is not really important (PC game)

    Read the article

  • Oracle Identity Manager Role Management With API

    - by mustafakaya
    As an administrator, you use roles to create and manage the records of a collection of users to whom you want to permit access to common functionality, such as access rights, roles, or permissions. Roles can be independent of an organization, span multiple organizations, or contain users from a single organization. Using roles, you can: View the menu items that the users can access through Oracle Identity Manager Administration Web interface. Assign users to roles. Assign a role to a parent role Designate status to the users so that they can specify defined responses for process tasks. Modify permissions on data objects. Designate role administrators to perform actions on roles, such as enabling members of another role to assign users to the current role, revoke members from current role and so on. Designate provisioning policies for a role. These policies determine if a resource object is to be provisioned to or requested for a member of the role. Assign or remove membership rules to or from the role. These rules determine which users can be assigned/removed as direct membership to/from the role.  In this post, i will share some examples for role management with Oracle Identity Management API.  You can do role operations you can use Thor.API.Operations.tcGroupOperationsIntf interface. tcGroupOperationsIntf service =  getClient().getService(tcGroupOperationsIntf.class);     Assign an user to role :    public void assignRoleByUsrKey(String roleName, String usrKey) throws Exception {         Map<String, String> filter = new HashMap<String, String>();         filter.put("Groups.Role Name", roleName);         tcResultSet role = service.findGroups(filter);         String groupKey = role.getStringValue("Groups.Key");         service.addMemberUser(Long.parseLong(groupKey), Long.parseLong(usrKey));     }  Revoke an user from role:     public void revokeRoleByUsrKey(String roleName, String usrKey) throws Exception {         Map<String, String> filter = new HashMap<String, String>();         filter.put("Groups.Role Name", roleName);         tcResultSet role = service.findGroups(filter);         String groupKey = role.getStringValue("Groups.Key");         service.removeMemberUser(Long.parseLong(groupKey), Long.parseLong(usrKey));     } Get all members of a role :      public List<User> getRoleMembers(String roleName) throws Exception {         List<User> userList = new ArrayList<User>();         Map<String, String> filter = new HashMap<String, String>();         filter.put("Groups.Role Name", roleName);         tcResultSet role = service.findGroups(filter);       String groupKey = role.getStringValue("Groups.Key");         tcResultSet members = service.getAllMemberUsers(Long.parseLong(groupKey));         for (int i = 0; i < members.getRowCount(); i++) {                 members.goToRow(i);                 long userKey = members.getLongValue("Users.Key");                 User member = oimUserManager.findUserByUserKey(String.valueOf(userKey));                 userList.add(member);         }        return userList;     } About me: Mustafa Kaya is a Senior Consultant in Oracle Fusion Middleware Team, living in Istanbul. Before coming to Oracle, he worked in teams developing web applications and backend services at a telco company. He is a Java technology enthusiast, software engineer and addicted to learn new technologies,develop new ideas. Follow Mustafa on Twitter,Connect on LinkedIn, and visit his site for Oracle Fusion Middleware related tips.

    Read the article

  • Java Hashed Collections

    The Java collections framework contains classes you use to maintain collections of other objects. These collection classes have different performance and ordering properties. See how the HashMap and HashSet Classes allow objects to be added to a collection, removed from a collection, or found in roughly constant time. Discover how to use these classes and what to do to achieve good performance from them.

    Read the article

  • Uploading multiple files using Spring MVC 3.0.2 after HiddenHttpMethodFilter has been enabled

    - by Tiny
    I'm using Spring version 3.0.2. I need to upload multiple files using the multiple="multiple" attribute of a file browser such as, <input type="file" id="myFile" name="myFile" multiple="multiple"/> (and not using multiple file browsers something like the one stated by this answer, it indeed works I tried). Although no versions of Internet Explorer supports this approach unless an appropriate jQuery plugin/widget is used, I don't care about it right now (since most other browsers support this). This works fine with commons fileupload but in addition to using RequestMethod.POST and RequestMethod.GET methods, I also want to use other request methods supported and suggested by Spring like RequestMethod.PUT and RequestMethod.DELETE in their own appropriate places. For this to be so, I have configured Spring with HiddenHttpMethodFilter which goes fine as this question indicates. but it can upload only one file at a time even though multiple files in the file browser are chosen. In the Spring controller class, a method is mapped as follows. @RequestMapping(method={RequestMethod.POST}, value={"admin_side/Temp"}) public String onSubmit(@RequestParam("myFile") List<MultipartFile> files, @ModelAttribute("tempBean") TempBean tempBean, BindingResult error, Map model, HttpServletRequest request, HttpServletResponse response) throws IOException, FileUploadException { for(MultipartFile file:files) { System.out.println(file.getOriginalFilename()); } } Even with the request parameter @RequestParam("myFile") List<MultipartFile> files which is a List of type MultipartFile (it can always have only one file at a time). I could find a strategy which is likely to work with multiple files on this blog. I have gone through it carefully. The solution below the section SOLUTION 2 – USE THE RAW REQUEST says, If however the client insists on using the same form input name such as ‘files[]‘ or ‘files’ and then populating that name with multiple files then a small hack is necessary as follows. As noted above Spring 2.5 throws an exception if it detects the same form input name of type file more than once. CommonsFileUploadSupport – the class which throws that exception is not final and the method which throws that exception is protected so using the wonders of inheritance and subclassing one can simply fix/modify the logic a little bit as follows. The change I’ve made is literally one word representing one method invocation which enables us to have multiple files incoming under the same form input name. It attempts to override the method protected MultipartParsingResult parseFileItems(List fileItems, String encoding) {} of the abstract class CommonsFileUploadSupport by extending the class CommonsMultipartResolver such as, package multipartResolver; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.ServletContext; import org.apache.commons.fileupload.FileItem; import org.springframework.util.StringUtils; import org.springframework.web.multipart.MultipartException; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartResolver; final public class MultiCommonsMultipartResolver extends CommonsMultipartResolver { public MultiCommonsMultipartResolver() { } public MultiCommonsMultipartResolver(ServletContext servletContext) { super(servletContext); } @Override @SuppressWarnings("unchecked") protected MultipartParsingResult parseFileItems(List fileItems, String encoding) { Map<String, MultipartFile> multipartFiles = new HashMap<String, MultipartFile>(); Map multipartParameters = new HashMap(); // Extract multipart files and multipart parameters. for (Iterator it = fileItems.iterator(); it.hasNext();) { FileItem fileItem = (FileItem) it.next(); if (fileItem.isFormField()) { String value = null; if (encoding != null) { try { value = fileItem.getString(encoding); } catch (UnsupportedEncodingException ex) { if (logger.isWarnEnabled()) { logger.warn("Could not decode multipart item '" + fileItem.getFieldName() + "' with encoding '" + encoding + "': using platform default"); } value = fileItem.getString(); } } else { value = fileItem.getString(); } String[] curParam = (String[]) multipartParameters.get(fileItem.getFieldName()); if (curParam == null) { // simple form field multipartParameters.put(fileItem.getFieldName(), new String[] { value }); } else { // array of simple form fields String[] newParam = StringUtils.addStringToArray(curParam, value); multipartParameters.put(fileItem.getFieldName(), newParam); } } else { // multipart file field CommonsMultipartFile file = new CommonsMultipartFile(fileItem); if (multipartFiles.put(fileItem.getName(), file) != null) { throw new MultipartException("Multiple files for field name [" + file.getName() + "] found - not supported by MultipartResolver"); } if (logger.isDebugEnabled()) { logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize() + " bytes with original filename [" + file.getOriginalFilename() + "], stored " + file.getStorageDescription()); } } } return new MultipartParsingResult(multipartFiles, multipartParameters); } } What happens is that the last line in the method parseFileItems() (the return statement) i.e. return new MultipartParsingResult(multipartFiles, multipartParameters); causes a compile-time error because the first parameter multipartFiles is a type of Map implemented by HashMap but in reality, it requires a parameter of type MultiValueMap<String, MultipartFile> It is a constructor of a static class inside the abstract class CommonsFileUploadSupport, public abstract class CommonsFileUploadSupport { protected static class MultipartParsingResult { public MultipartParsingResult(MultiValueMap<String, MultipartFile> mpFiles, Map<String, String[]> mpParams) { } } } The reason might be - this solution is about the Spring version 2.5 and I'm using the Spring version 3.0.2 which might be inappropriate for this version. I however tried to replace the Map with MultiValueMap in various ways such as the one shown in the following segment of code, MultiValueMap<String, MultipartFile>mul=new LinkedMultiValueMap<String, MultipartFile>(); for(Entry<String, MultipartFile>entry:multipartFiles.entrySet()) { mul.add(entry.getKey(), entry.getValue()); } return new MultipartParsingResult(mul, multipartParameters); but no success. I'm not sure how to replace Map with MultiValueMap and even doing so could work either. After doing this, the browser shows the Http response, HTTP Status 400 - type Status report message description The request sent by the client was syntactically incorrect (). Apache Tomcat/6.0.26 I have tried to shorten the question as possible as I could and I haven't included unnecessary code. How could be made it possible to upload multiple files after Spring has been configured with HiddenHttpMethodFilter? That blog indicates that It is a long standing, high priority bug. If there is no solution regarding the version 3.0.2 (3 or higher) then I have to disable Spring support forever and continue to use commons-fileupolad as suggested by the third solution on that blog omitting the PUT, DELETE and other request methods forever. Just curiously waiting for a solution and/or suggestion. Very little changes to the code in the parseFileItems() method inside the class MultiCommonsMultipartResolver might make it to upload multiple files but I couldn't succeed in my attempts (again with the Spring version 3.0.2 (3 or higher)).

    Read the article

  • Facing Null Pointer Exception while using BIRT

    - by srikanth
    Hi, I am using BIRT APIs in a java program.My code is : package com.tecnotree.mdx.product.utils; import java.util.HashMap; import java.util.logging.Level; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.core.framework.Platform; import org.eclipse.birt.report.engine.api.EngineConfig; import org.eclipse.birt.report.engine.api.EngineConstants; import org.eclipse.birt.report.engine.api.HTMLRenderOption; import org.eclipse.birt.report.engine.api.IReportEngine; import org.eclipse.birt.report.engine.api.IReportEngineFactory; import org.eclipse.birt.report.engine.api.IReportRunnable; import org.eclipse.birt.report.engine.api.IRunAndRenderTask; import org.eclipse.birt.report.engine.api.ReportEngine; public class ExampleReport { public static void main(String[] args) { // Variables used to control BIRT Engine instance ReportEngine eng = null; IReportRunnable design = null; IRunAndRenderTask task = null; HTMLRenderOption renderContext = null; HashMap contextMap = null; HTMLRenderOption options = null; final EngineConfig conf = new EngineConfig(); conf .setEngineHome("C:\\birt-runtime-2_5_2\\birt-runtime-2_5_2\\ReportEngine"); System.out.println("conf " + conf.getBIRTHome()); conf.setLogConfig(null, Level.FINE); try { Platform.startup(conf); } catch (BirtException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } IReportEngineFactory factory = (IReportEngineFactory) Platform .createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY); System.out.println("Factory : " + factory.toString()); System.out.println(conf.toString()); IReportEngine engine = factory.createReportEngine(conf); System.out.println("Engine : " + engine); try { design = eng .openReportDesign("C:\\birt-runtime-2_5_2\\birt-runtime-2_5_2\\ReportEngine\\samples\\hello_world.rptdesign"); } catch (Exception e) { System.err .println("An error occured during the opening of the report file!"); e.printStackTrace(); System.exit(-1); } task = eng.createRunAndRenderTask(design); renderContext = new HTMLRenderOption(); renderContext.setImageDirectory("image"); contextMap = new HashMap(); contextMap.put(EngineConstants.APPCONTEXT_HTML_RENDER_CONTEXT, renderContext); task.setAppContext(contextMap); options = new HTMLRenderOption(); options.setOutputFileName("c:/temp/output.html"); options.setOutputFormat("html"); task.setRenderOption(options); try { task.run(); } catch (Exception e) { System.err.println("An error occured while running the report!"); e.printStackTrace(); System.exit(-1); } System.out.println("All went well. Closing program!"); eng.destroy(); } } But i am facing NullPointerException while creating the report. STACKTRACE : Exception in thread "main" java.lang.NullPointerException at org.eclipse.birt.report.engine.api.impl.ReportEngine$EngineExtensionManager.<init>(ReportEngine.java:784) at org.eclipse.birt.report.engine.api.impl.ReportEngine.<init>(ReportEngine.java:109) at org.eclipse.birt.report.engine.api.impl.ReportEngineFactory$1.run(ReportEngineFactory.java:18) at org.eclipse.birt.report.engine.api.impl.ReportEngineFactory$1.run(ReportEngineFactory.java:1) at java.security.AccessController.doPrivileged(Native Method) at org.eclipse.birt.report.engine.api.impl.ReportEngineFactory.createReportEngine(ReportEngineFactory.java:14) at com.tecnotree.mdx.product.utils.ExampleReport.main(ExampleReport.java:47) Please help me regarding this... my project deadline has been reached... Appreciate your Reply Thanks in Advance

    Read the article

  • Solr WordDelimiterFilter + Lucene Highlighter

    - by Lucas
    I am trying to get the Highlighter class from Lucene to work properly with tokens coming from Solr's WordDelimiterFilter. It works 90% of the time, but if the matching text contains a ',' such as "1,500" the output is incorrect: Expected: 'test 1,500 this' Observed: 'test 11,500 this' I am not currently sure whether it is Highlighter messing up the recombination or WordDelimiterFilter messing up the tokenization but something is unhappy. Here are the relevant dependencies from my pom: org.apache.lucene lucene-core 2.9.3 jar compile org.apache.lucene lucene-highlighter 2.9.3 jar compile org.apache.solr solr-core 1.4.0 jar compile And here is a simple JUnit test class demonstrating the problem: package test.lucene; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.io.Reader; import java.util.HashMap; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.Query; import org.apache.lucene.search.highlight.Highlighter; import org.apache.lucene.search.highlight.InvalidTokenOffsetsException; import org.apache.lucene.search.highlight.QueryScorer; import org.apache.lucene.search.highlight.SimpleFragmenter; import org.apache.lucene.search.highlight.SimpleHTMLFormatter; import org.apache.lucene.util.Version; import org.apache.solr.analysis.StandardTokenizerFactory; import org.apache.solr.analysis.WordDelimiterFilterFactory; import org.junit.Test; public class HighlighterTester { private static final String PRE_TAG = "<b>"; private static final String POST_TAG = "</b>"; private static String[] highlightField( Query query, String fieldName, String text ) throws IOException, InvalidTokenOffsetsException { SimpleHTMLFormatter formatter = new SimpleHTMLFormatter( PRE_TAG, POST_TAG ); Highlighter highlighter = new Highlighter( formatter, new QueryScorer( query, fieldName ) ); highlighter.setTextFragmenter( new SimpleFragmenter( Integer.MAX_VALUE ) ); return highlighter.getBestFragments( getAnalyzer(), fieldName, text, 10 ); } private static Analyzer getAnalyzer() { return new Analyzer() { @Override public TokenStream tokenStream( String fieldName, Reader reader ) { // Start with a StandardTokenizer TokenStream stream = new StandardTokenizerFactory().create( reader ); // Chain on a WordDelimiterFilter WordDelimiterFilterFactory wordDelimiterFilterFactory = new WordDelimiterFilterFactory(); HashMap<String, String> arguments = new HashMap<String, String>(); arguments.put( "generateWordParts", "1" ); arguments.put( "generateNumberParts", "1" ); arguments.put( "catenateWords", "1" ); arguments.put( "catenateNumbers", "1" ); arguments.put( "catenateAll", "0" ); wordDelimiterFilterFactory.init( arguments ); return wordDelimiterFilterFactory.create( stream ); } }; } @Test public void TestHighlighter() throws ParseException, IOException, InvalidTokenOffsetsException { String fieldName = "text"; String text = "test 1,500 this"; String queryString = "1500"; String expected = "test " + PRE_TAG + "1,500" + POST_TAG + " this"; QueryParser parser = new QueryParser( Version.LUCENE_29, fieldName, getAnalyzer() ); Query q = parser.parse( queryString ); String[] observed = highlightField( q, fieldName, text ); for ( int i = 0; i < observed.length; i++ ) { System.out.println( "\t" + i + ": '" + observed[i] + "'" ); } if ( observed.length > 0 ) { System.out.println( "Expected: '" + expected + "'\n" + "Observed: '" + observed[0] + "'" ); assertEquals( expected, observed[0] ); } else { assertTrue( "No matches found", false ); } } } Anyone have any ideas or suggestions?

    Read the article

  • Unable to build my c++ code with g++ 4.6.3

    - by Mriganka
    I am facing multiple issues with building my c++ code on Ubuntu 12.04. This code was building and running fine on RH Enterprise. I am using g++ 4.6.3. Here's the output of g++ -v. g++ -v Using built-in specs. COLLECT_GCC=g++ COLLECT_LTO_WRAPPER=/usr/lib/gcc/i686-linux-gnu/4.6/lto-wrapper Target: i686-linux-gnu Configured with: ../src/configure -v --with-pkgversion='Ubuntu/Linaro 4.6.3-1ubuntu5' --with-bugurl=file:///usr/share/doc/gcc-4.6/README.Bugs --enable-languages=c,c++,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.6 --enable-shared --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.6 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-gnu-unique-object --enable-plugin --enable-objc-gc --enable-targets=all --disable-werror --with-arch-32=i686 --with-tune=generic --enable-checking=release --build=i686-linux-gnu --host=i686-linux-gnu --target=i686-linux-gnu Thread model: posix gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5) Here's a sample of my code: #include "Word.h" #include < string> using namespace std; pthread_mutex_t Word::_lock = PTHREAD_MUTEX_INITIALIZER; Word::Word(): _occurrences(1) { memset(_buf, 0, 25); } Word::Word(char *str): _occurrences(1) { memset(_buf, 0, 25); if (str != NULL) { strncpy(_buf, str, strlen(str)); } } g++ -c -ansi or g++ -c -std=c++98 or g++ -c -std=c++03, none of these options are able to build the code correctly. I get the following compilation errors: mriganka@ubuntu:~/WordCount$ make g++ -c -g -ansi Word.cpp -o Word.o Word.cpp: In constructor ‘Word::Word()’: Word.cpp:10:21: error: ‘memset’ was not declared in this scope Word.cpp: In constructor ‘Word::Word(char*)’: Word.cpp:16:21: error: ‘memset’ was not declared in this scope Word.cpp:19:34: error: ‘strlen’ was not declared in this scope Word.cpp:19:35: error: ‘strncpy’ was not declared in this scope Word.cpp: In member function ‘void Word::operator=(const Word&)’: Word.cpp:37:42: error: ‘strlen’ was not declared in this scope Word.cpp:37:43: error: ‘strncpy’ was not declared in this scope Word.cpp: In copy constructor ‘Word::Word(const Word&)’: Word.cpp:44:21: error: ‘memset’ was not declared in this scope Word.cpp:45:52: error: ‘strlen’ was not declared in this scope Word.cpp:45:53: error: ‘strncpy’ was not declared in this scope So basically g++ 4.6.3 on Ubuntu 12.04 is not able to recognize the standard c++ headers. And I am not finding a way out of this situation. Second problem: In order to make progress, I included < string.h instead of < string. But now I am facing linking errors with my message queue and pthread library functions. Here's the error that I am getting: mriganka@ubuntu:~/WordCount$ make g++ -c -g -ansi Word.cpp -o Word.o g++ -lrt -I/usr/lib/i386-linux-gnu Word.o HashMap.o main.o -o word_count main.o: In function `main': /home/mriganka/WordCount/main.cpp:75: undefined reference to `pthread_create' /home/mriganka/WordCount/main.cpp:90: undefined reference to `mq_open' /home/mriganka/WordCount/main.cpp:93: undefined reference to `mq_getattr' /home/mriganka/WordCount/main.cpp:113: undefined reference to `mq_send' /home/mriganka/WordCount/main.cpp:123: undefined reference to `pthread_join' /home/mriganka/WordCount/main.cpp:129: undefined reference to `mq_close' /home/mriganka/WordCount/main.cpp:130: undefined reference to `mq_unlink' main.o: In function `count_words(void*)': /home/mriganka/WordCount/main.cpp:151: undefined reference to `mq_open' /home/mriganka/WordCount/main.cpp:154: undefined reference to `mq_getattr' /home/mriganka/WordCount/main.cpp:162: undefined reference to `mq_timedreceive' collect2: ld returned 1 exit status Here's my makefile: CC=g++ CFLAGS=-c -g -ansi LDFLAGS=-lrt INC=-I/usr/lib/i386-linux-gnu SOURCES=Word.cpp HashMap.cpp main.cpp OBJECTS=$(SOURCES:.cpp=.o) EXECUTABLE=word_count all: $(SOURCES) $(EXECUTABLE) $(EXECUTABLE): $(OBJECTS) $(CC) $(LDFLAGS) $(INC) -pthread $(OBJECTS) -o $@ .cpp.o: $(CC) $(CFLAGS) $< -o $@ clean: rm -f *.o word_count Please help me to resolve both the issues. I searched online relentlessly for any solution of these problems, but no one seems to have encountered these issues.

    Read the article

  • How to show an image on jasper report?

    - by spderosso
    Hi, I want to show an image on a jasper report. I have the following on the .jrxml: <image> <reportElement x="181" y="0" width="209" height="74"/> <imageExpression class="java.lang.String"><![CDATA["logo.jpg"]]></imageExpression> </image> The image logo.jpg is in the same directory as the .jrxml. By just putting that it didn't work for me. I googled a bit and found out that jasper report considers what i put on the .jrxml as a relative path to the JVM directory and that to change this I need to pass as a "REPORT_FILE_RESOLVER" parameter a FileResolver that returns the file. So, I did the following in my .java (is located in same place as the .jrxml and the image) FileResolver fileResolver = new FileResolver() { @Override public File resolveFile(String fileName) { return new File(fileName); } }; HashMap<String, Object> parameters = new HashMap<String, Object>(); parameters.put("REPORT_FILE_RESOLVER", fileResolver); ... Which should return the expected file, but I still get a net.sf.jasperreports.engine.JRException: Error loading byte data : logo.jpg at net.sf.jasperreports.engine.util.JRLoader.loadBytes(JRLoader.java:301) at net.sf.jasperreports.engine.util.JRLoader.loadBytesFromLocation(JRLoader.java:479) at net.sf.jasperreports.engine.JRImageRenderer.getInstance(JRImageRenderer.java:180) ... What am I doing wrong? Thanks!

    Read the article

  • How to get Cookies using HttpClient

    - by Sunil
    Hello I am using HttpClient to get Cookies but I am unable find any cookies.My Code is given below public class LoginTab { private Cookie[] cookies; HttpClient httpClient; HttpState httpState; HashMap postData; public LoginTab() { httpClient = new HttpClient(); httpState = new HttpState(); httpClient.getHttpConnectionManager(). getParams().setConnectionTimeout(300000); httpClient.setState(httpState); // RFC 2101 cookie management spec is used per default // to parse, validate, format & match cookies httpClient.getParams().setCookiePolicy(CookiePolicy.RFC_2109); postData= new HashMap(); } public String getMethod(String url) { GetMethod getMethod = new GetMethod(url); String pageSoure=""; try{ httpClient.executeMethod(getMethod); pageSoure=getMethod.getResponseBodyAsString(); extractUsefulPostData(pageSoure, postData); getMethod.releaseConnection(); }catch(Exception ex) { ex.printStackTrace(); } return pageSoure; } public static void main(String[]arg) { LoginTab loginTab= new LoginTab(); System.out.println(loginTab.getMethod("http://tab.com.au/")); Cookie [] cookies=loginTab.httpState.getCookies(); System.out.println(cookies.length); for(int i=0;i<cookies.length;i++) System.out.println(cookies[i]); } } Please suggest me where is the mistake. Thanks in advance

    Read the article

  • How to get Cookies using HttpClient

    - by Sunil
    Hello I am using HttpClient to get Cookies but I am unable find any cookies.My Code is given below public class LoginTab { private Cookie[] cookies; HttpClient httpClient; HttpState httpState; HashMap postData; public LoginTab() { httpClient = new HttpClient(); httpState = new HttpState(); httpClient.getHttpConnectionManager(). getParams().setConnectionTimeout(300000); httpClient.setState(httpState); // RFC 2101 cookie management spec is used per default // to parse, validate, format & match cookies httpClient.getParams().setCookiePolicy(CookiePolicy.RFC_2109); postData= new HashMap(); } public String getMethod(String url) { GetMethod getMethod = new GetMethod(url); String pageSoure=""; try{ httpClient.executeMethod(getMethod); pageSoure=getMethod.getResponseBodyAsString(); extractUsefulPostData(pageSoure, postData); getMethod.releaseConnection(); }catch(Exception ex) { ex.printStackTrace(); } return pageSoure; } public static void main(String[]arg) { LoginTab loginTab= new LoginTab(); System.out.println(loginTab.getMethod("http://tab.com.au/")); Cookie [] cookies=loginTab.httpState.getCookies(); System.out.println(cookies.length); for(int i=0;i<cookies.length;i++) System.out.println(cookies[i]); } } Please suggest me where is the mistake. Thanks in advance

    Read the article

  • Blank subreport in Jasper Reports

    - by Andy Chapman
    Hi all, I'm trying to launch a report that I created in iReport which contains a main report and a subreport. In iReport, the subreport launches fine and contains data, however when I try to launch it from within my java code, the subreport is blank. What I've done so far: I have a String parameter in the main report called "SUBREPORT" that is used to define the path to the subreport. E.g. value: "E:\java\ReportLauncher\reports\test_subreport1.jasper" The subreport expression in the main report is set to: $P{SUBREPORT} The subreport connection expression is: $P{REPORT_CONNECTION} I also have a subreport parameter defined called "INVOICE_NUMBER" that is set to $F{InviInvNo}, which maps to a field in the main report. In my java code, I have: HashMap<String, Object> paramHash = new HashMap(); paramHash.put("INVOICE_NUMBER", invoiceID); paramHash.put("REPORT_CONNECTION", this.conn); paramHash.put("SUBREPORT", subReportPath); JasperPrint jasperprint = JasperFillManager.fillReport(this.reportPath, paramHash, this.conn); The main report is created fine and is populated. The subreport area however is blank. Any thoughts for what I'm doing wrong? Thanks in advance, Andy.

    Read the article

  • Android - Launch Intent within ExpandableListView

    - by Ryan
    Hello, I'm trying to figure out if it is possible to launch an intent within an ExpandableListView. Basically one of the "Groups" is Phone Number and it's child is the number. I want the user to be able to click it and have it automatically call that number. Is this possible? How? Here is my code to populate the ExpandableListView using a Map called "data". ExpandableListView myList = (ExpandableListView) findViewById(R.id.myList); //ExpandableListAdapter adapter = new MyExpandableListAdapter(data); List<Map<String, String>> groupData = new ArrayList<Map<String, String>>(); List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>(); Iterator it = data.entrySet().iterator(); while (it.hasNext()) { //Get the key name and value for it Map.Entry pair = (Map.Entry)it.next(); String keyName = (String) pair.getKey(); String value = pair.getValue().toString(); //Add the parents -- aka main categories Map<String, String> curGroupMap = new HashMap<String, String>(); groupData.add(curGroupMap); curGroupMap.put("NAME", keyName); //Add the child data List<Map<String, String>> children = new ArrayList<Map<String, String>>(); Map<String, String> curChildMap = new HashMap<String, String>(); children.add(curChildMap); curChildMap.put("NAME", value); childData.add(children); } // Set up our adapter mAdapter = new SimpleExpandableListAdapter( mContext, groupData, R.layout.exp_list_parent, new String[] { "NAME", "IS_EVEN" }, new int[] { R.id.rowText1, R.id.rowText2 }, childData, R.layout.exp_list_child, new String[] { "NAME", "IS_EVEN" }, new int[] { R.id.rowText3, R.id.rowText4} ); myList.setAdapter(mAdapter);

    Read the article

  • Ant build from Android-generated build file fails - how to fix?

    - by Eno
    Building our Android app from Ant fails with this error: [apply] [apply] UNEXPECTED TOP-LEVEL ERROR: [apply] java.lang.OutOfMemoryError: Java heap space [apply] at java.util.HashMap.<init>(HashMap.java:209) [apply] at java.util.HashSet.<init>(HashSet.java:86) [apply] at com.android.dx.ssa.Dominators.compress(Dominators.java:96) [apply] at com.android.dx.ssa.Dominators.eval(Dominators.java:132) [apply] at com.android.dx.ssa.Dominators.run(Dominators.java:213) [apply] at com.android.dx.ssa.DomFront.run(DomFront.java:84) [apply] at com.android.dx.ssa.SsaConverter.placePhiFunctions(SsaConverter.java:265) [apply] at com.android.dx.ssa.SsaConverter.convertToSsaMethod(SsaConverter.java:51) [apply] at com.android.dx.ssa.Optimizer.optimize(Optimizer.java:100) [apply] at com.android.dx.ssa.Optimizer.optimize(Optimizer.java:74) [apply] at com.android.dx.dex.cf.CfTranslator.processMethods(CfTranslator.java:269) [apply] at com.android.dx.dex.cf.CfTranslator.translate0(CfTranslator.java:131) [apply] at com.android.dx.dex.cf.CfTranslator.translate(CfTranslator.java:85) [apply] at com.android.dx.command.dexer.Main.processClass(Main.java:297) [apply] at com.android.dx.command.dexer.Main.processFileBytes(Main.java:276) [apply] at com.android.dx.command.dexer.Main.access$100(Main.java:56) [apply] at com.android.dx.command.dexer.Main$1.processFileBytes(Main.java:228) [apply] at com.android.dx.cf.direct.ClassPathOpener.processArchive(ClassPathOpener.java:245) [apply] at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:130) [apply] at com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpener.java:108) [apply] at com.android.dx.command.dexer.Main.processOne(Main.java:245) [apply] at com.android.dx.command.dexer.Main.processAllFiles(Main.java:183) [apply] at com.android.dx.command.dexer.Main.run(Main.java:139) [apply] at com.android.dx.command.dexer.Main.main(Main.java:120) [apply] at com.android.dx.command.Main.main(Main.java:87) BUILD FAILED Ive tried giving Ant more memory by setting ANT_OPTS="-Xms256m -Xmx512m". (This build machine has 1Gb RAM). Do I just need more memory or is there anything else I can try?

    Read the article

  • How can I pass an arbitrary object to jasper report as parameter?

    - by spderosso
    Hi, I would like to pass as a parameter to my .jrxml an arbitrary object of my domain, e.g a Person. InputStream reportFile = MyPage.this.getClass().getResourceAsStream("test.jrxml"); HashMap<String, Person> parameters = new HashMap<String, Person>(); parameters.put("person", new Person("John", "Doe")); ... JasperReport report = JasperCompileManager.compileReport(reportFile); JasperPrint print = JasperFillManager.fillReport(report, parameters, new JREmptyDataSource()); return JasperExportManager.exportReportToPdf(print); And on the .jrxml do something like: <?xml version="1.0" encoding="UTF-8"?> <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="test" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20"> <property name="ireport.zoom" value="1.0"/> <property name="ireport.x" value="0"/> <property name="ireport.y" value="0"/> <parameter name="PERSON" isForPrompting="false" class="myApp.domain.person"/> <background> <band splitType="Stretch"/> </background> <title> <band height="20"> <staticText> <reportElement x="180" y="0" width="200" height="20"/> <text><![CDATA[$P{PERSON.lastName}]]></text> </staticText> </band> </title> ... Is something like this possible? Where can I find more complex tutorials that show more than just passing a java.lang.String? Thanks

    Read the article

  • adjacency list creation , out of Memory error

    - by p1
    Hello , I am trying to create an adjacency list to store a graph.The implementation works fine while storing 100,000 records. However,when I tried to store around 1million records I ran into OutofMemory Error : Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at java.util.Arrays.copyOfRange(Arrays.java:3209) at java.lang.String.(String.java:215) at java.io.BufferedReader.readLine(BufferedReader.java:331) at java.io.BufferedReader.readLine(BufferedReader.java:362) at liarliar.main(liarliar.java:39) Following is my implementation HashMap<String,ArrayList<String>> adj = new HashMap<String,ArrayList<String>>(num); while ((str = in.readLine()) != null) { StringTokenizer Tok = new StringTokenizer(str); name = (String) Tok.nextElement(); cnt = Integer.valueOf(Tok.nextToken()); ArrayList<String> templist = new ArrayList<String>(cnt); while(cnt>0) { templist.add(in.readLine()); cnt--; } adj.put(name,templist); } //done creating a adjacency list I am wondering, if there is any better way to implement the adjacency list. Also, I know number of nodes right in the begining and , in the future I flatten the list as I visit nodes. Any suggestions ? Thanks

    Read the article

  • Do the ‘up to date’ guarantees for values of Java's final fields extend to indirect references?

    - by mattbh
    The Java language spec defines semantics of final fields in section 17.5: The usage model for final fields is a simple one. Set the final fields for an object in that object's constructor. Do not write a reference to the object being constructed in a place where another thread can see it before the object's constructor is finished. If this is followed, then when the object is seen by another thread, that thread will always see the correctly constructed version of that object's final fields. It will also see versions of any object or array referenced by those final fields that are at least as up-to-date as the final fields are. My question is - does the 'up-to-date' guarantee extend to the contents of nested arrays, and nested objects? An example scenario: Thread A constructs a HashMap of ArrayLists, then assigns the HashMap to final field 'myFinal' in an instance of class 'MyClass' Thread B sees a (non-synchronized) reference to the MyClass instance and reads 'myFinal', and accesses and reads the contents of one of the ArrayLists In this scenario, are the members of the ArrayList as seen by Thread B guaranteed to be at least as up to date as they were when MyClass's constructor completed? I'm looking for clarification of the semantics of the Java Memory Model and language spec, rather than alternative solutions like synchronization. My dream answer would be a yes or no, with a reference to the relevant text.

    Read the article

  • XMLRPC java insert issue

    - by Sanjai Palliyil
    I am trying to insert customer details into OpenERP server using XMLPRC and java. I am able to do an authentication. But when i call the execute method to insert the record by passing the parameters, am getting Exception in thread "main" java.lang.NullPointerException on line res_create = client_1.execute("execute", params_create); Please find my code below res = client.execute("login", params); String url_1 = "http://agilewebdevelopment.net:8514/xmlrpc/object"; XmlRpcClientConfigImpl config_1 = new XmlRpcClientConfigImpl(); try { config_1.setServerURL(new URL(url_1)); } catch (MalformedURLException e) { System.out.println("First"); e.printStackTrace(); } System.out.println(res); HashMap<String, Object> vals = new HashMap<String, Object>(); vals.put("name", "Mantavya Gajjar"); vals.put("ref", "MGA"); XmlRpcClient client_1 = new XmlRpcClient(); client.setConfig(config_1); Object[] params_create = new Object[]{"erp_performance", "1", "admin", "res.partner", "create", vals}; Object res_create = null; try { res_create = client_1.execute("execute", params_create); } catch (XmlRpcException e) { e.printStackTrace(); } Any helps is appreciated

    Read the article

  • Reference a Map by name within Velocity Template

    - by Wiretap
    Pretty sure there is an easy answer to this, but just can't find the right VTL syntax. In my context I'm passing a Map which contains other Maps. I'd like to reference these inner maps by name and assign them within my template. The inner maps are constructed by different parts of the app, and then added to the context by way of example public static void main( String[] args ) throws Exception { VelocityEngine ve = new VelocityEngine(); ve.init(); Template t = ve.getTemplate( "test.vm" ); VelocityContext context = new VelocityContext(); Map<String,Map<String,String>> messageData = new HashMap<String, Map<String,String>>(); Map<String,String> data_map = new HashMap<String,String>(); data_map.put("data_1","1234"); data_map.put("a_date", "31-Dec-2009"); messageData.put("inner_map", data_map); context.put("msgData", messageData); StringWriter writer = new StringWriter(); t.merge( context, writer ); System.out.println( writer.toString() ); } Template - test.vm #set ($in_map = $msgData.get($inner_map) ) data: $in_map.data_1 $in_map.a_date

    Read the article

  • To have an Integer pointing to 3 ordered lists in Java

    - by Masi
    Which datastructure would you use in the place of X to have efficient merges, sorts and additions as described below? #1 Possible solution: one HashMap to X -datastructure Having a HashMap pointing from fileID to some datastructure linking word, wordCount and wordID may be a good solution. However, I have not found a way to implement it. I am not allowed to use Postgres or any similar tool to keep my data neutralized. I want to have efficient merges, sorts and additions according to fileID, wordID or wordCount for the type below. I have the type Words which has th field fileID that points to a list of words and to relating pieces of information: The Type class Words =================================== fileID: int [list of words] : ArrayList [list of wordCounts] : ArrayList [list of wordIDs] : ArrayList Example of the data in fileID word wordCount wordID instance1 of words 1 He 123 1111 1 llo 321 2 instance2 of words 2 Van 213 666 2 cou 777 932 Example of needed merge fileID wordID fileID wordID 1 2 1 3 wordID=2 2 2 ========> 1 2 2 3 2 2 I cannot see any usage of set-operations such as intersections here because order is needed. Having about three HashMaps makes sorting difficult: from word to wordID in a given fileID from wordID to fileID from wordID to wordCount in a given fileID

    Read the article

  • Eclipse says I don't implement Enumeration, but I do

    - by Harm De Weirdt
    Goodmorning everybody, I'm having a little problem with a project for school. We are told to make an Iterator that implements Enumeration over a Hashmap. So i made this Enumeration: public Enumeration<Object> getEnumeration() { return new Enumeration<Object>() { private int itemsDone = 0; Collection<Long> keysCollection = getContent().keySet(); Long [] keys = keysCollection.toArray(new Long[keysCollection.size()]); @Override public boolean hasMoreElements() { if(itemsDone < getContent().size() +1 ) { return true; }else { return false; } } @Override public Object nextElement() { return getContent().get(keys[itemsDone++]); } }; } This goes in my Backpack class public class Backpack extends Item implements Carrier, Enumeration<Object>{ The hashmap is returned by getContent(). The problem now is that eclipse keeps telling me I havent implemented the methods from Enumeration. If I use the quick fix it just adds the hasMoreElements() and nextElement() dummy methods in my class. Somehow it doesn't see these methods in the inner class.. Can anyone help me please? Any help is appreciated.

    Read the article

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