Search Results

Search found 8588 results on 344 pages for 'thread abort'.

Page 148/344 | < Previous Page | 144 145 146 147 148 149 150 151 152 153 154 155  | Next Page >

  • Spring MVC Project's .war file not able to deploy using JRE in jetty server

    - by PDKumar
    IDE: STS(Eclipse) Server: Jetty-distribution-8.1.15.v20140411 I have created a SpringsMVC Project using Template available in STS tool(New-Springs Project- Springs MVC Project). I generated a war file(SpringsMVC.war) and placed it in /webapps folder of Jetty server. Now I started Jetty using JRE's 'java' , D:\jetty-distribution-8.1.15.v20140411"C:\Program Files (x86)\Java\jre7\bin\java" -jar start.jar Now when I tried to access my application in browser, it shows the below error; HTTP ERROR 500 Problem accessing /SpringMVCProject1/. Reason: Server Error Caused by: org.apache.jasper.JasperException: PWC6345: There is an error in invoking javac. A full JDK (not just JRE) is required at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:92) at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:378) at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:119) at org.apache.jasper.compiler.Jsr199JavaCompiler.compile(Jsr199JavaCompiler.java:208) at org.apache.jasper.compiler.Compiler.generateClass(Compiler.java:384) at org.apache.jasper.compiler.Compiler.compile(Compiler.java:453) at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:625) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:492) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:378) at javax.servlet.http.HttpServlet.service(HttpServlet.java:848) at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:684) at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:503) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:137) at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:575) at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:231) at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1086) at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:429) at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:193) at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1020) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135) at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:276) at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:103) at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238) at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:262) at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1180) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:950) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778) at javax.servlet.http.HttpServlet.service(HttpServlet.java:735) at javax.servlet.http.HttpServlet.service(HttpServlet.java:848) at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:684) at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:503) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:137) at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:533) at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:231) at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1086) at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:429) at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:193) at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1020) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135) at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:255) at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:154) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116) at org.eclipse.jetty.server.Server.handle(Server.java:370) at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:494) at org.eclipse.jetty.server.AbstractHttpConnection.headerComplete(AbstractHttpConnection.java:971) at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.headerComplete(AbstractHttpConnection.java:1033) at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:644) at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:235) at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82) at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:696) at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:53) at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608) at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543) at java.lang.Thread.run(Unknown Source) But if I use JDK's java, war file gets deployed and output displayed perfectly. D:\jetty-distribution-8.1.15.v20140411"C:\Program Files (x86)\Java\jdk1.7.0_55\bin\java" -jar start.jar Hello world! The time on the server is August 20, 2014 3:42:53 PM IST. Please tell is it not possible to use JRE to execute a "SpringsMVCProject"?

    Read the article

  • matplotlib and python multithread file processing

    - by Napseis
    I have a large number of files to process. I have written a script that get, sort and plot the datas I want. So far, so good. I have tested it and it gives the desired result. Then I wanted to do this using multithreading. I have looked into the doc and examples on the internet, and using one thread in my program works fine. But when I use more, at some point I get random matplotlib error, and I suspect some conflict there, even though I use a function with names for the plots, and iI can't see where the problem could be. Here is the whole script should you need more comment, i'll add them. Thank you. #!/usr/bin/python import matplotlib matplotlib.use('GTKAgg') import numpy as np from scipy.interpolate import griddata import matplotlib.pyplot as plt import matplotlib.colors as mcl from matplotlib import rc #for latex import time as tm import sys import threading import Queue #queue in 3.2 and Queue in 2.7 ! import pdb #the debugger rc('text', usetex=True)#for latex map=0 #initialize the map index. It will be use to index the array like this: array[map,[x,y]] time=np.zeros(1) #an array to store the time middle_h=np.zeros((0,3)) #x phi c #for the middle of the box current_file=open("single_void_cyl_periodic_phi_c_middle_h_out",'r') for line in current_file: if line.startswith('# === time'): map+=1 np.append(time,[float(line.strip('# === time '))]) elif line.startswith('#'): pass else: v=np.fromstring(line,dtype=float,sep=' ') middle_h=np.vstack( (middle_h,v[[1,3,4]]) ) current_file.close() middle_h=middle_h.reshape((map,-1,3)) #3d array: map, x, phi,c ##### def load_and_plot(): #will load a map file, and plot it along with the corresponding profile loaded before while not exit_flag: print("fecthing work ...") #try: if not tasks_queue.empty(): map_index=tasks_queue.get() print("----> working on map: %s" %map_index) x,y,zp=np.loadtxt("single_void_cyl_growth_periodic_post_map_"+str(map_index),unpack=True, usecols=[1, 2,3]) for i,el in enumerate(zp): if el<0.: zp[i]=0. xv=np.unique(x) yv=np.unique(y) X,Y= np.meshgrid(xv,yv) Z = griddata((x, y), zp, (X, Y),method='nearest') figure=plt.figure(num=map_index,figsize=(14, 8)) ax1=plt.subplot2grid((2,2),(0,0)) ax1.plot(middle_h[map_index,:,0],middle_h[map_index,:,1],'*b') ax1.grid(True) ax1.axis([-15, 15, 0, 1]) ax1.set_title('Profiles') ax1.set_ylabel(r'$\phi$') ax1.set_xlabel('x') ax2=plt.subplot2grid((2,2),(1,0)) ax2.plot(middle_h[map_index,:,0],middle_h[map_index,:,2],'*r') ax2.grid(True) ax2.axis([-15, 15, 0, 1]) ax2.set_ylabel('c') ax2.set_xlabel('x') ax3=plt.subplot2grid((2,2),(0,1),rowspan=2,aspect='equal') sub_contour=ax3.contourf(X,Y,Z,np.linspace(0,1,11),vmin=0.) figure.colorbar(sub_contour,ax=ax3) figure.savefig('single_void_cyl_'+str(map_index)+'.png') plt.close(map_index) tasks_queue.task_done() else: print("nothing left to do, other threads finishing,sleeping 2 seconds...") tm.sleep(2) # except: # print("failed this time: %s" %map_index+". Sleeping 2 seconds") # tm.sleep(2) ##### exit_flag=0 nb_threads=2 tasks_queue=Queue.Queue() threads_list=[] jobs=list(range(map)) #each job is composed of a map print("inserting jobs in the queue...") for job in jobs: tasks_queue.put(job) print("done") #launch the threads for i in range(nb_threads): working_bee=threading.Thread(target=load_and_plot) working_bee.daemon=True print("starting thread "+str(i)+' ...') threads_list.append(working_bee) working_bee.start() #wait for all tasks to be treated tasks_queue.join() #flip the flag, so the threads know it's time to stop exit_flag=1 for t in threads_list: print("waiting for threads %s to stop..."%t) t.join() print("all threads stopped")

    Read the article

  • I don't understand how work call_once

    - by SABROG
    Please help me understand how work call_once Here is thread-safe code. I don't understand why this need Thread Local Storage and global_epoch variables. Variable _fast_pthread_once_per_thread_epoch can be changed to constant/enum like {FAST_PTHREAD_ONCE_INIT, BEING_INITIALIZED, FINISH_INITIALIZED}. Why needed count calls in global_epoch? I think this code can be rewriting with logc: if flag FINISH_INITIALIZED do nothing, else go to block with mutexes and this all. #ifndef FAST_PTHREAD_ONCE_H #define FAST_PTHREAD_ONCE_H #include #include typedef sig_atomic_t fast_pthread_once_t; #define FAST_PTHREAD_ONCE_INIT SIG_ATOMIC_MAX extern __thread fast_pthread_once_t _fast_pthread_once_per_thread_epoch; #ifdef __cplusplus extern "C" { #endif extern void fast_pthread_once( pthread_once_t *once, void (*func)(void) ); inline static void fast_pthread_once_inline( fast_pthread_once_t *once, void (*func)(void) ) { fast_pthread_once_t x = *once; /* unprotected access */ if ( x _fast_pthread_once_per_thread_epoch ) { fast_pthread_once( once, func ); } } #ifdef __cplusplus } #endif #endif FAST_PTHREAD_ONCE_H Source fast_pthread_once.c The source is written in C. The lines of the primary function are numbered for reference in the subsequent correctness argument. #include "fast_pthread_once.h" #include static pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER; /* protects global_epoch and all fast_pthread_once_t writes */ static pthread_cond_t cv = PTHREAD_COND_INITIALIZER; /* signalled whenever a fast_pthread_once_t is finalized */ #define BEING_INITIALIZED (FAST_PTHREAD_ONCE_INIT - 1) static fast_pthread_once_t global_epoch = 0; /* under mu */ __thread fast_pthread_once_t _fast_pthread_once_per_thread_epoch; static void check( int x ) { if ( x == 0 ) abort(); } void fast_pthread_once( fast_pthread_once_t *once, void (*func)(void) ) { /*01*/ fast_pthread_once_t x = *once; /* unprotected access */ /*02*/ if ( x _fast_pthread_once_per_thread_epoch ) { /*03*/ check( pthread_mutex_lock(µ) == 0 ); /*04*/ if ( *once == FAST_PTHREAD_ONCE_INIT ) { /*05*/ *once = BEING_INITIALIZED; /*06*/ check( pthread_mutex_unlock(µ) == 0 ); /*07*/ (*func)(); /*08*/ check( pthread_mutex_lock(µ) == 0 ); /*09*/ global_epoch++; /*10*/ *once = global_epoch; /*11*/ check( pthread_cond_broadcast(&cv;) == 0 ); /*12*/ } else { /*13*/ while ( *once == BEING_INITIALIZED ) { /*14*/ check( pthread_cond_wait(&cv;, µ) == 0 ); /*15*/ } /*16*/ } /*17*/ _fast_pthread_once_per_thread_epoch = global_epoch; /*18*/ check (pthread_mutex_unlock(µ) == 0); } } This code from BOOST: #ifndef BOOST_THREAD_PTHREAD_ONCE_HPP #define BOOST_THREAD_PTHREAD_ONCE_HPP // once.hpp // // (C) Copyright 2007-8 Anthony Williams // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include #include #include #include "pthread_mutex_scoped_lock.hpp" #include #include #include namespace boost { struct once_flag { boost::uintmax_t epoch; }; namespace detail { BOOST_THREAD_DECL boost::uintmax_t& get_once_per_thread_epoch(); BOOST_THREAD_DECL extern boost::uintmax_t once_global_epoch; BOOST_THREAD_DECL extern pthread_mutex_t once_epoch_mutex; BOOST_THREAD_DECL extern pthread_cond_t once_epoch_cv; } #define BOOST_ONCE_INITIAL_FLAG_VALUE 0 #define BOOST_ONCE_INIT {BOOST_ONCE_INITIAL_FLAG_VALUE} // Based on Mike Burrows fast_pthread_once algorithm as described in // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2444.html template void call_once(once_flag& flag,Function f) { static boost::uintmax_t const uninitialized_flag=BOOST_ONCE_INITIAL_FLAG_VALUE; static boost::uintmax_t const being_initialized=uninitialized_flag+1; boost::uintmax_t const epoch=flag.epoch; boost::uintmax_t& this_thread_epoch=detail::get_once_per_thread_epoch(); if(epoch #endif I right understand, boost don't use atomic operation, so code from boost not thread-safe?

    Read the article

  • surfaceDestroyed called out of turn

    - by Avasulthiris
    I'm currently developing on minimum sdk version 3 (Android 1.5 - cupcake) and I'm having a strange unexplained issue that I have not been able to solve on my own. It is now becoming a rather urgent issue as I've already missed 1 deadline... I'm writing a high-level library to make long term android development easier and quicker. The one specific module has to capture images for a application... I've gotten everything right so far over the last couple months, except this one little thing and I don't know what to do any more: When I use the Camera object and implement a SurfaceHolder.Callback, the methods surfaceCreated() and surfaceChanged() are called one after the other. Then when the activity finishes, surfaceDestroyed() is called. This is how it should be, but when I stick the exact same code in my library (plain Java library that references the Android API - not in an activity), surfaceDestroyed() is called directly after created and changed. As a result - the camera object is closed before I can use it and the application force closes. What a pain. I can't do anything! This method call is controlled by the device.. Why does the surface close for no reason? Even when I post it to run on the activity thread through my own invokeAndWait(Runnable) method, like I do for many other things. I have 5 different working examples of different ways and implementations of capturing images in android but I still get the same issue when I plug it into my library. I don't understand what the difference is. The code is pretty much the same - and I post all the related code to the UI thread so its not a thread handling issue or anything like that. I've rewritten it about 20 times in different ways - same issue every time.. The only other way to approach it that I know of is creating a new Camera and setting it to the VideoView. The android source (c++ native code) however provides no Camera constructor, only an open() method which automatically forwards the camera's state to 'prepared' but I can only set the camera to the VideoView from the 'initialized' state. Pretty silly, I know, but there is no way around it unless I modify the Android library source code haha. not an option! The API does not allow for this method - you are expected to use it like my first example. So essentially - i just need to understand exactly why surfaceDestroyed() is called out of turn and if there is anything I can do to avoid it closing? If i can just understand the exact logic behind it and how it works! The documentation isn't much help! Secondly, if someone knows of any alternative ways to do it, as my second example, but hopefully one which the API actually allows for? haha Thanks guys. I would post code, but its fairly complicated, a couple thousand lines for this specific class and it would probably take a couple days to explain with all the threading and event listeners and what not. I just need help with this 1 single thing. Please let me know if you have any questions.

    Read the article

  • Random Complete System Unresponsiveness Running Mathematical Functions

    - by Computer Guru
    I have a program that loads a file (anywhere from 10MB to 5GB) a chunk at a time (ReadFile), and for each chunk performs a set of mathematical operations (basically calculates the hash). After calculating the hash, it stores info about the chunk in an STL map (basically <chunkID, hash>) and then writes the chunk itself to another file (WriteFile). That's all it does. This program will cause certain PCs to choke and die. The mouse begins to stutter, the task manager takes 2 min to show, ctrl+alt+del is unresponsive, running programs are slow.... the works. I've done literally everything I can think of to optimize the program, and have triple-checked all objects. What I've done: Tried different (less intensive) hashing algorithms. Switched all allocations to nedmalloc instead of the default new operator Switched from stl::map to unordered_set, found the performance to still be abysmal, so I switched again to Google's dense_hash_map. Converted all objects to store pointers to objects instead of the objects themselves. Caching all Read and Write operations. Instead of reading a 16k chunk of the file and performing the math on it, I read 4MB into a buffer and read 16k chunks from there instead. Same for all write operations - they are coalesced into 4MB blocks before being written to disk. Run extensive profiling with Visual Studio 2010, AMD Code Analyst, and perfmon. Set the thread priority to THREAD_MODE_BACKGROUND_BEGIN Set the thread priority to THREAD_PRIORITY_IDLE Added a Sleep(100) call after every loop. Even after all this, the application still results in a system-wide hang on certain machines under certain circumstances. Perfmon and Process Explorer show minimal CPU usage (with the sleep), no constant reads/writes from disk, few hard pagefaults (and only ~30k pagefaults in the lifetime of the application on a 5GB input file), little virtual memory (never more than 150MB), no leaked handles, no memory leaks. The machines I've tested it on run Windows XP - Windows 7, x86 and x64 versions included. None have less than 2GB RAM, though the problem is always exacerbated under lower memory conditions. I'm at a loss as to what to do next. I don't know what's causing it - I'm torn between CPU or Memory as the culprit. CPU because without the sleep and under different thread priorities the system performances changes noticeably. Memory because there's a huge difference in how often the issue occurs when using unordered_set vs Google's dense_hash_map. What's really weird? Obviously, the NT kernel design is supposed to prevent this sort of behavior from ever occurring (a user-mode application driving the system to this sort of extreme poor performance!?)..... but when I compile the code and run it on OS X or Linux (it's fairly standard C++ throughout) it performs excellently even on poor machines with little RAM and weaker CPUs. What am I supposed to do next? How do I know what the hell it is that Windows is doing behind the scenes that's killing system performance, when all the indicators are that the application itself isn't doing anything extreme? Any advice would be most welcome.

    Read the article

  • Unnecessary Java context switches

    - by Paul Morrison
    I have a network of Java Threads (Flow-Based Programming) communicating via fixed-capacity channels - running under WindowsXP. What we expected, based on our experience with "green" threads (non-preemptive), would be that threads would switch context less often (thus reducing CPU time) if the channels were made bigger. However, we found that increasing channel size does not make any difference to the run time. What seems to be happening is that Java decides to switch threads even though channels aren't full or empty (i.e. even though a thread doesn't have to suspend), which costs CPU time for no apparent advantage. Also changing Thread priorities doesn't make any observable difference. My question is whether there is some way of persuading Java not to make unnecessary context switches, but hold off switching until it is really necessary to switch threads - is there some way of changing Java's dispatching logic? Or is it reacting to something I didn't pay attention to?! Or are there other asynchronism mechanisms, e.g. Thread factories, Runnable(s), maybe even daemons (!). The answer appears to be non-obvious, as so far none of my correspondents has come up with an answer (including most recently two CS profs). Or maybe I'm missing something that's so obvious that people can't imagine my not knowing it... I've added the send and receive code here - not very elegant, but it seems to work...;-) In case you are wondering, I thought the goLock logic in 'send' might be causing the problem, but removing it temporarily didn't make any difference. I have added the code for send and receive... public synchronized Packet receive() { if (isDrained()) { return null; } while (isEmpty()) { try { wait(); } catch (InterruptedException e) { close(); return null; } if (isDrained()) { return null; } } if (isDrained()) { return null; } if (isFull()) { notifyAll(); // notify other components waiting to send } Packet packet = array[receivePtr]; array[receivePtr] = null; receivePtr = (receivePtr + 1) % array.length; //notifyAll(); // only needed if it was full usedSlots--; packet.setOwner(receiver); if (null == packet.getContent()) { traceFuncs("Received null packet"); } else { traceFuncs("Received: " + packet.toString()); } return packet; } synchronized boolean send(final Packet packet, final OutputPort op) { sender = op.sender; if (isClosed()) { return false; } while (isFull()) { try { wait(); } catch (InterruptedException e) { indicateOneSenderClosed(); return false; } sender = op.sender; } if (isClosed()) { return false; } try { receiver.goLock.lockInterruptibly(); } catch (InterruptedException ex) { return false; } try { packet.clearOwner(); array[sendPtr] = packet; sendPtr = (sendPtr + 1) % array.length; usedSlots++; // move this to here if (receiver.getStatus() == StatusValues.DORMANT || receiver.getStatus() == StatusValues.NOT_STARTED) { receiver.activate(); // start or wake up if necessary } else { notifyAll(); // notify receiver // other components waiting to send to this connection may also get // notified, // but this is handled by while statement } sender = null; Component.network.active = true; } finally { receiver.goLock.unlock(); } return true; }

    Read the article

  • UI not updated while using ProgressMonitorInputStream in Swing to monitor compressed file decompress

    - by Bozhidar Batsov
    I'm working on swing application that relies on an embedded H2 database. Because I don't want to bundle the database with the app(the db is frequently updated and I want new users of the app to start with a recent copy), I've implemented a solution which downloads a compressed copy of the db the first time the application is started and extracts it. Since the extraction process might be slow I've added a ProgressMonitorInputStream to show to progress of the extraction process - unfortunately when the extraction starts, the progress dialog shows up but it's not updated at all. It seems like to events are getting through to the event dispatch thread. Here is the method: public static String extractDbFromArchive(String pathToArchive) { if (SwingUtilities.isEventDispatchThread()) { System.out.println("Invoking on event dispatch thread"); } // Get the current path, where the database will be extracted String currentPath = System.getProperty("user.home") + File.separator + ".spellbook" + File.separator; LOGGER.info("Current path: " + currentPath); try { //Open the archive FileInputStream archiveFileStream = new FileInputStream(pathToArchive); // Read two bytes from the stream before it used by CBZip2InputStream for (int i = 0; i < 2; i++) { archiveFileStream.read(); } // Open the gzip file and open the output file CBZip2InputStream bz2 = new CBZip2InputStream(new ProgressMonitorInputStream( null, "Decompressing " + pathToArchive, archiveFileStream)); FileOutputStream out = new FileOutputStream(ARCHIVED_DB_NAME); LOGGER.info("Decompressing the tar file..."); // Transfer bytes from the compressed file to the output file byte[] buffer = new byte[1024]; int len; while ((len = bz2.read(buffer)) > 0) { out.write(buffer, 0, len); } // Close the file and stream bz2.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } try { TarInputStream tarInputStream = null; TarEntry tarEntry; tarInputStream = new TarInputStream(new ProgressMonitorInputStream( null, "Extracting " + ARCHIVED_DB_NAME, new FileInputStream(ARCHIVED_DB_NAME))); tarEntry = tarInputStream.getNextEntry(); byte[] buf1 = new byte[1024]; LOGGER.info("Extracting tar file"); while (tarEntry != null) { //For each entry to be extracted String entryName = currentPath + tarEntry.getName(); entryName = entryName.replace('/', File.separatorChar); entryName = entryName.replace('\\', File.separatorChar); LOGGER.info("Extracting entry: " + entryName); FileOutputStream fileOutputStream; File newFile = new File(entryName); if (tarEntry.isDirectory()) { if (!newFile.mkdirs()) { break; } tarEntry = tarInputStream.getNextEntry(); continue; } fileOutputStream = new FileOutputStream(entryName); int n; while ((n = tarInputStream.read(buf1, 0, 1024)) > -1) { fileOutputStream.write(buf1, 0, n); } fileOutputStream.close(); tarEntry = tarInputStream.getNextEntry(); } tarInputStream.close(); } catch (Exception e) { } currentPath += "db" + File.separator + DB_FILE_NAME; if (!currentPath.isEmpty()) { LOGGER.info("DB placed in : " + currentPath); } return currentPath; } This method gets invoked on the event dispatch thread (SwingUtilities.isEventDispatchThread() returns true) so the UI components should be updated. I haven't implemented this as an SwingWorker since I need to wait for the extraction anyways before I can proceed with the initialization of the program. This method get invoked before the main JFrame of the application is visible. I don't won't a solution based on SwingWorker + property changed listeners - I think that the ProgressMonitorInputStream is exactly what I need, but I guess I'm not doing something right. I'm using Sun JDK 1.6.18. Any help would be greatly appreciated.

    Read the article

  • log-back and thirdparty writing to stdout. How to stop them getting interleaved.

    - by David Roussel
    First some background. I have a batch-type java process run from a DOS batch script. All the java logging goes to stdout, and the batch script redirects the stdout to a file. (This is good for me because I can ECHO from the script and it gets into the log file, so I can see all the java JVM command line args, which is great for debugging.) I may not I use slf4j API, and for the backend I used to use log4j, but recently switched to logback-classic. Although all my application code uses slf4j, I have a third party library that does it's own logging (not using a standard API) which also gets written to stdout. The problem is that sometimes log lines get mixed up and don't cleanly appear on separate lines. Here is an example of some messed up output: 2010-05-28 18:00:44.783 [thread-1 ] INFO CreditCorrelationElementBuilderImpl - Bump parameters exist for scenario, now attempting bumping. [indexDisplayName=STANDARD_S1_v300] 2010-05-28 18:01:43.517 [thread-1 ] INFO CreditCorrelationElementBuilderImpl - Found adjusted point in data, now applying bump. [point=0.144040000000000] 2010-05-28 18:01:58.642 [thread-1 ] DEBUG com.company.request.Request - Generated request for [dealName=XXX_20050225_01[5],dealType=GENERIC_XXX,correlationType=2,copulaType=1] in 73.8 s, Simon Stopwatch: [sys1.batchpricer.reqgen.gen INHERIT] total 1049 s, counter 24, max 74.1 s, min 212 ms 2010-05-28 18:05/28/10 18:02:20.236 INFO: [ServiceEvent] SubmittedTask:BC-STRESS_04_FZBC-2010-05-21-545024448189310126-23 01:58.658 [req-writer-2b ] INFO .c.g.r.o.OptionalFileDocumentOutput - Writing request XML to \\filserver\dir\file1.xml - write time: 21.4 ms - Simon Stopwatch: [sys1.batchpricer.reqgen.writeinputfile INHERIT] total 905 ms, counter 24, max 109 ms, min 10.8 ms 2010-05-28 18:02:33.626 [ResponseCallbacks-1: DriverJobSpace$TakeJobRunner$1] ERROR c.c.s.s.D.CalculatorCallback - Id:23 no deal found !! 2010-0505/28/10 18:02:50.267 INFO: [ServiceEvent] CompletedTask:BC-STRESS_04_FZBC-2010-05-21-545024448189310126-23:Total:24 Now comparing back to older log files, it seems the problem didn't occur when using log4j as the logging backend. So logback must be doing something different. The problem seems to be that although PrintStream.write(byte buf[], int off, int len) is synchronized, however I can see in ch.qos.logback.core.joran.spi.ConsoleTarget that System.out.write(int b) is the only write method called. So inbetween logback outputting each byte, the thirdparty library is managing to write a whole string to the stdout. (Not only is this cause me a problem, but it must also be a little inefficient?) Is there any other fix to this interleaving problem than patching the code to ConsoleTarget so it implments the other write methods? Any nice work arounds. Or should I just file a bug report? Here is my logback.xml: <configuration> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%-16thread] %-5level %-35.35logger{30} - %msg%n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="STDOUT" /> </root> </configuration> I'm using logback 0.9.20 with java 1.6.0_07.

    Read the article

  • Dynamically loading modules in Python (+ multi processing question)

    - by morpheous
    I am writing a Python package which reads the list of modules (along with ancillary data) from a configuration file. I then want to iterate through each of the dynamically loaded modules and invoke a do_work() function in it which will spawn a new process, so that the code runs ASYNCHRONOUSLY in a separate process. At the moment, I am importing the list of all known modules at the beginning of my main script - this is a nasty hack I feel, and is not very flexible, as well as being a maintenance pain. This is the function that spawns the processes. I will like to modify it to dynamically load the module when it is encountered. The key in the dictionary is the name of the module containing the code: def do_work(work_info): for (worker, dataset) in work_info.items(): #import the module defined by variable worker here... # [Edit] NOT using threads anymore, want to spawn processes asynchronously here... #t = threading.Thread(target=worker.do_work, args=[dataset]) # I'll NOT dameonize since spawned children need to clean up on shutdown # Since the threads will be holding resources #t.daemon = True #t.start() Question 1 When I call the function in my script (as written above), I get the following error: AttributeError: 'str' object has no attribute 'do_work' Which makes sense, since the dictionary key is a string (name of the module to be imported). When I add the statement: import worker before spawning the thread, I get the error: ImportError: No module named worker This is strange, since the variable name rather than the value it holds are being used - when I print the variable, I get the value (as I expect) whats going on? Question 2 As I mentioned in the comments section, I realize that the do_work() function written in the spawned children needs to cleanup after itself. My understanding is to write a clean_up function that is called when do_work() has completed successfully, or an unhandled exception is caught - is there anything more I need to do to ensure resources don't leak or leave the OS in an unstable state? Question 3 If I comment out the t.daemon flag statement, will the code stil run ASYNCHRONOUSLY?. The work carried out by the spawned children are pretty intensive, and I don't want to have to be waiting for one child to finish before spawning another child. BTW, I am aware that threading in Python is in reality, a kind of time sharing/slicing - thats ok Lastly is there a better (more Pythonic) way of doing what I'm trying to do? [Edit] After reading a little more about Pythons GIL and the threading (ahem - hack) in Python, I think its best to use separate processes instead (at least IIUC, the script can take advantage of multiple processes if they are available), so I will be spawning new processes instead of threads. I have some sample code for spawning processes, but it is a bit trivial (using lambad functions). I would like to know how to expand it, so that it can deal with running functions in a loaded module (like I am doing above). This is a snippet of what I have: def do_mp_bench(): q = mp.Queue() # Not only thread safe, but "process safe" p1 = mp.Process(target=lambda: q.put(sum(range(10000000)))) p2 = mp.Process(target=lambda: q.put(sum(range(10000000)))) p1.start() p2.start() r1 = q.get() r2 = q.get() return r1 + r2 How may I modify this to process a dictionary of modules and run a do_work() function in each loaded module in a new process?

    Read the article

  • Listening for TCP and UDP requests on the same port

    - by user339328
    I am writing a Client/Server set of programs Depending on the operation requested by the client, I use make TCP or UDP request. Implementing the client side is straight-forward, since I can easily open connection with any protocol and send the request to the server-side. On the servers-side, on the other hand, I would like to listen both for UDP and TCP connections on the same port. Moreover, I like the the server to open new thread for each connection request. I have adopted the approach explained in: link text I have extended this code sample by creating new threads for each TCP/UDP request. This works correctly if I use TCP only, but it fails when I attempt to make UDP bindings. Please give me any suggestion how can I correct this. tnx Here is the Server Code: public class Server { public static void main(String args[]) { try { int port = 4444; if (args.length > 0) port = Integer.parseInt(args[0]); SocketAddress localport = new InetSocketAddress(port); // Create and bind a tcp channel to listen for connections on. ServerSocketChannel tcpserver = ServerSocketChannel.open(); tcpserver.socket().bind(localport); // Also create and bind a DatagramChannel to listen on. DatagramChannel udpserver = DatagramChannel.open(); udpserver.socket().bind(localport); // Specify non-blocking mode for both channels, since our // Selector object will be doing the blocking for us. tcpserver.configureBlocking(false); udpserver.configureBlocking(false); // The Selector object is what allows us to block while waiting // for activity on either of the two channels. Selector selector = Selector.open(); tcpserver.register(selector, SelectionKey.OP_ACCEPT); udpserver.register(selector, SelectionKey.OP_READ); System.out.println("Server Sterted on port: " + port + "!"); //Load Map Utils.LoadMap("mapa"); System.out.println("Server map ... LOADED!"); // Now loop forever, processing client connections while(true) { try { selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); // Iterate through the Set of keys. for (Iterator<SelectionKey> i = keys.iterator(); i.hasNext();) { SelectionKey key = i.next(); i.remove(); Channel c = key.channel(); if (key.isAcceptable() && c == tcpserver) { new TCPThread(tcpserver.accept().socket()).start(); } else if (key.isReadable() && c == udpserver) { new UDPThread(udpserver.socket()).start(); } } } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); System.err.println(e); System.exit(1); } } } The UDPThread code: public class UDPThread extends Thread { private DatagramSocket socket = null; public UDPThread(DatagramSocket socket) { super("UDPThread"); this.socket = socket; } @Override public void run() { byte[] buffer = new byte[2048]; try { DatagramPacket packet = new DatagramPacket(buffer, buffer.length); socket.receive(packet); String inputLine = new String(buffer); String outputLine = Utils.processCommand(inputLine.trim()); DatagramPacket reply = new DatagramPacket(outputLine.getBytes(), outputLine.getBytes().length, packet.getAddress(), packet.getPort()); socket.send(reply); } catch (IOException e) { e.printStackTrace(); } socket.close(); } } I receive: Exception in thread "UDPThread" java.nio.channels.IllegalBlockingModeException at sun.nio.ch.DatagramSocketAdaptor.receive(Unknown Source) at server.UDPThread.run(UDPThread.java:25) 10x

    Read the article

  • Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host

    - by xnoor
    i have an update server that sends client updates through TCP port 12000, the sending of a single file is successful only the first time, but after that i get an error message on the server "Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host", if i restart the update service on the server, it works again only one, i have normal multithreaded windows service SERVER CODE namespace WSTSAU { public partial class ApplicationUpdater : ServiceBase { private Logger logger = LogManager.GetCurrentClassLogger(); private int _listeningPort; private int _ApplicationReceivingPort; private string _setupFilename; private string _startupPath; public ApplicationUpdater() { InitializeComponent(); } protected override void OnStart(string[] args) { init(); logger.Info("after init"); Thread ListnerThread = new Thread(new ThreadStart(StartListener)); ListnerThread.IsBackground = true; ListnerThread.Start(); logger.Info("after thread start"); } private void init() { _listeningPort = Convert.ToInt16(ConfigurationSettings.AppSettings["ListeningPort"]); _setupFilename = ConfigurationSettings.AppSettings["SetupFilename"]; _startupPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6); } private void StartListener() { try { logger.Info("Listening Started"); ThreadPool.SetMinThreads(50, 50); TcpListener listener = new TcpListener(_listeningPort); listener.Start(); while (true) { TcpClient c = listener.AcceptTcpClient(); ThreadPool.QueueUserWorkItem(ProcessReceivedMessage, c); } } catch (Exception ex) { logger.Error(ex.Message); } } void ProcessReceivedMessage(object c) { try { TcpClient tcpClient = c as TcpClient; NetworkStream Networkstream = tcpClient.GetStream(); byte[] _data = new byte[1024]; int _bytesRead = 0; _bytesRead = Networkstream.Read(_data, 0, _data.Length); MessageContainer messageContainer = new MessageContainer(); messageContainer = SerializationManager.XmlFormatterByteArrayToObject(_data, messageContainer) as MessageContainer; switch (messageContainer.messageType) { case MessageType.ApplicationUpdateMessage: ApplicationUpdateMessage appUpdateMessage = new ApplicationUpdateMessage(); appUpdateMessage = SerializationManager.XmlFormatterByteArrayToObject(messageContainer.messageContnet, appUpdateMessage) as ApplicationUpdateMessage; Func<ApplicationUpdateMessage, bool> HandleUpdateRequestMethod = HandleUpdateRequest; IAsyncResult cookie = HandleUpdateRequestMethod.BeginInvoke(appUpdateMessage, null, null); bool WorkerThread = HandleUpdateRequestMethod.EndInvoke(cookie); break; } } catch (Exception ex) { logger.Error(ex.Message); } } private bool HandleUpdateRequest(ApplicationUpdateMessage appUpdateMessage) { try { TcpClient tcpClient = new TcpClient(); NetworkStream networkStream; FileStream fileStream = null; tcpClient.Connect(appUpdateMessage.receiverIpAddress, appUpdateMessage.receiverPortNumber); networkStream = tcpClient.GetStream(); fileStream = new FileStream(_startupPath + "\\" + _setupFilename, FileMode.Open, FileAccess.Read); FileInfo fi = new FileInfo(_startupPath + "\\" + _setupFilename); BinaryReader binFile = new BinaryReader(fileStream); FileUpdateMessage fileUpdateMessage = new FileUpdateMessage(); fileUpdateMessage.fileName = fi.Name; fileUpdateMessage.fileSize = fi.Length; MessageContainer messageContainer = new MessageContainer(); messageContainer.messageType = MessageType.FileProperties; messageContainer.messageContnet = SerializationManager.XmlFormatterObjectToByteArray(fileUpdateMessage); byte[] messageByte = SerializationManager.XmlFormatterObjectToByteArray(messageContainer); networkStream.Write(messageByte, 0, messageByte.Length); int bytesSize = 0; byte[] downBuffer = new byte[2048]; while ((bytesSize = fileStream.Read(downBuffer, 0, downBuffer.Length)) > 0) { networkStream.Write(downBuffer, 0, bytesSize); } fileStream.Close(); tcpClient.Close(); networkStream.Close(); return true; } catch (Exception ex) { logger.Info(ex.Message); return false; } finally { } } protected override void OnStop() { } } i have to note something that my windows service (server) is multithreaded.. i hope anyone can help with this

    Read the article

  • How do you place an Excel Sheet/Workbook onto a C# .NET Winform?

    - by incognick
    I am trying to create a stand alone application in Visual Studio 2008 C# .Net that will house Excel Workbooks (2007). I am using Office.Interop in order to create the Excel application and I open the workbooks via Workbooks.Open(...). The Interop does not provide any functionality to "move" the workbooks onto a form so I turned to P/Invoke Win32 library. I am able to move the entire excel application onto a WinForm with great success: // pseudo code to give you the idea excel = new Excel.ApplicationClass(); SetParent(excel.Hwnd, form.handle); This allows me to customize the form and control user input. All right click commands and formula editing work properly. Now, the issue I run into is when I want to open two workbooks in two separate forms. I do this by creating two excel application classes and placing each of those in their own form. When I try to reference one workbook to another workbook via =[Book2]Sheet1!A1, for example, it does not update. This is expected as each application is running under its own thread/process. Here are the alternatives I have tried. If you have any suggestions I would be greatly appreciative.(OLE is not an option. VSTO must be available) Create a single application class and move the workbook window into my form. Results: The window moves into my form and displays correctly, however, no right click or left click works on the form and it never gains focus. (I have tried to manually set focus and it does not work either). My guess is, by moving the window outside of the XLDESK application (viewable in Spy++ for Excel Application), the workbook application (EXCEL7) does not receive the correct window messages to gain focus and to behave properly. This leads me to: Move the XLDESK window handle into my form. Results: This allows the workbook to be click-able again but also has an undesired result of moving all child windows into the same form. Create a main excel application that creates workbooks. Create a new excel application for each new window. Move the workbook under the new excel application XLDESK window. Results: This also has the same effect of the 1st option. Unable to click in the workbook. This must mean that the thread that created the workbook is also responsible for the events. Create a windows hook that watches the WndProc procedure. Results: No events watched. The targeted thread must export the hook proc in a DLL export call. Excel does not do this and thus you cannot inject into it's DLL (unless someone can prove me wrong). I am able to watch all threads within my own process but not from an outside process. Excel is created as a separate process. Subclass NativeWindow. Results: Same as #4. After I move the window into my form, all events are captured up until the mouse is directly over the excel sheet making the sheet seem unclickable. One idea I haven't tried yet is just to continually save the excel sheet as the user edits it. This should update all references but I would feel this would cause poor system performance. There will be numerous chart references as well and I'm not sure if this solution would cause problems further down the road. I think in the end, all the workbooks need to be created by the same Excel Application and then moved to get the desired results but I can't seem to find the correct way to move the windows without disabling the user input in the process. Any suggestions?

    Read the article

  • Loading multiple copies of a group of DLLs in the same process

    - by george
    Background I'm maintaining a plugin for an application. I'm Using Visual C++ 2003. The plugin is composed of several DLLs - there's the main DLL, that's the one that the application loads using LoadLibrary, and there are several utility DLLs that are used by the main DLL and by each other. Dependencies generally look like this: plugin.dll - utilA.dll, utilB.dll utilA.dll - utilB.dll utilB.dll - utilA.dll, utilC.dll You get the picture. Some of the dependencies between the DLLs are load-time and some run-time. All the DLL files are stored in the executable's directory (not a requirement, just how it works now). The problem There's a new requirement - running multiple instances of the plugin within the application. The application runs each instance of a plugin in its own thread, i.e. each thread calls The plugin's code, however, is nothing but thread-safe - lots of global variables etc.. Unfortunately, fixing the whole thing isn't currently an option, so I need a way to load multiple (at most 3) copies of the plugin's DLLs in the same process. Option 1: The distinct names approach Creating 3 copies of each DLL file, so that each file has a distinct name. e.g. plugin1.dll, plugin2.dll, plugin3.dll, utilA1.dll, utilA2.dll, utilA3.dll, utilB1.dll, etc.. The application will load plugin1.dll, plugin2.dll and plugin3.dll. The files will be in the executable's directory. For each group of DLLs to know each other by name (so the inter-dependencies work), the names need to be known at compilation time - meaning the DLLs need to be compiled multiple times, only each time with different output file names. Not very complicated, but I'd hate having 3 copies of the VS project files, and don't like having to compile the same files over and over. Option 2: The side-by-side assemblies approach Creating 3 copies of the DLL files, each group in its own directory, and defining each group as an assembly by putting an assembly manifest file in the directory, listing the plugin's DLLs. Each DLL will have an application manifest pointing to the assembly, so that the loader finds the copies of the utility DLLs that reside in the same directory. The manifest needs to be embedded for it to be found when a DLL is loaded using LoadLibrary. I'll use mt.exe from a later VS version for the job, since VS2003 has no built-in manifest embedding support. I've tried this approach with partial success - dependencies are found during load-time of the DLLs, but not when a DLL function is called that loads another DLL. This seems to be the expected behavior according to this article - A DLL's activation context is only used at the DLL's load-time, and afterwards it's deactivated and the process's activation context is used. I haven't yet tried working around this using ISOLATION_AWARE_ENABLED. Questions Got any other options? Any quick & dirty solution will do. :-) Will ISOLATION_AWARE_ENABLED even work with VS2003? Comments will be greatly appreciated. Thanks!

    Read the article

  • Need a hand understanding this Java code please :-)

    - by Brian
    Hi all, Just wondering if anyone would be able to take a look at this code for implementing the quicksort algorithm and answer me a few questions, please :-) public class Run { /*************************************************************************** * Quicksort code from Sedgewick 7.1, 7.2. **************************************************************************/ public static void quicksort(double[] a) { //shuffle(a); // to guard against worst-case quicksort(a, 0, a.length - 1, 0); } static void quicksort(final double[] a, final int left, final int right, final int tdepth) { if (right <= left) return; final int i = partition(a, left, right); if ((tdepth < 4) && ((i - left) > 1000)) { final Thread t = new Thread() { public void run() { quicksort(a, left, i - 1, tdepth + 1); } }; t.start(); quicksort(a, i + 1, right, tdepth + 1); try { t.join(); } catch (InterruptedException e) { throw new RuntimeException("Cancelled", e); } } else { quicksort(a, left, i - 1, tdepth); quicksort(a, i + 1, right, tdepth); } } // partition a[left] to a[right], assumes left < right private static int partition(double[] a, int left, int right) { int i = left - 1; int j = right; while (true) { while (less(a[++i], a[right])) // find item on left to swap ; // a[right] acts as sentinel while (less(a[right], a[--j])) // find item on right to swap if (j == left) break; // don't go out-of-bounds if (i >= j) break; // check if pointers cross exch(a, i, j); // swap two elements into place } exch(a, i, right); // swap with partition element return i; } // is x < y ? private static boolean less(double x, double y) { return (x < y); } // exchange a[i] and a[j] private static void exch(double[] a, int i, int j) { double swap = a[i]; a[i] = a[j]; a[j] = swap; } // shuffle the array a[] private static void shuffle(double[] a) { int N = a.length; for (int i = 0; i < N; i++) { int r = i + (int) (Math.random() * (N - i)); // between i and N-1 exch(a, i, r); } } // test client public static void main(String[] args) { int N = 5000000; // Integer.parseInt(args[0]); // generate N random real numbers between 0 and 1 long start = System.currentTimeMillis(); double[] a = new double[N]; for (int i = 0; i < N; i++) a[i] = Math.random(); long stop = System.currentTimeMillis(); double elapsed = (stop - start) / 1000.0; System.out.println("Generating input: " + elapsed + " seconds"); // sort them start = System.currentTimeMillis(); quicksort(a); stop = System.currentTimeMillis(); elapsed = (stop - start) / 1000.0; System.out.println("Quicksort: " + elapsed + " seconds"); } } My questions are: What is the purpose of the variable tdepth? Is this considered a "proper" implementation of a parallel quicksort? I ask becuase it doesn't use implements Runnable or extends Thread... If it doesn't already, is it possible to modify this code to use multiple threads? By passing in the number of threads you want to use as a parameter, for example...? Many thanks, Brian

    Read the article

  • Is there a library available which easily can record and replay results of API calls?

    - by Billy ONeal
    I'm working on writing various things that call relatively complicated Win32 API functions. Here's an example: //Encapsulates calling NtQuerySystemInformation buffer management. WindowsApi::AutoArray NtDll::NtQuerySystemInformation( SystemInformationClass toGet ) const { AutoArray result; ULONG allocationSize = 1024; ULONG previousSize; NTSTATUS errorCheck; do { previousSize = allocationSize; result.Allocate(allocationSize); errorCheck = WinQuerySystemInformation(toGet, result.GetAs<void>(), allocationSize, &allocationSize); if (allocationSize <= previousSize) allocationSize = previousSize * 2; } while (errorCheck == 0xC0000004L); if (errorCheck != 0) { THROW_MANUAL_WINDOWS_ERROR(WinRtlNtStatusToDosError(errorCheck)); } return result; } //Client of the above. ProcessSnapshot::ProcessSnapshot() { using Dll::NtDll; NtDll ntdll; AutoArray systemInfoBuffer = ntdll.NtQuerySystemInformation( NtDll::SystemProcessInformation); BYTE * currentPtr = systemInfoBuffer.GetAs<BYTE>(); //Loop through the results, creating Process objects. SYSTEM_PROCESSES * asSysInfo; do { // Loop book keeping asSysInfo = reinterpret_cast<SYSTEM_PROCESSES *>(currentPtr); currentPtr += asSysInfo->NextEntryDelta; //Create the process for the current iteration and fill it with data. std::auto_ptr<ProcImpl> currentProc(ProcFactory( static_cast<unsigned __int32>(asSysInfo->ProcessId), this)); NormalProcess* nptr = dynamic_cast<NormalProcess*>(currentProc.get()); if (nptr) { nptr->SetProcessName(asSysInfo->ProcessName); } // Populate process threads for(ULONG idx = 0; idx < asSysInfo->ThreadCount; ++idx) { SYSTEM_THREADS& sysThread = asSysInfo->Threads[idx]; Thread thread( currentProc.get(), static_cast<unsigned __int32>(sysThread.ClientId.UniqueThread), sysThread.StartAddress); currentProc->AddThread(thread); } processes.push_back(currentProc); } while(asSysInfo->NextEntryDelta != 0); } My problem is in mocking out the NtDll::NtQuerySystemInformation method -- namely, that the data structure returned is complicated (Well, here it's actually relatively simple but it can be complicated), and writing a test which builds the data structure like the API call does can take 5-6 times as long as writing the code that uses the API. What I'd like to do is take a call to the API, and record it somehow, so that I can return that recorded value to the code under test without actually calling the API. The returned structures cannot simply be memcpy'd, because they often contain inner pointers (pointers to other locations in the same buffer). The library in question would need to check for these kinds of things, and be able to restore pointer values to a similar buffer upon replay. (i.e. check each pointer sized value if it could be interpreted as a pointer within the buffer, change that to an offset, and remember to change it back to a pointer on replay -- a false positive rate here is acceptable) Is there anything out there that does anything like this?

    Read the article

  • AsyncTask, inner classes and Buttons states

    - by Intern John Smith
    For a musical application (a sequencer), I have a few buttons static ArrayList<Button> Buttonlist = new ArrayList<Button>(); Buttonlist.add(0,(Button) findViewById(R.id.case_kick1)); Buttonlist.add(1,(Button) findViewById(R.id.case_kick2)); Buttonlist.add(2,(Button) findViewById(R.id.case_kick3)); Buttonlist.add(3,(Button) findViewById(R.id.case_kick4)); Buttonlist.add(4,(Button) findViewById(R.id.case_kick5)); Buttonlist.add(5,(Button) findViewById(R.id.case_kick6)); Buttonlist.add(6,(Button) findViewById(R.id.case_kick7)); Buttonlist.add(7,(Button) findViewById(R.id.case_kick8)); that I activate through onClickListeners with for example Buttonlist.get(0).setActivated(true); I played the activated sound via a loop and ifs : if (Buttonlist.get(k).isActivated()) {mSoundManager.playSound(1); Thread.sleep(250);} The app played fine but I couldn't access the play/pause button when it was playing : I searched and found out about AsyncTasks. I have a nested class PlayPause : class PlayPause extends AsyncTask<ArrayList<Button>,Integer,Void> in which I have this : protected Void doInBackground(ArrayList<Button>... params) { for(int k=0;k<8;k++) { boolean isPlayed = false; if (Buttonlist.get(k).isActivated()) { mSoundManager.playSound(1); isPlayed = true; try {Thread.sleep(250); } catch (InterruptedException e) {e.printStackTrace();}} if(!isPlayed){ try {Thread.sleep(250);} catch (InterruptedException e) {e.printStackTrace();} } } return null; } I launch it via Play.setOnClickListener(new PlayClickListener()); with PlayClickListener : public class PlayClickListener implements OnClickListener { private Tutorial acti; public PlayClickListener(){ super(); } @SuppressWarnings("unchecked") public void onClick(View v) { if(Tutorial.play==0){ Tutorial.play=1; Tutorial.Play.setBackgroundResource(R.drawable.action_down); acti = new Tutorial(); Tutorial.PlayPause myPlayPause = acti.new PlayPause(); myLecture.execute(Tutorial.Buttonlist); } else { Tutorial.play=0; Tutorial.lecture.cancel(true); Tutorial.Play.setBackgroundResource(R.drawable.action); } } } But it doesn't work. when I click on buttons and I touch Play/Pause, I have this : 07-02 11:06:01.350: E/AndroidRuntime(7883): FATAL EXCEPTION: AsyncTask #1 07-02 11:06:01.350: E/AndroidRuntime(7883): Caused by: java.lang.NullPointerException 07-02 11:06:01.350: E/AndroidRuntime(7883): at com.Tutorial.Tutorial$PlayPause.doInBackground(Tutorial.java:603) 07-02 11:06:01.350: E/AndroidRuntime(7883): at com.Tutorial.Tutorial$PlayPause.doInBackground(Tutorial.java:1) And I don't know how to get rid of this error. Obviously, the Asynctask doesn't find the Buttonlist activated status, even if the list is static. I don't know how to access these buttons' states, isPressed doesn't work either. Thanks for reading and helping me !

    Read the article

  • how to fetch meaningful

    - by user1298017
    Hi Every body, I have connected my device to serial port. I am using Javax.comm API to fetch the data from my device. On tapping of card i am reading data as below: newData = inputStream.read(); and able to fetch data : 0 128 161 132 132 132 132 132 132 132 101 65 2 226 99 98 132 132 132 132 132 132 132 132 131 134 164 132 132 132 165 134 132 196 230 167 132 132 132 132 132 132 132 197 196 132 133 132 132 164 197 132 132 198 103 255 How can deciper meaning ful text from it. My code is as below: import java.io.*; import java.util.*; import javax.comm.*; import javax.comm.SerialPort; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; public class NFCReader3 implements Runnable, SerialPortEventListener { static CommPortIdentifier portId; static Enumeration portList; InputStream inputStream; SerialPort serialPort; Thread readThread; int i=0; public static void main(String[] args) { boolean portFound = false; String defaultPort = "COM9"; portList = CommPortIdentifier.getPortIdentifiers(); while (portList.hasMoreElements()) { portId = (CommPortIdentifier) portList.nextElement(); if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { if (portId.getName().equals(defaultPort)) { System.out.println("Found port: "+defaultPort); portFound = true; NFCReader3 reader = new NFCReader3(); } } } if (!portFound) { System.out.println("port " + defaultPort + " not found."); } } public NFCReader3() { try { serialPort = (SerialPort) portId.open("SimpleReadApp2S", 2000); } catch (PortInUseException e) {} try { inputStream = serialPort.getInputStream(); } catch (IOException e) {} try { serialPort.addEventListener(this); } catch (TooManyListenersException e) {} serialPort.notifyOnDataAvailable(true); try { serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); } catch (UnsupportedCommOperationException e) {} readThread = new Thread(this); readThread.start(); } public void run() { try { Thread.sleep(20000); } catch (InterruptedException e) {} } public void serialEvent(SerialPortEvent event) { StringBuffer inputBuffer = new StringBuffer(); int newData = 0; switch (event.getEventType()) { case SerialPortEvent.BI: case SerialPortEvent.OE: case SerialPortEvent.FE: case SerialPortEvent.PE: case SerialPortEvent.CD: case SerialPortEvent.CTS: case SerialPortEvent.DSR: case SerialPortEvent.RI: case SerialPortEvent.OUTPUT_BUFFER_EMPTY: break; case SerialPortEvent.DATA_AVAILABLE: while (newData != -1) { try { newData = inputStream.read(); System.out.print(newData); System.out.print(" "); if (newData == -1) { break; } if ('\r' == (char)newData) { inputBuffer.append('\n'); } else { inputBuffer.append((char)newData); } } catch (IOException ex) { System.out.println("exception"); System.err.println(ex); return; } } break;

    Read the article

  • Fragment method and socket.io

    - by Tolgay Toklar
    I have a method,this method updates an array list in fragment.I can call this method in main activity like this public void getFromUser(String message) { addMessageToFragment("ok"); } public void addMessageToFragment(String message) { Log.w("Step 1",message); frgObj.addMessageToList("asd"); } getFromUser is calling from fragment(when user presses the button) this is working as well.But I am using socket.io in my app,when I try to call this method from socket.io,app is not working. public void on(String event, IOAcknowledge ack, Object... args) { try{ addMessageToFragment("ok"); } catch (JSONException e) {} } When this callback function calls,app is giving this errors: 08-19 11:57:24.813: W/System.err(4962): io.socket.SocketIOException: Exception was thrown in on(String, JSONObject[]). 08-19 11:57:24.813: W/System.err(4962): Message was: 5:::{"name":"listele","args":[{"mesaj":"123","gonderen":"781722165-tolgay007-DKSMIcIYGahPuKXriM83","alici":"tolgay007","blck_id":"781722165-tolgay007","out_username":"Anony-781722","ars_status":1,"longinf":"3aqghef","a_status":1}]} 08-19 11:57:24.813: W/System.err(4962): at io.socket.IOConnection.transportMessage(IOConnection.java:702) 08-19 11:57:24.813: W/System.err(4962): at io.socket.WebsocketTransport.onMessage(WebsocketTransport.java:82) 08-19 11:57:24.813: W/System.err(4962): at org.java_websocket.client.WebSocketClient.onWebsocketMessage(WebSocketClient.java:361) 08-19 11:57:24.813: W/System.err(4962): at org.java_websocket.WebSocketImpl.deliverMessage(WebSocketImpl.java:565) 08-19 11:57:24.813: W/System.err(4962): at org.java_websocket.WebSocketImpl.decodeFrames(WebSocketImpl.java:331) 08-19 11:57:24.813: W/System.err(4962): at org.java_websocket.WebSocketImpl.decode(WebSocketImpl.java:152) 08-19 11:57:24.813: W/System.err(4962): at org.java_websocket.client.WebSocketClient.interruptableRun(WebSocketClient.java:247) 08-19 11:57:24.823: W/System.err(4962): at org.java_websocket.client.WebSocketClient.run(WebSocketClient.java:193) 08-19 11:57:24.823: W/System.err(4962): at java.lang.Thread.run(Thread.java:841) 08-19 11:57:24.823: W/System.err(4962): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. 08-19 11:57:24.823: W/System.err(4962): at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6094) 08-19 11:57:24.823: W/System.err(4962): at android.view.ViewRootImpl.focusableViewAvailable(ViewRootImpl.java:2800) 08-19 11:57:24.823: W/System.err(4962): at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:650) 08-19 11:57:24.823: W/System.err(4962): at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:650) 08-19 11:57:24.823: W/System.err(4962): at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:650) 08-19 11:57:24.823: W/System.err(4962): at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:650) 08-19 11:57:24.823: W/System.err(4962): at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:650) 08-19 11:57:24.823: W/System.err(4962): at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:650) 08-19 11:57:24.823: W/System.err(4962): at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:650) 08-19 11:57:24.823: W/System.err(4962): at android.view.View.setFlags(View.java:8878) 08-19 11:57:24.823: W/System.err(4962): at android.view.View.setFocusableInTouchMode(View.java:6114) 08-19 11:57:24.823: W/System.err(4962): at android.widget.AdapterView.checkFocus(AdapterView.java:718) 08-19 11:57:24.823: W/System.err(4962): at android.widget.AdapterView$AdapterDataSetObserver.onChanged(AdapterView.java:813) 08-19 11:57:24.823: W/System.err(4962): at android.widget.AbsListView$AdapterDataSetObserver.onChanged(AbsListView.java:6280) 08-19 11:57:24.823: W/System.err(4962): at android.database.DataSetObservable.notifyChanged(DataSetObservable.java:37) 08-19 11:57:24.823: W/System.err(4962): at android.widget.BaseAdapter.notifyDataSetChanged(BaseAdapter.java:50) 08-19 11:57:24.823: W/System.err(4962): at android.widget.ArrayAdapter.notifyDataSetChanged(ArrayAdapter.java:286) 08-19 11:57:24.823: W/System.err(4962): at com.impact.ribony.ConversationFragment.addMessageToList(ConversationFragment.java:91) 08-19 11:57:24.823: W/System.err(4962): at com.impact.ribony.MainActivity.addMessageToFragment(MainActivity.java:344) 08-19 11:57:24.823: W/System.err(4962): at com.impact.ribony.MainActivity$2.on(MainActivity.java:183) 08-19 11:57:24.823: W/System.err(4962): at io.socket.IOConnection.on(IOConnection.java:908) 08-19 11:57:24.883: W/System.err(4962): at io.socket.IOConnection.transportMessage(IOConnection.java:697) I didn't understand this error.What can be cause this error ?

    Read the article

  • Use of select or multithread for almost 80 or more clients?

    - by Tushar Goel
    I am working on one project in which i need to read from 80 or more clients and then write their o/p into a file continuously and then read these new data for another task. My question is what should i use select or multithreading? Also I tried to use multi threading using read/fgets and write/fputs call but as they are blocking calls and one operation can be performed at one time so it is not feasible. Any idea is much appreciated. update 1: I have tried to implement the same using condition variable. I able to achieve this but it is writing and reading one at a time.When another client tried to write then it cannot able to write unless i quit from the 1st thread. I do not understand this. This should work now. What mistake i am doing? Update 2: Thanks all .. I am able to succeeded to get this model implemented using mutex condition variable. updated Code is as below: **header file******* char *mailbox ; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER ; pthread_cond_t writer = PTHREAD_COND_INITIALIZER; int main(int argc,char *argv[]) { pthread_t t1 , t2; pthread_attr_t attr; int fd, sock , *newfd; struct sockaddr_in cliaddr; socklen_t clilen; void *read_file(); void *update_file(); //making a server socket if((fd=make_server(atoi(argv[1])))==-1) oops("Unable to make server",1) //detaching threads pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); ///opening thread for reading pthread_create(&t2,&attr,read_file,NULL); while(1) { clilen = sizeof(cliaddr); //accepting request sock=accept(fd,(struct sockaddr *)&cliaddr,&clilen); //error comparison against failire of request and INT if(sock==-1 && errno != EINTR) oops("accept",2) else if ( sock ==-1 && errno == EINTR) oops("Pressed INT",3) newfd = (int *)malloc(sizeof(int)); *newfd = sock; //creating thread per request pthread_create(&t1,&attr,update_file,(void *)newfd); } free(newfd); return 0; } void *read_file(void *m) { pthread_mutex_lock(&lock); while(1) { printf("Waiting for lock.\n"); pthread_cond_wait(&writer,&lock); printf("I am reading here.\n"); printf("%s",mailbox); mailbox = NULL ; pthread_cond_signal(&writer); } } void *update_file(int *m) { int sock = *m; int fs ; int nread; char buffer[BUFSIZ] ; if((fs=open("database.txt",O_RDWR))==-1) oops("Unable to open file",4) while(1) { pthread_mutex_lock(&lock); write(1,"Waiting to get writer lock.\n",29); if(mailbox != NULL) pthread_cond_wait(&writer,&lock); lseek(fs,0,SEEK_END); printf("Reading from socket.\n"); nread=read(sock,buffer,BUFSIZ); printf("Writing in file.\n"); write(fs,buffer,nread); mailbox = buffer ; pthread_cond_signal(&writer); pthread_mutex_unlock(&lock); } close(fs); }

    Read the article

  • 10000's+ UI elements, bind or draw?

    - by jpiccolo
    I am drawing a header for a timeline control. It looks like this: I go to 0.01 millisecond per line, so for a 10 minute timeline I am looking at drawing 60000 lines + 6000 labels. This takes a while, ~10 seconds. I would like to offload this from the UI thread. My code is currently: private void drawHeader() { Header.Children.Clear(); switch (viewLevel) { case ViewLevel.MilliSeconds100: double hWidth = Header.Width; this.drawHeaderLines(new TimeSpan(0, 0, 0, 0, 10), 100, 5, hWidth); //Was looking into background worker to off load UI //backgroundWorker = new BackgroundWorker(); //backgroundWorker.DoWork += delegate(object sender, DoWorkEventArgs args) // { // this.drawHeaderLines(new TimeSpan(0, 0, 0, 0, 10), 100, 5, hWidth); // }; //backgroundWorker.RunWorkerAsync(); break; } } private void drawHeaderLines(TimeSpan timeStep, int majorEveryXLine, int distanceBetweenLines, double headerWidth) { var currentTime = new TimeSpan(0, 0, 0, 0, 0); const int everyXLine100 = 10; double currentX = 0; var currentLine = 0; while (currentX < headerWidth) { var l = new Line { ToolTip = currentTime.ToString(@"hh\:mm\:ss\.fff"), StrokeThickness = 1, X1 = 0, X2 = 0, Y1 = 30, Y2 = 25 }; if (((currentLine % majorEveryXLine) == 0) && currentLine != 0) { l.StrokeThickness = 2; l.Y2 = 15; var textBlock = new TextBlock { Text = l.ToolTip.ToString(), FontSize = 8, FontFamily = new FontFamily("Tahoma"), Foreground = new SolidColorBrush(Color.FromRgb(255, 255, 255)) }; Canvas.SetLeft(textBlock, (currentX - 22)); Canvas.SetTop(textBlock, 0); Header.Children.Add(textBlock); } if ((((currentLine % everyXLine100) == 0) && currentLine != 0) && (currentLine % majorEveryXLine) != 0) { l.Y2 = 20; var textBlock = new TextBlock { Text = string.Format(".{0}", TimeSpan.Parse(l.ToolTip.ToString()).Milliseconds), FontSize = 8, FontFamily = new FontFamily("Tahoma"), Foreground = new SolidColorBrush(Color.FromRgb(192, 192, 192)) }; Canvas.SetLeft(textBlock, (currentX - 8)); Canvas.SetTop(textBlock, 8); Header.Children.Add(textBlock); } l.Stroke = new SolidColorBrush(Color.FromRgb(255, 255, 255)); Header.Children.Add(l); Canvas.SetLeft(l, currentX); currentX += distanceBetweenLines; currentLine++; currentTime += timeStep; } } I had looked into BackgroundWorker, except you can't create UI elements on a non-UI thread. Is it possible at all to do drawHeaderLines in a non-UI thread? Could I use data binding for drawing the lines? Would this help with UI responsiveness? I would imagine I can use databinding, but the Styling is probably beyond my current WPF ability (coming from winforms and trying to learn what all these style objects are and binding them). Would anyone be able to supply a starting point for tempting this out? Or Google a tutorial that would get me started?

    Read the article

  • CommunicationException with 'not recognized sequence' message in WCF.

    - by brain_pusher
    Hello, I get a CommunicationException while using WCF service. The message is: The remote endpoint no longer recognizes this sequence. This is most likely due to an abort on the remote endpoint. The value of wsrm:Identifier is not a known Sequence identifier. The reliable session was faulted. The exception is thrown in a moment after a contract method was called. Before calling contract method the channel state is Opened. I restore my service client after catching this exception and for some time it works fine. But then this error occures again. It seems like some timeout is exceeded, but I can't understand which one exactly. I use wsHttpBinding with reliableSession enabled. The InactivityTimeout is set to half an hour and I'm sure it's not exceeded, because exception is thrown earlier.

    Read the article

  • First round playing with Memcached

    - by Shaun
    To be honest I have not been very interested in the caching before I’m going to a project which would be using the multi-site deployment and high connection and concurrency and very sensitive to the user experience. That means we must cache the output data for better performance. After looked for the Internet I finally focused on the Memcached. What’s the Memcached? I think the description on its main site gives us a very good and simple explanation. Free & open source, high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load. Memcached is an in-memory key-value store for small chunks of arbitrary data (strings, objects) from results of database calls, API calls, or page rendering. Memcached is simple yet powerful. Its simple design promotes quick deployment, ease of development, and solves many problems facing large data caches. Its API is available for most popular languages. The original Memcached was built on *nix system are is being widely used in the PHP world. Although it’s not a problem to use the Memcached installed on *nix system there are some windows version available fortunately. Since we are WISC (Windows – IIS – SQL Server – C#, which on the opposite of LAMP) it would be much easier for us to use the Memcached on Windows rather than *nix. I’m using the Memcached Win X64 version provided by NorthScale. There are also the x86 version and other operation system version.   Install Memcached Unpack the Memcached file to a folder on the machine you want it to be installed, we can see that there are only 3 files and the main file should be the “memcached.exe”. Memcached would be run on the server as a service. To install the service just open a command windows and navigate to the folder which contains the “memcached.exe”, let’s say “C:\Memcached\”, and then type “memcached.exe -d install”. If you are using Windows Vista and Windows 7 system please be execute the command through the administrator role. Right-click the command item in the start menu and use “Run as Administrator”, otherwise the Memcached would not be able to be installed successfully. Once installed successful we can type “memcached.exe -d start” to launch the service. Now it’s ready to be used. The default port of Memcached is 11211 but you can change it through the command argument. You can find the help by typing “memcached -h”.   Using Memcached Memcahed has many good and ready-to-use providers for vary program language. After compared and reviewed I chose the Memcached Providers. It’s built based on another 3rd party Memcached client named enyim.com Memcached Client. The Memcached Providers is very simple to set/get the cached objects through the Memcached servers and easy to be configured through the application configuration file (aka web.config and app.config). Let’s create a console application for the demonstration and add the 3 DLL files from the package of the Memcached Providers to the project reference. Then we need to add the configuration for the Memcached server. Create an App.config file and firstly add the section on top of it. Here we need three sections: the section for Memcached Providers, for enyim.com Memcached client and the log4net. 1: <configSections> 2: <section name="cacheProvider" 3: type="MemcachedProviders.Cache.CacheProviderSection, MemcachedProviders" 4: allowDefinition="MachineToApplication" 5: restartOnExternalChanges="true"/> 6: <sectionGroup name="enyim.com"> 7: <section name="memcached" 8: type="Enyim.Caching.Configuration.MemcachedClientSection, Enyim.Caching"/> 9: </sectionGroup> 10: <section name="log4net" 11: type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/> 12: </configSections> Then we will add the configuration for 3 of them in the App.config file. The Memcached server information would be defined under the enyim.com section since it will be responsible for connect to the Memcached server. Assuming I installed the Memcached on two servers with the default port, the configuration would be like this. 1: <enyim.com> 2: <memcached> 3: <servers> 4: <!-- put your own server(s) here--> 5: <add address="192.168.0.149" port="11211"/> 6: <add address="10.10.20.67" port="11211"/> 7: </servers> 8: <socketPool minPoolSize="10" maxPoolSize="100" connectionTimeout="00:00:10" deadTimeout="00:02:00"/> 9: </memcached> 10: </enyim.com> Memcached supports the multi-deployment which means you can install the Memcached on the servers as many as you need. The protocol of the Memcached responsible for routing the cached objects into the proper server. So it’s very easy to scale-out your system by Memcached. And then define the Memcached Providers configuration. The defaultExpireTime indicates how long the objected cached in the Memcached would be expired, the default value is 2000 ms. 1: <cacheProvider defaultProvider="MemcachedCacheProvider"> 2: <providers> 3: <add name="MemcachedCacheProvider" 4: type="MemcachedProviders.Cache.MemcachedCacheProvider, MemcachedProviders" 5: keySuffix="_MySuffix_" 6: defaultExpireTime="2000"/> 7: </providers> 8: </cacheProvider> The last configuration would be the log4net. 1: <log4net> 2: <!-- Define some output appenders --> 3: <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"> 4: <layout type="log4net.Layout.PatternLayout"> 5: <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/> 6: </layout> 7: </appender> 8: <!--<threshold value="OFF" />--> 9: <!-- Setup the root category, add the appenders and set the default priority --> 10: <root> 11: <priority value="WARN"/> 12: <appender-ref ref="ConsoleAppender"> 13: <filter type="log4net.Filter.LevelRangeFilter"> 14: <levelMin value="WARN"/> 15: <levelMax value="FATAL"/> 16: </filter> 17: </appender-ref> 18: </root> 19: </log4net>   Get, Set and Remove the Cached Objects Once we finished the configuration it would be very simple to consume the Memcached servers. The Memcached Providers gives us a static class named DistCache that can be used to operate the Memcached servers. Get<T>: Retrieve the cached object from the Memcached servers. If failed it will return null or the default value. Add: Add an object with a unique key into the Memcached servers. Assuming that we have an operation that retrieve the email from the name which is time consuming. This is the operation that should be cached. The method would be like this. I utilized Thread.Sleep to simulate the long-time operation. 1: static string GetEmailByNameSlowly(string name) 2: { 3: Thread.Sleep(2000); 4: return name + "@ethos.com.cn"; 5: } Then in the real retrieving method we will firstly check whether the name, email information had been searched previously and cached. If yes we will just return them from the Memcached, otherwise we will invoke the slowly method to retrieve it and then cached. 1: static string GetEmailByName(string name) 2: { 3: var email = DistCache.Get<string>(name); 4: if (string.IsNullOrEmpty(email)) 5: { 6: Console.WriteLine("==> The name/email not be in memcached so need slow loading. (name = {0})==>", name); 7: email = GetEmailByNameSlowly(name); 8: DistCache.Add(name, email); 9: } 10: else 11: { 12: Console.WriteLine("==> The name/email had been in memcached. (name = {0})==>", name); 13: } 14: return email; 15: } Finally let’s finished the calling method and execute. 1: static void Main(string[] args) 2: { 3: var name = string.Empty; 4: while (name != "q") 5: { 6: Console.Write("==> Please enter the name to find the email: "); 7: name = Console.ReadLine(); 8:  9: var email = GetEmailByName(name); 10: Console.WriteLine("==> The email of {0} is {1}.", name, email); 11: } 12: } The first time I entered “ziyanxu” it takes about 2 seconds to get the email since there’s nothing cached. But the next time I entered “ziyanxu” it returned very quickly from the Memcached.   Summary In this post I explained a bit on why we need cache, what’s Memcached and how to use it through the C# application. The example is fairly simple but hopefully demonstrated on how to use it. Memcached is very easy and simple to be used since it gives you the full opportunity to consider what, when and how to cache the objects. And when using Memcached you don’t need to consider the cache servers. The Memcached would be like a huge object pool in front of you. The next step I’m thinking now are: What kind of data should be cached? And how to determined the key? How to implement the cache as a layer on top of the business layer so that the application will not notice that the cache is there. How to implement the cache by AOP so that the business logic no need to consider the cache. I will investigate on them in the future and will share my thoughts and results.   Hope this helps, Shaun All documents and related graphics, codes are provided "AS IS" without warranty of any kind. Copyright © Shaun Ziyan Xu. This work is licensed under the Creative Commons License.

    Read the article

  • How to set permissions so two users can work on the same hg repository?

    - by John Mee
    Ubuntu: Jaunty Mercurial: 1.3.1 Access: ssh (users john and bob) File permission: -rw-rw---- 1 john john 129276 May 17 13:28 dirstate User: bob Command: 'hg st' Response: **abort: Permission denied: /our/respository/.hg/dirstate** Obviously mercurial can't let bob see the state because the file it needs to read belongs to me. So I change the permissions to allow bob to read the file and everything is fine, up until I next try to do something, whence the situations are reversed. Now he owns the file and I can't read it. So I set up a "committers" group and both john and bob belong to the group, but still mercurial fiddles with the ownership and permissions whenever one or other commits. How do we configure it so two different logins in the same group can commit to the same repository over ssh?

    Read the article

  • How to undo an hg merge? (I think.)

    - by Grumdrig
    I'm new to collaborating with Mercurial. My situation: Another programmer changed rev 1 of a file to replace 4-space indents with 2-space indent. (I.e. changed every line.) Call that rev 2, pushed to the remote repo. I've committed substantive changes rev 1 with various code changes in my local workspace. Call that rev 3. I've hg pulled and hg mergeed without a clear idea of what was going on. The conflicts are myriad and not really substantive. So I really wish I'd changed my local repo to 2-space indents before merging; then the merge will be trivial (i'm supposing). But I can't seem to back up. I think I need to hg update -r 3 but it says abort: outstanding uncommitted merges. How can I undo the merge, changes spacing in my local repo, and remerge?

    Read the article

  • Mercurial: Problem converting Windows cvs repository to mercurial

    - by jalperin
    I’m trying to convert an existing Windows CVS repository to Mercurial and getting the following response and error: C:\Windows\system32>hg convert c:\users\jeff\webs\shelter-cvs\shelter assuming destination shelter-hg initializing destination shelter-hg repository connecting to :local:c:\cvs abort: unexpected response from CVS server (expected "Valid-requests", but got 'E cvs [server aborted]: c:\\cvs: no such repository\n') Here’s the background: The repository was created with TortoiseCVS so I believe it’s actually cvsnt. I can properly checkout from the repository using either the command line or the TortoiseCVS gui, so I think it is set up correctly. I'm trying to convert a working copy, not the repository itself I’m running Windows 7, 64-bit I’ve installed TortoiseHG and enabled the convert extension.

    Read the article

< Previous Page | 144 145 146 147 148 149 150 151 152 153 154 155  | Next Page >