Search Results

Search found 13011 results on 521 pages for 'catch block'.

Page 74/521 | < Previous Page | 70 71 72 73 74 75 76 77 78 79 80 81  | Next Page >

  • screnshot in android

    - by ujjawal
    The following is the code I am using to take a screen shot using GLSurfaceView. But I dont know why the onDraw() method in the GLSurfaceView.Renderer Class is not being called. Please if some one can look at the code below and point out what am I doing wrong.`public class MainActivity extends Activity { private GLSurfaceView mGLView; int x,y,w,h; Display disp; /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); // ToDo add your GUI initialization code here setContentView(R.layout.main); x=0; y=0; disp = getWindowManager().getDefaultDisplay(); w = disp.getWidth(); h = disp.getHeight(); mGLView = new ClearGLSurfaceView(this); } class ClearGLSurfaceView extends GLSurfaceView { public ClearGLSurfaceView(Context context) { super(context); setDebugFlags(DEBUG_CHECK_GL_ERROR | DEBUG_LOG_GL_CALLS); mRenderer = new ClearRenderer(); setRenderer(mRenderer); } ClearRenderer mRenderer; } class ClearRenderer implements GLSurfaceView.Renderer { public void onSurfaceCreated(GL10 gl, EGLConfig config) { // Do nothing special. } public void onSurfaceChanged(GL10 gl, int w, int h) { //gl.glViewport(0, 0, w, h); } public void onDrawFrame(GL10 gl) { //gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); int b[]=new int[w*(y+h)]; int bt[]=new int[w*h]; IntBuffer ib=IntBuffer.wrap(b); ib.position(0); gl.glReadPixels(x, 0, w, y+h, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, ib); for(int i=0, k=0; i<h; i++, k++) {//remember, that OpenGL bitmap is incompatible with Android bitmap //and so, some correction need. for(int j=0; j<w; j++) { int pix=b[i*w+j]; int pb=(pix>>16)&0xff; int pr=(pix<<16)&0x00ff0000; int pix1=(pix&0xff00ff00) | pr | pb; bt[(h-k-1)*w+j]=pix1; } } Bitmap bmp = Bitmap.createBitmap(bt, w, h,Bitmap.Config.ARGB_8888); try { File f = new File("/sdcard/testpicture.png"); f.createNewFile(); FileOutputStream fos=new FileOutputStream(f); bmp.compress(CompressFormat.PNG, 100, fos); try { fos.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { fos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); } } } } ` Please someone help me out. I have just started learning to work on android.

    Read the article

  • IOException during blocking network NIO in JDK 1.7

    - by Bass
    I'm just learning NIO, and here's the short example I've written to test how a blocking NIO can be interrupted: class TestBlockingNio { private static final boolean INTERRUPT_VIA_THREAD_INTERRUPT = true; /** * Prevent the socket from being GC'ed */ static Socket socket; private static SocketChannel connect(final int port) { while (true) { try { final SocketChannel channel = SocketChannel.open(new InetSocketAddress(port)); channel.configureBlocking(true); return channel; } catch (final IOException ioe) { try { Thread.sleep(1000); } catch (final InterruptedException ie) { } continue; } } } private static byte[] newBuffer(final int length) { final byte buffer[] = new byte[length]; for (int i = 0; i < length; i++) { buffer[i] = (byte) 'A'; } return buffer; } public static void main(final String args[]) throws IOException, InterruptedException { final int portNumber = 10000; new Thread("Reader") { public void run() { try { final ServerSocket serverSocket = new ServerSocket(portNumber); socket = serverSocket.accept(); /* * Fully ignore any input from the socket */ } catch (final IOException ioe) { ioe.printStackTrace(); } } }.start(); final SocketChannel channel = connect(portNumber); final Thread main = Thread.currentThread(); final Thread interruptor = new Thread("Inerruptor") { public void run() { System.out.println("Press Enter to interrupt I/O "); while (true) { try { System.in.read(); } catch (final IOException ioe) { ioe.printStackTrace(); } System.out.println("Interrupting..."); if (INTERRUPT_VIA_THREAD_INTERRUPT) { main.interrupt(); } else { try { channel.close(); } catch (final IOException ioe) { System.out.println(ioe.getMessage()); } } } } }; interruptor.setDaemon(true); interruptor.start(); final ByteBuffer buffer = ByteBuffer.allocate(32768); int i = 0; try { while (true) { buffer.clear(); buffer.put(newBuffer(buffer.capacity())); buffer.flip(); channel.write(buffer); System.out.print('X'); if (++i % 80 == 0) { System.out.println(); Thread.sleep(100); } } } catch (final ClosedByInterruptException cbie) { System.out.println("Closed via Thread.interrupt()"); } catch (final AsynchronousCloseException ace) { System.out.println("Closed via Channel.close()"); } } } In the above example, I'm writing to a SocketChannel, but noone is reading from the other side, so eventually the write operation hangs. This example works great when run by JDK-1.6, with the following output: Press Enter to interrupt I/O XXXX Interrupting... Closed via Thread.interrupt() — meaning that only 128k of data was written to the TCP socket's buffer. When run by JDK-1.7 (1.7.0_25-b15 and 1.7.0-u40-b37), however, the very same code bails out with an IOException: Press Enter to interrupt I/O XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXX Exception in thread "main" java.io.IOException: Broken pipe at sun.nio.ch.FileDispatcherImpl.write0(Native Method) at sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:47) at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:93) at sun.nio.ch.IOUtil.write(IOUtil.java:65) at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:487) at com.example.TestBlockingNio.main(TestBlockingNio.java:109) Can anyone explain this different behaviour?

    Read the article

  • How to read from an XmlReader without moving it forwards

    - by andy
    hey guys, I've got this scenario: while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Name == itemElementName) { XElement item = null; try { item = XElement.ReadFrom(reader) as XElement; } catch (XmlException ex) { //log line number and stuff from XmlException class } } } In the above loop I'm transforming a certain node (itemElementName) into an XElement. Some nodes will be good XML and will go into an XElement, however, some will not. In the CATCH, I'd like to now only catch the standard XmlException stuff... I'd also like to catch an extract of the current Xml and a string. However, if I do any kind of READ operation on the node before I pass it to the XElement, it moves the reader forward. How can get a "snapshot" of the contents of the OuterXml of the reader without interfering with it's position?

    Read the article

  • How to transform a production to LL(1) grammar for a list separated by a semicolon?

    - by Subb
    Hi, I'm reading this introductory book on parsing (which is pretty good btw) and one of the exercice is to "build a parser for your favorite language." Since I don't want to die today, I thought I could do a parser for something relatively simple, ie a simplified CSS. Note: This book teach you how to right a LL(1) parser using the recursive-descent algorithm. So, as a sub-exercice, I am building the grammar from what I know of CSS. But I'm stuck on a production that I can't transform in LL(1) : //EBNF block = "{", declaration, {";", declaration}, [";"], "}" //BNF <block> =:: "{" <declaration> "}" <declaration> =:: <single-declaration> <opt-end> | <single-declaration> ";" <declaration> <opt-end> =:: "" | ";" This describe a CSS block. Valid block can have the form : { property : value } { property : value; } { property : value; property : value } { property : value; property : value; } ... The problem is with the optional ";" at the end, because it overlap with the starting character of {";", declaration}, so when my parser meet a semicolon in this context, it doesn't know what to do. The book talk about this problem, but in its example, the semicolon is obligatory, so the rule can be modified like this : block = "{", declaration, ";", {declaration, ";"}, "}" So, Is it possible to achieve what I'm trying to do using a LL(1) parser?

    Read the article

  • How to avoid exceptions catches copy-paste in .NET

    - by Budda
    Working with .NET framework I have a service with a set of methods that can generates several types of exceptions: MyException2, MyExc1, Exception... To provide proper work for all methods, each of them contains following sections: void Method1(...) { try { ... required functionality } catch(MyException2 exc) { ... process exception of MyException2 type } catch(MyExc1 exc) { ... process exception of MyExc1 type } catch(Exception exc) { ... process exception of Exception type } ... process and return result if necessary } It is very boring to have exactly same stuff in EACH service method with exactly same exceptions processing functionality... Is there any possibility to "group" these catch-sections and use only one line (something similar to C++ macros)? Probably something new in .NET 4.0 is related to this topic? Thanks. P.S. Any thoughts are welcome.

    Read the article

  • help me understand cuda

    - by scatman
    i am having some troubles understanding threads in NVIDIA gpu architecture with cuda. please could anybody clarify these info: an 8800 gpu has 16 SMs with 8 SPs each. so we have 128 SPs. i was viewing stanford's video presentation and it was saying that every SP is capable of running 96 threads cuncurrently. does this mean that it (SP) can run 96/32=3 warps concurrently? moreover, since every SP can run 96 threads and we have 8 SPs in every SM. does this mean that every SM can run 96*8=768 threads concurrently?? but if every SM can run a single Block at a time, and the maximum number of threads in a block is 512, so what is the purpose of running 768 threads concurrently and have a max of 512 threads? a more general question is:how are blocks,threads,and warps distributed to SMs and SPs? i read that every SM gets a single block to execute at a time and threads in a block is divided into warps (32 threads), and SPs execute warps.

    Read the article

  • Downloading large files with AFNetworking

    - by goodfella
    I'm trying to implement downloading of a large file and show to user current progress, but block in: -[AFURLConnectionOperation setDownloadProgressBlock:] returns incorrect bytesRead and totalBytesRead values (they are smaller than they should be). For example: If I have a 90MB file and when it downloads completely, latest block invocation in setDownloadProgressBlock: gives me totalBytesRead value about 30MB. On other side, if file is 2MB large, latest block invocation gives correct totalBytesRead 2MB value. AFNetworking is updated to the latest version from github. If AFNetworking can't do it correctly, what solution can I use? Edit: I've determined that even if file is not downloaded completely (and this happens every time with relatively big file) AFNetworking calls success block in: -[AFHTTPRequestOperation setCompletionBlockWithSuccess:failure] I asked a similar question here about this situation, but didn't get any answers. I can check in code downloaded and real file sizes, but AFNetworking has no API for continuation of partial download.

    Read the article

  • A question about Drupal Node and Views

    - by Sushi
    I have created an "Add Question" content-type node which lets users ask questions. The questions have a title, image attachment option, and the content. I am showing the questions which have image as a block by filtering it as "Content: Photofield - list True" in Views. This way, only the questions which have images attached to the question appear in this block. Photofield by the way is the content type. I want to create a new block which only shows the questions which have no attached image. I have done filtering this block view by keeping filters as "Content: Photofield - list False" but in vain. There's also some expose option and I did some messing around with it too without coming to the result I want. Can anyone help?

    Read the article

  • Jquery current menu

    - by Isis
    Hello I have: var href = window.location.href; if(href.search('/welcome\\/') > 0) { $('.menuwelcome').css('display', 'block'); $('#welcome2').append('<b>?????????? ??????????</b>').find('a').remove(); $('#welcome2').find('img').attr('src', '/static/images/arrow_black.gif'); } if(href.search('/contacts\\/') > 0) { $('.menuwelcome').css('display', 'block'); $('#mcontacts').append('<b>????????</b>').find('a').remove(); $('#mcontacts').find('img').attr('src', '/static/images/arrow_black_down.gif'); } if(href.search('/sindbad_history\\/') > 0) { $('.menuwelcome').css('display', 'block'); $('.menuwelcome:first').append('<b>???????</b>').find('a').remove(); $('.menuwelcome:first').find('img').attr('src', '/static/images/arrow_black.gif'); } if(href.search('/insurance\\/') > 0) { $('.menusafe').css('display', 'block'); $('#msafe').append('<b>???????????</b>').find('a').remove(); $('#msafe').find('img').attr('src', '/static/images/arrow_black_down.gif'); } if(href.search('/insurance_advices\\/') > 0) { $('.menusafe').css('display', 'block'); $('.menusafe:first').append('<b>???????? ??????????</b>').find('a').remove(); $('.menusafe:first').find('img').attr('src', '/static/images/arrow_black.gif'); } How can I minimize this code? Sorry for bad english

    Read the article

  • jquery ui is not scaling text properly!

    - by Stephen Belanger
    I'm trying use jquery ui to scale a div that I'm dragging around to make it easier to see what's behind it, but any text inside it is scaling strangely. The text itself becomes smaller, but it seems to have a bunch of padding around it and is floating now. The text extends past the bottom of the div even though it should be contained properly by the div. I put a red border around the lines of text and the borders are the same size as the original text. I'm not really sure what to do to get this to work... HTML: <div class="item draggable" id="item-1'"> <div class="image-block"> <a class="delete-button" title="delete me!" href="/remove/1" onclick="return $(this).confirm(\'Really remove this image?\');">X</a> <a class="image" href="/edit/1"><img src="/someimage.jpg" /></a> <div class="clear-block"></div> </div> <h3>Some title</h3> </div> CSS: div.image-list div.item { float:left; background:#fff; width:150px; padding:5px; margin:4px; border:1px solid #d3d5d6; } div.image-list div.item h3 { margin:0; padding:0; border:solid 1px #F00; } div.image-list div.item div.image-block a.delete-button { float:right; position:relative; background:#fff; display:none; top:0.8em; margin-bottom:-20.0em; width:3em; height:1.8em; padding:0.2em 1em; } div.image-list div.item div.image-block a.image { float:left; display:block; } .clear-block { clear:both; } jquery: $(".draggable").draggable({ helper: 'clone', start: function(ev, ui) { $(ui.helper).effect( "scale", { percent: 50 }, 200 ); } });

    Read the article

  • Input/output (read) errors in Bacula while setting up a Tape Drive + Autochanger

    - by Kyle Brandt
    When running the label barcode command in bacula I am getting Input/output errors. I am just getting started in trying to set this up: Connecting to Storage daemon TapeDevice at ny-back01.ny.stackoverflow.com:9103 ... Sending label command for Volume "ACJ332" Slot 1 ... 3307 Issuing autochanger "unload slot 8, drive 0" command. 3304 Issuing autochanger "load slot 1, drive 0" command. 3305 Autochanger "load slot 1, drive 0", status is OK. block.c:1010 Read error on fd=5 at file:blk 0:0 on device "ULTRIUM-HH4" (/dev/st0). ERR=Input/output error. 3000 OK label. VolBytes=64512 DVD=0 Volume="ACJ332" Device="ULTRIUM-HH4" (/dev/st0) Catalog record for Volume "ACJ332", Slot 1 successfully created. Sending label command for Volume "ACJ331" Slot 2 ... 3307 Issuing autochanger "unload slot 1, drive 0" command. 3304 Issuing autochanger "load slot 2, drive 0" command. 3305 Autochanger "load slot 2, drive 0", status is OK. block.c:1010 Read error on fd=5 at file:blk 0:0 on device "ULTRIUM-HH4" (/dev/st0). ERR=Input/output error. 3000 OK label. VolBytes=64512 DVD=0 Volume="ACJ331" Device="ULTRIUM-HH4" (/dev/st0) Catalog record for Volume "ACJ331", Slot 2 successfully created. Sending label command for Volume "ACJ328" Slot 3 ... 3307 Issuing autochanger "unload slot 2, drive 0" command. 3304 Issuing autochanger "load slot 3, drive 0" command. 3305 Autochanger "load slot 3, drive 0", status is OK. block.c:1010 Read error on fd=5 at file:blk 0:0 on device "ULTRIUM-HH4" (/dev/st0). ERR=Input/output error. 3000 OK label. VolBytes=64512 DVD=0 Volume="ACJ328" Device="ULTRIUM-HH4" (/dev/st0) Catalog record for Volume "ACJ328", Slot 3 successfully created. Sending label command for Volume "ACJ329" Slot 4 ... 3307 Issuing autochanger "unload slot 3, drive 0" command. 3304 Issuing autochanger "load slot 4, drive 0" command. 3305 Autochanger "load slot 4, drive 0", status is OK. block.c:1010 Read error on fd=5 at file:blk 0:0 on device "ULTRIUM-HH4" (/dev/st0). ERR=Input/output error. 3000 OK label. VolBytes=64512 DVD=0 Volume="ACJ329" Device="ULTRIUM-HH4" (/dev/st0) Catalog record for Volume "ACJ329", Slot 4 successfully created. Sending label command for Volume "ACJ335" Slot 5 ... 3307 Issuing autochanger "unload slot 4, drive 0" command. 3304 Issuing autochanger "load slot 5, drive 0" command. 3305 Autochanger "load slot 5, drive 0", status is OK. block.c:1010 Read error on fd=5 at file:blk 0:0 on device "ULTRIUM-HH4" (/dev/st0). ERR=Input/output error. 3000 OK label. VolBytes=64512 DVD=0 Volume="ACJ335" Device="ULTRIUM-HH4" (/dev/st0) Catalog record for Volume "ACJ335", Slot 5 successfully created. Sending label command for Volume "ACJ334" Slot 6 ... 3307 Issuing autochanger "unload slot 5, drive 0" command. 3304 Issuing autochanger "load slot 6, drive 0" command. 3305 Autochanger "load slot 6, drive 0", status is OK. block.c:1010 Read error on fd=5 at file:blk 0:0 on device "ULTRIUM-HH4" (/dev/st0). ERR=Input/output error. 3000 OK label. VolBytes=64512 DVD=0 Volume="ACJ334" Device="ULTRIUM-HH4" (/dev/st0) Catalog record for Volume "ACJ334", Slot 6 successfully created. Sending label command for Volume "ACJ333" Slot 7 ... 3307 Issuing autochanger "unload slot 6, drive 0" command. 3304 Issuing autochanger "load slot 7, drive 0" command. 3305 Autochanger "load slot 7, drive 0", status is OK. block.c:1010 Read error on fd=5 at file:blk 0:0 on device "ULTRIUM-HH4" (/dev/st0). ERR=Input/output error. 3000 OK label. VolBytes=64512 DVD=0 Volume="ACJ333" Device="ULTRIUM-HH4" (/dev/st0) Catalog record for Volume "ACJ333", Slot 7 successfully created. Sending label command for Volume "ACJ330" Slot 8 ... 3307 Issuing autochanger "unload slot 7, drive 0" command. Bacula-dir: # Definition of file storage device Storage { Name = TapeDevice # Do not use "localhost" here Address = ny-back01.... # N.B. Use a fully qualified name here SDPort = 9103 Password = "..." Device = ULTRIUM-HH4 Media Type = LTO-4 Media Type = File Autochanger = Yes } Bacula-sd: Autochanger { Name = StorageLoader1U Device = ULTRIUM-HH4 Changer Command = "/etc/bacula/scripts/mtx-changer %c %o %S %a %d" Changer Device = /dev/sg5 } Device { Name = ULTRIUM-HH4 Media Type = LTO-4 Archive Device = /dev/st0 AutomaticMount = yes; AlwaysOpen = yes; RemovableMedia = yes; RandomAccess = no; AutoChanger = yes; RandomAccess = no; } Anyone knows what this means / why I am getting this?

    Read the article

  • Strange Java Socket Behavior (Connects, but Doesn't Send)

    - by Donald Campbell
    I have a fairly complex project that boils down to a simple Client / Server communicating through object streams. Everything works flawlessly for two consecutive connections (I connect once, work, disconnect, then connect again, work, and disconnect). The client connects, does its business, and then closes. The server successfully closes both the object output stream and the socket, with no IO errors. When I try to connect a third time, the connection appears to go through (the ServerSocket.accept() method goes through and an ObjectOutputStream is successfully created). No data is passed, however. The inputStream.readUnshared() method simply blocks. I have taken the following memory precautions: When it comes time to close the sockets, all running threads are stopped, and all objects are nulled out. After every writeUnshared() method call, the ObjectOutputBuffer is flushed and reset. Has anyone encountered a similar problem, or does anyone have any suggestions? I'm afraid my project is rather large, and so copying code is problematic. The project boils down to this: SERVER MAIN ServerSocket serverSocket = new ServerSocket(port); while (true) { new WorkThread(serverSocket.accept()).start(); } WORK THREAD (SERVER) public void run() { ObjectInputBuffer inputBuffer = new ObjectInputBuffer(new BufferedInputStream(socket.getInputStream())); while (running) { try { Object myObject = inputBuffer.readUnshared(); // do work is not specified in this sample doWork(myObject); } catch (IOException e) { running = false; } } try { inputBuffer.close(); socket.close(); } catch (Exception e) { System.out.println("Could not close."); } } CLIENT public Client() { Object myObject; Socket mySocket = new Socket(address, port); try { ObjectOutputBuffer output = new ObjectOutputBuffer(new BufferedOutputStream(mySocket.getOutputStream())); output.reset(); output.flush(); } catch (Exception e) { System.out.println("Could not get an input."); mySocket.close(); return; } // get object data is not specified in this sample. it simply returns a serializable object myObject = getObjectData(); while (myObject != null) { try { output.writeUnshared(myObject); output.reset(); output.flush(); } catch (Exception e) { e.printStackTrace(); break; } // catch } // while try { output.close(); socket.close(); } catch (Exception e) { System.out.println("Could not close."); } } Thank you to everyone who may be able to help!

    Read the article

  • How can I tell what events fire from GXT?

    - by CoverosGene
    I cannot seem to find any documentation of what events fire and when in GXT. The API docs have lists of all the events that could fire (in Events). And it describes how to handle events that you catch. But I'm interested in the opposite side, which events are fired when I take a certain action. I can set some listeners for various different components, or I can use addListener with a specific event code to catch individual events. That's spotty, and I seem to be using trial-and-error to guess what I might want to catch. Is there a way to log all the events that are firing? Or catch all of them so I could look at them in a debugger? Or is there some documentation I am missing that has the information? Something along the lines of "when you click on a widget, a ButtonEvent is fired. Events.x is fired on the hover, Events.y on the click."

    Read the article

  • Force IOException during file reading

    - by DixonD
    I have the piece of code that reads data from file. I want to force IOException in this code for testing purpose (I want to check if code throws correct custom exception in this case). Is there a some way to create a file which is protected from being read, for example? Maybe dealing with some security checks can help? Please, note that passing name to not-existent file cannot help, because FileNotFoundException has separate catch clause. Here peace of code for better undestanding of question: BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(csvFile)); String rawLine; while ((rawLine = reader.readLine()) != null) { // some work is done here } } catch (FileNotFoundException e) { throw new SomeCustomException(); } catch (IOException e) { throw new SomeCustomException(); } finally { // close the input stream if (reader != null) { try { reader.close(); } catch (IOException e) { // ignore } } }

    Read the article

  • How to store and echo multiple lines elegantly in bash?

    - by EmpireJones
    I'm trying to capture a block of text into a variable, with newlines maintained, then echo it. However, the newlines don't seemed to be maintained when I am either capturing the text or displaying it. Any ideas regarding how I can accomplish this? Example: #!/bin/bash read -d '' my_var <<"BLOCK" this is a test BLOCK echo $my_var Output: this is a test Desired output: this is a test

    Read the article

  • non blocking client server chat application in java using nio

    - by Amith
    I built a simple chat application using nio channels. I am very much new to networking as well as threads. This application is for communicating with server (Server / Client chat application). My problem is that multiple clients are not supported by the server. How do I solve this problem? What's the bug in my code? public class Clientcore extends Thread { SelectionKey selkey=null; Selector sckt_manager=null; public void coreClient() { System.out.println("please enter the text"); BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in)); SocketChannel sc = null; try { sc = SocketChannel.open(); sc.configureBlocking(false); sc.connect(new InetSocketAddress(8888)); int i=0; while (!sc.finishConnect()) { } for(int ii=0;ii>-22;ii++) { System.out.println("Enter the text"); String HELLO_REQUEST =stdin.readLine().toString(); if(HELLO_REQUEST.equalsIgnoreCase("end")) { break; } System.out.println("Sending a request to HelloServer"); ByteBuffer buffer = ByteBuffer.wrap(HELLO_REQUEST.getBytes()); sc.write(buffer); } } catch (IOException e) { e.printStackTrace(); } finally { if (sc != null) { try { sc.close(); } catch (Exception e) { e.printStackTrace(); } } } } public void run() { try { coreClient(); } catch(Exception ej) { ej.printStackTrace(); }}} public class ServerCore extends Thread { SelectionKey selkey=null; Selector sckt_manager=null; public void run() { try { coreServer(); } catch(Exception ej) { ej.printStackTrace(); } } private void coreServer() { try { ServerSocketChannel ssc = ServerSocketChannel.open(); try { ssc.socket().bind(new InetSocketAddress(8888)); while (true) { sckt_manager=SelectorProvider.provider().openSelector(); ssc.configureBlocking(false); SocketChannel sc = ssc.accept(); register_server(ssc,SelectionKey.OP_ACCEPT); if (sc == null) { } else { System.out.println("Received an incoming connection from " + sc.socket().getRemoteSocketAddress()); printRequest(sc); System.err.println("testing 1"); String HELLO_REPLY = "Sample Display"; ByteBuffer buffer = ByteBuffer.wrap(HELLO_REPLY.getBytes()); System.err.println("testing 2"); sc.write(buffer); System.err.println("testing 3"); sc.close(); }}} catch (IOException e) { e.printStackTrace(); } finally { if (ssc != null) { try { ssc.close(); } catch (IOException e) { e.printStackTrace(); } } } } catch(Exception E) { System.out.println("Ex in servCORE "+E); } } private static void printRequest(SocketChannel sc) throws IOException { ReadableByteChannel rbc = Channels.newChannel(sc.socket().getInputStream()); WritableByteChannel wbc = Channels.newChannel(System.out); ByteBuffer b = ByteBuffer.allocate(1024); // read 1024 bytes while (rbc.read(b) != -1) { b.flip(); while (b.hasRemaining()) { wbc.write(b); System.out.println(); } b.clear(); } } public void register_server(ServerSocketChannel ssc,int selectionkey_ops)throws Exception { ssc.register(sckt_manager,selectionkey_ops); }} public class HelloClient { public void coreClientChat() { Clientcore t=new Clientcore(); new Thread(t).start(); } public static void main(String[] args)throws Exception { HelloClient cl= new HelloClient(); cl.coreClientChat(); }} public class HelloServer { public void coreServerChat() { ServerCore t=new ServerCore(); new Thread(t).start(); } public static void main(String[] args) { HelloServer st= new HelloServer(); st.coreServerChat(); }}

    Read the article

  • Question about Transact SQL syntax

    - by Yousui
    Hi guys, The following code works like a charm: BEGIN TRY BEGIN TRANSACTION COMMIT TRANSACTION END TRY BEGIN CATCH IF @@TRANCOUNT > 0 ROLLBACK; DECLARE @ErrorMessage NVARCHAR(4000), @ErrorSeverity int; SELECT @ErrorMessage = ERROR_MESSAGE(), @ErrorSeverity = ERROR_SEVERITY(); RAISERROR(@ErrorMessage, @ErrorSeverity, 1); END CATCH But this code gives an error: BEGIN TRY BEGIN TRANSACTION COMMIT TRANSACTION END TRY BEGIN CATCH IF @@TRANCOUNT > 0 ROLLBACK; RAISERROR(ERROR_MESSAGE(), ERROR_SEVERITY(), 1); END CATCH Why?

    Read the article

  • how to retrive String from DatagramPacket

    - by sajith
    the following code prints [B@40545a60,[B@40545a60abc exp but i want to print abc,so that i can retrive the correct message from the receiving system public class Operation { InetAddress ip; DatagramSocket dsock; DatagramPacket pack1; byte[] bin,bout; WifyOperation(InetAddress Systemip) { ip=Systemip; try { dsock=new DatagramSocket(); } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } } void sendbyte() { String senddata="abc"+"123"; bout=senddata.getBytes(); pack1=new DatagramPacket(bout,bout.length,ip,3322); try { dsock.send(pack1); Log.d(pack1.getData().toString(),"abc exp"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } how i retrieve string instead of byte from the packet pack1

    Read the article

  • Need help with height 100% layout

    - by serg
    I am trying to build the following layout (file browser type of thing, left block would contain a list of files, right panel would contain selected file content): <------------- MENU -------------------> <--- LEFT ----><------- RIGHT ---------> <--- LEFT ----><------- RIGHT ---------> <--- LEFT ----><------- RIGHT ---------> <--- LEFT ----><------- RIGHT ---------> <--- LEFT ----><------- RIGHT ---------> <--- LEFT ----><------- RIGHT ---------> The page itself shouldn't have any scrollbars. Menu has 100% width and fixed height Left block has fixed width and 100% height. If content is taller - scroll bar appears inside the left block only. Right block contains <pre> element and takes the remaining width and 100% height. If content is wider or taller - scrollbar appears inside the right block only. This is what I have so far: http://jsbin.com/uqegi4/3/edit The problem is fixed menu height messes up 100% height calculation and all scrollbars inside left and right blocks appear at wrong time. I don't care about cross browser compatibility, only Chrome matters. Thanks.

    Read the article

  • Ping remote server and wait to get data

    - by infinity
    Hi I'm building my first application for android and I've reached a point where I can't find a solution even have no idea what to search for in Google. So the problem: I am pinging a remote server with GET request through the application passing some parameters like file_id. Then the server gives back confirmation if the file exists or error otherwise, both in plain text. The error string is $$$ERROR$$$. Actually the confirmation is JSON string that holds the path to the file. If the file doesn't exists on the server it generated the error message and start downloading the file and processing it which normally takes 10-30 seconds. What would be the best way to check if the file is ready for download? I have DownloadFile class that extends AsyncTask but before I reach the point to download the file I need the URL which is dependant on the previous request which is in the main class in the UI thread. Here is some code: public class MainActivity extends Activity { private String getInfo() { // Create a new HttpClient and Post Header HttpClient httpClient = new DefaultHttpClient(); HttpGet httpPost = new HttpGet(infoUrl); StringBuilder sb = null; String data; JSONObject jObject = null; try { HttpResponse response = httpClient.execute(httpPost); // This might be equal "$$$ERROR$$$" if no file exists sb = inputStreamToString(response.getEntity().getContent()); } catch(ClientProtocolException e) { // TODO Auto-generated catch block Log.v("Error: pushItem ClientProtocolException: ", e.toString()); } catch (IOException e) { // TODO Auto-generated catch block Log.v("Error: pushItem IOException: ", e.toString()); } // Clean the data to be complaint JSON format data = sb.toString().replace("info = ", ""); try { jObject = new JSONObject(data); data = jObject.getString("h"); fileTitle = jObject.getString("title"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } downloadUrl = String.format(downloadUrl, fileId, data); return downloadUrl; } } So my idea was to get the content and if equal to $$$ERROR$$$ go into loop until JSON data is passed but I guess there is better solution. Note: I don't have control over the server output so have to deal with what I have.

    Read the article

  • Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?

    - by Mulmoth
    It is said to be a good habit to close all JDBC resources after usage. But if I have the following code, is it necessary to close the Resultset and the Statement? Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = // Retrieve connection stmt = conn.prepareStatement(// Some SQL); rs = stmt.executeQuery(); } catch { // Error Handling } finally { try { if (rs != null) rs.close(); } catch (Exception e) {}; try { if (stmt != null) stmt.close(); } catch (Exception e) {}; try { if (conn != null) conn.close(); } catch (Exception e) {}; } The question is if the closing of the connection does the job or if it leaves some resources in use.

    Read the article

  • CSS horizontal scrolling overflow with jQuery slider

    - by Jeffrey
    I'm trying to setup a full screen jquery slider. I've broken the project into two steps 1) css and 2) js. 1) CSS, below is a picture of what I'm shooting for (no fixed height) and below that is the code I have so far that doesn't work. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <style type="text/css"> /* Positioning */ #container { width: 2500px; } .block { display: inline; } /* Styling */ .block img { padding: 5px; } </style> </head> <body> <div id="container"> <div class="block"><img src="http://i42.tinypic.com/1zp2poz.gif"></div> <div class="block"><img src="http://i42.tinypic.com/1zp2poz.gif"></div> <div class="block"><img src="http://i42.tinypic.com/1zp2poz.gif"></div> </div> </body> </html> 2) Javascript, using jquery I'd like the divs to slide left when clicked on them... like the jQuery Coda Slider if possible. Thanks, any help is appreciated.

    Read the article

  • How do I close a file after catching an IOException in java?

    - by DimDom
    All, I am trying to ensure that a file I have open with BufferedReader is closed when I catch an IOException, but it appears as if my BufferedReader object is out of scope in the catch block. public static ArrayList readFiletoArrayList(String fileName, ArrayList fileArrayList) { fileArrayList.removeAll(fileArrayList); try { //open the file for reading BufferedReader fileIn = new BufferedReader(new FileReader(fileName)); // add line by line to array list, until end of file is reached // when buffered reader returns null (todo). while(true){ fileArrayList.add(fileIn.readLine()); } }catch(IOException e){ fileArrayList.removeAll(fileArrayList); fileIn.close(); return fileArrayList; //returned empty. Dealt with in calling code. } } Netbeans complains that it "cannot find symbol fileIn" in the catch block, but I want to ensure that in the case of an IOException that the Reader gets closed. How can I do that without the ugliness of a second try/catch construct around the first? Any tips or pointers as to best practise in this situation is appreciated,

    Read the article

  • Exceptions confusion

    - by Misiur
    Hi there. I'm trying to build site using OOP in PHP. Everyone is talking about Singleton, hermetization, MVC, and using exceptions. So I've tried to do it like this: Class building whole site: class Core { public $is_core; public $theme; private $db; public $language; private $info; static private $instance; public function __construct($lang = 'eng', $theme = 'default') { if(!self::$instance) { try { $this->db = new sdb(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS); } catch(PDOException $e) { throw new CoreException($e->getMessage()); } try { $this->language = new Language($lang); } catch(LangException $e) { throw new CoreException($e->getMessage()); } try { $this->theme = new Theme($theme); } catch(ThemeException $e) { throw new CoreException($e->getMessage()); } } return self::$instance; } public function getSite($what) { return $this->language->getLang(); } private function __clone() { } } Class managing themes class Theme { private $theme; public function __construct($name = 'default') { if(!is_dir("themes/$name")) { throw new ThemeException("Unable to load theme $name"); } else { $this->theme = $name; } } public function getTheme() { return $this->theme; } public function display($part) { if(!is_file("themes/$this->theme/$part.php")) { throw new ThemeException("Unable to load theme part: themes/$this->theme/$part.php"); } else { return 'So far so good'; } } } And usage: error_reporting(E_ALL); require_once('config.php'); require_once('functions.php'); try { $core = new Core(); } catch(CoreException $e) { echo 'Core Exception: '.$e->getMessage(); } echo $core->theme->getTheme(); echo "<br />"; echo $core->language->getLang(); try { $core->theme->display('footer'); } catch(ThemeException $e) { echo $e->getMessage(); } I don't like those exception handlers - i don't want to catch them like some pokemons... I want to use things simple: $core-theme-display('footer'); And if something is wrong, and debug mode is enabled, then aplication show error. What should i do?

    Read the article

  • What's Wrong With My VB.NET Code Of Windows Forms Application?

    - by Krishanu Dey
    I've to forms frmPrint & frmEmail and a dataset(MyDataset) with some DataTable and DataTable Adapters. In frmPrint I've the following Sub Public Sub StartPrinting() try adapterLettersInSchedules.Fill(ds.LettersInSchedules) adapterLetters.Fill(ds.Letters) adapterClients.Fill(ds.Clients) adapterPrintJobs.GetPrintJobsDueToday(ds.PrintJobs, False, DateTime.Today) For Each prow As MyDataSet.PrintJobsRow In ds.PrintJobs Dim lisrow As MyDataSet.LettersInSchedulesRow = ds.LettersInSchedules.FindByID(prow.LetterInScheduleID) If lisrow.Isemail = False Then Dim clientrow As MyDataSet.ClientsRow = ds.Clients.FindByClientID(prow.ClientID) Dim letterrow As MyDataSet.LettersRow = ds.Letters.FindByID(lisrow.LetterID) 'prow. 'lisrow.is Label1.SuspendLayout() Label1.Refresh() Label1.Text = "Printing letter" txt.Rtf = letterrow.LetterContents txt.Rtf = txt.Rtf.Replace("<%Firstname%>", clientrow.FirstName) txt.Rtf = txt.Rtf.Replace("<%Lastname%>", clientrow.LastName) txt.Rtf = txt.Rtf.Replace("<%Title%>", clientrow.Title) txt.Rtf = txt.Rtf.Replace("<%Street%>", clientrow.Street) txt.Rtf = txt.Rtf.Replace("<%City%>", clientrow.City) txt.Rtf = txt.Rtf.Replace("<%State%>", clientrow.State) txt.Rtf = txt.Rtf.Replace("<%Zip%>", clientrow.Zip) txt.Rtf = txt.Rtf.Replace("<%PhoneH%>", clientrow.PhoneH) txt.Rtf = txt.Rtf.Replace("<%PhoneW%>", clientrow.PhoneW) txt.Rtf = txt.Rtf.Replace("<%Date%>", DateTime.Today.ToShortDateString) Try PDoc.PrinterSettings = printDlg.PrinterSettings PDoc.Print() prow.Printed = True adapterPrintJobs.Update(prow) Catch ex As Exception End Try End If Next prow ds.PrintJobs.Clear() Catch ex As Exception MessageBox.Show(ex.Message, "Print", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub And in frmEmail i've the Following Sub Public Sub SendEmails() try adapterLettersInSchedules.Fill(ds.LettersInSchedules) adapterLetters.Fill(ds.Letters) adapterClients.Fill(ds.Clients) adapterEmailJobs.GetEmailJobsDueToday(ds.EmailJobs, False, Today) Dim ls_string As String For Each prow As MyDataSet.EmailJobsRow In ds.EmailJobs Dim lisrow As MyDataSet.LettersInSchedulesRow = ds.LettersInSchedules.FindByID(prow.LetterInScheduleID) If lisrow.Isemail = True Then Dim clientrow As MyDataSet.ClientsRow = ds.Clients.FindByClientID(prow.ClientID) Dim letterrow As MyDataSet.LettersRow = ds.Letters.FindByID(lisrow.LetterID) txt.Rtf = letterrow.LetterContents ls_string = RTF2HTML(txt.Rtf) ls_string = Mid(ls_string, 1, Len(ls_string) - 176) If ls_string = "" Then Throw New Exception("Rtf To HTML Conversion Failed") Label1.SuspendLayout() Label1.Refresh() Label1.Text = "Sending Email" If SendEmail(clientrow.Email, ls_string, letterrow.EmailSubject) Then Try prow.Emailed = True adapterEmailJobs.Update(prow) Catch ex As Exception End Try Else prow.Emailed = False adapterEmailJobs.Update(prow) End If End If Next prow Catch ex As Exception MessageBox.Show(ex.Message, "Email", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub I'm running this two subs using two different Threads. Public th As New Thread(New ThreadStart(AddressOf StartFirstPrint)) Public th4 As New Thread(New ThreadStart(AddressOf sendFirstEmail)) Here is the code of StartFirstPrint and sendFirstEmail Public Sub StartFirstPrint() Do While thCont Try Dim frm As New frmPrint() 'frm.MdiParent = Me frm.StartPrinting() Catch ex As Exception End Try Loop End Sub Public Sub sendFirstEmail() Do While thCont Try Dim frmSNDEmail As New frmEmail frmSNDEmail.SendEmails() Catch ex As Exception End Try Loop End Sub the thCont is a public boolean variable that specifies when to shop those threads. Most Of the time this works very well. But some times it gives errors Like the following image I don't know why is this occurring. Please help me.

    Read the article

< Previous Page | 70 71 72 73 74 75 76 77 78 79 80 81  | Next Page >