When I Ctrl C my program on linux I often get output that looks similar to a stack-dump (a crash).
Can I catch the Ctrl-C signal and exit gracefully?
Thanks!
I have a system with a few different databases, and I would like to check if a certain database is down, and if so display a message to the user.
Is it possible in NHibernate to check if there is an active connection to the database, without having to request data and then catch the exception?
Hello!
I cannot find a simple example about my question above: how can i detect the end of a method chain?
I'm just looked Zend_Db_Select for example but this one is too complex for this simple question i think.
Is it possible to catch the 'end' of a method chain in PHP?
thanks,
fabrik
I have this colom Model on JqGrid:
{name:'ta',index:'ta',jsonmap:'ta',width:70,editable:true,edittype:'select',
editoptions: {dataUrl:hostname+'/sisfa/ta_cb'}}
I am using JqGrid form editing to edit this field. How to 'catch' the field editor for this field on form editing. I'm using this method, but not work
.editGridRow("new",
{closeAfterAdd: true, addCaption:'Add Data',
width:500,dataheight:300,beforeShowForm:function(formid){
console.log($('#tr_ta').find('select[name=ta]'));
}});
This method work for other edittype.
Hi, I have this script which loads external content:
<script type="text/javascript">
var http_request = false;
function makePOSTRequest(url, parameters) {
http_request = false;
if (window.XMLHttpRequest) {
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) {
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = alertContents;
http_request.open('POST', url, true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", parameters.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(parameters);
}
function alertContents() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
result = http_request.responseText;
document.getElementById('opciones').innerHTML = result;
} else {
alert('Hubo un problema con la operación.');
}
}
}
function get(obj) {
var poststr = "port_post=" + encodeURI( document.getElementById("port-post").value );
makePOSTRequest('http://www.site.com/inc/metaform.php?opcion='+ encodeURI( document.getElementById("port-post").value ), poststr);
}
</script>
This is the select that retrieves the content:
<select name="port_post" id="port-post" onchange="get(this.parentNode);">
<option value="1">Select one...</option>
<option value="2">Pear</option>
<option value="3">Pineapple</option>
</select>
And this is the container div:
<div id="opciones">Default content</div>
All I whish to know is how I can unset the ajax loading when I change the selection to "Select one...". I wish to say, how restoring the Default content once the "Select one..." option is selected.
hi ,
i am making a app which takes photo on button click
i have camera.java which operates camera and takes photo
how to i call it on the below event?
public void onClick(DialogInterface arg0, int arg1) {
setContentView(R.layout.startcamera);
}
Camera .java
package neuro.com;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
public class CameraDemo extends Activity {
private static final String TAG = "CameraDemo";
Camera camera;
Preview preview;
Button buttonClick;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.startcamera);
preview = new Preview(this);
((FrameLayout) findViewById(R.id.preview)).addView(preview);
buttonClick = (Button) findViewById(R.id.buttonClick);
buttonClick.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
preview.camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
});
Log.d(TAG, "onCreate'd");
}
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
Log.d(TAG, "onShutter'd");
}
};
/** Handles data for raw picture */
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
Log.d(TAG, "onPictureTaken - raw");
}
};
/** Handles data for jpeg picture */
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
try {
// write to local sandbox file system
// outStream = CameraDemo.this.openFileOutput(String.format("%d.jpg", System.currentTimeMillis()), 0);
// Or write to sdcard
outStream = new FileOutputStream(String.format("/sdcard/%d.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Log.d(TAG, "onPictureTaken - jpeg");
}
};
}
In my project I can successfully test database code. I'm using Spring, Hibernate, HSQL, junit and Maven.
The catch is that currently I have to launch HSQL manually prior to running the tests. What is the best way to automate the launching of HSQL with the technologies being used?
Using this code it should return a list of the assets. But it crashes, with a "Source not found, Edit Source Lookup Path..." message in the debugger when I call the list method:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AssetManager assets = this.getAssets();
try {
//error happens on this next line
String[] l = assets.list(null);
} catch (IOException e) {
}
}
Question 1: How should I structure my project so the sound and images files can be loaded most easily? Right now, I have the folder:
C:\java\pacman
with the sub-directory
C:\java\pacman\src
containing all the code, and
C:\java\pacman\assets
containing the images and .wav files. Is this the best structure or should I put the assets somewhere else?
Question 2:
What's the best way to refer to the images/sounds without using the full path e.g C:\java\pacman\assets\something.png to them? If I use the getCodeBase() function it seems to refer to the C:\java\pacman\bin instead of C:\java\pacman\.
I want to use such a function/class which would work automatically when i compile the applet in a jar as well as right now when I test the applet through eclipse.
Question 3: How should I load the images/sounds? This is what I'm using now:
1) For general images:
import java.awt.Image;
public Image getImg(String file)
{
//imgDir in this case is a hardcoded string containing
//"C:\\java\\pacman\\assets\\"
file=imgDir + file;
return new ImageIcon(file).getImage();
}
The images returned from this function are used in the drawImage method of the Graphics class in the paint method of the applet.
2) For a buffered image, which is used to get subImages and load sprites from a sprite sheet:
public BufferedImage getSheet() throws IOException
{
return ImageIO.read(new File(img.getPath("pacman-sprites.png")));
}
Later:
public void loadSprites()
{
BufferedImage sheet;
try
{
sheet=getSheet();
redGhost.setNormalImg(sheet.getSubimage(0, 60, 20, 20));
redGhost.setUpImg(sheet.getSubimage(0, 60, 20, 20));
redGhost.setDownImg(sheet.getSubimage(30, 60, 20, 20));
redGhost.setLeftImg(sheet.getSubimage(30, 60, 20, 20));
redGhost.setRightImg(sheet.getSubimage(60, 60, 20, 20));
}
catch (IOException e)
{
System.out.println("Couldnt open file!");
System.out.println(e.getLocalizedMessage());
}
}
3) For sound files:
import sun.audio.*;
import java.io.*;
public synchronized void play() {
try {
InputStream in = new FileInputStream(filename);
AudioStream as = new AudioStream(in);
AudioPlayer.player.start(as);
} catch (IOException e) {
e.printStackTrace();
}
}
Regarding the terminate handler,
As i understand it, when something bad happens in code, for example when we dont catch an exception,
terminate() is called, which in turn calls abort()
set_terminate(my_function) allows us to get terminate() to call a user specified function my_terminate.
my question is: where do these functions "live" they don't seem to be a part of the language, but work as if they are present in every single cpp file, without having to include any header file.
I got a problem regrading with my apps which is once I go to my apps, it sure will show me a login page instead of allow page?
it always display the login page 1st then only display allow page, I had tried other apps, if I am 1st time user, It sure will appear the allow page only, it did not show me the login page.
my question is how to I avoid my login page direct go to allow page?
here is my login page picture
here is my apps link
https://apps.facebook.com/christmas_testing/
here is my facebook php jdk api coding
<?php
$fbconfig['appid' ] = "XXXXXXXXXXXXX";
$fbconfig['secret'] = "XXXXXXXXXXXXX";
$fbconfig['baseUrl'] = "myserverlink";
$fbconfig['appBaseUrl'] = "http://apps.facebook.com/christmas_testing/";
if (isset($_GET['code'])){
header("Location: " . $fbconfig['appBaseUrl']);
exit;
}
if (isset($_GET['request_ids'])){
//user comes from invitation
//track them if you need
header("Location: " . $fbconfig['appBaseUrl']);
}
$user = null; //facebook user uid
try{
include_once "facebook.php";
}
catch(Exception $o){
echo '<pre>';
print_r($o);
echo '</pre>';
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => true,
));
//Facebook Authentication part
$user = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email,publish_stream,user_birthday,user_location,user_work_history,user_about_me,user_hometown'
)
);
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
//you should use error_log($e); instead of printing the info on browser
d($e); // d is a debug function defined at the end of this file
$user = null;
}
}
if (!$user) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
//get user basic description
$userInfo = $facebook->api("/$user");
function d($d){
echo '<pre>';
print_r($d);
echo '</pre>';
}
?
Hi All,
I am writing an application that can record a 3GP video.
I have tried both MMAPI and Invoke API. But have following issues.
Using MMAPI:
1. When I record to stream, It records video in RIMM streaming format. when I try to play this video player gives error "Unsupported media format.".
2. When I record to a file. It will create a file of size 0.
Using Invoke API:
1. In MMS mode it does not allow to record a video more than 30 seconds.
2. In Normal mode size of the file is very large.
3. Once I invoke camera application I do not have any control on application.
Here is my source code:
_player = javax.microedition.media.Manager
.createPlayer("capture://video?encoding=video/3gpp&mode=mms");
// I have tried every encoding returns from System.getProperty("video.encodings") method
_player.realize();
_videoControl = (VideoControl) _player.getControl("VideoControl");
_recordControl = (RecordControl) _player.getControl("RecordControl");
_volumeControl = (VolumeControl) _player.getControl("VolumeControl");
String videoPath = System.getProperty("fileconn.dir.videos");
if (videoPath == null) {
videoPath = "file:///store/home/user/videos/";
}
_recordControl.setRecordLocation(videoPath + "RecordedVideo.3gp");
_player.addPlayerListener(this);
Field videoField = (Field) _videoControl.initDisplayMode(
VideoControl.USE_GUI_PRIMITIVE,
"net.rim.device.api.ui.Field");
_videoControl.setVisible(true);
add(videoField);
_player.start();
ON start menu item Selection:
try {
_recordControl.startRecord();
} catch (Exception e) {
_player.close();
showAlert(e.getClass() + " " + e.getMessage());
}
On stop menuItem selection:
try {
_recordControl.commit();
} catch (Exception e) {
_player.close();
showAlert(e.getClass() + " " + e.getMessage());
}
Please let me if I am doing something wrong.
Thanks,
Pankaj
I have a very strange problem. It only shows from time to time, on several devices. Can't seem to reproduce it when I want, but had it so many times, that I think I know where I get it.
So I have a Loader which connects to sqlite through a singleton SQLiteOpenHelper:
try{
Log.i(TAG, "Get details offline / db helper: "+DatabaseHelper.getInstance(getContext()));
SQLiteDatabase db=DatabaseHelper.getInstance(this.getContext()).getWritableDatabase();
Log.i(TAG, "Get details offline / db: "+db);
//doing some work on the db
//...
} catch(SQLiteException e){
e.printStackTrace();
return null;
} catch(Exception e){
e.printStackTrace();
return null;
//trying everything to grab some exception or whatever
}
My SQLIteOpenHelper looks something like this:
public class DatabaseHelper extends SQLiteOpenHelper {
private static DatabaseHelper mInstance = null;
private static Context mCxt;
public static DatabaseHelper getInstance(Context cxt) {
//using app context ass suggested by CommonsWare
Log.i("DBHELPER1", "cxt"+mCxt+" / instance: "+mInstance);
if (mInstance == null) {
mInstance = new DatabaseHelper(cxt.getApplicationContext());
}
Log.i("DBHELPER2", "cxt"+mCxt+" / instance: "+mInstance);
mCxt = cxt;
return mInstance;
}
//private constructor
private DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.mCxt = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
//some tables created here
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//upgrade code here
}
It really works great in most cases. But from time to time I get a log similar to this:
06-10 23:49:59.621: I/DBHELPER1(26499): cxtcom.bananout.Bananout@407152c8 / instance: com.bananout.helpers.DatabaseHelper@40827560
06-10 23:49:59.631: I/DBHELPER2(26499): cxtcom.bananout.Bananout@407152c8 / instance: com.bananout.helpers.DatabaseHelper@40827560
06-10 23:49:59.631: I/DetailsLoader(26499): Get event details offline / db helper: com.bananout.helpers.DatabaseHelper@40827560
06-10 23:49:59.631: I/DBHELPER1(26499): cxtcom.bananout.Bananout@407152c8 / instance: com.bananout.helpers.DatabaseHelper@40827560
06-10 23:49:59.651: I/DBHELPER2(26499): cxtcom.bananout.Bananout@407152c8 / instance: com.bananout.helpers.DatabaseHelper@40827560
This line Log.i(TAG, "Get details offline / db: "+db); never gets called! No Exceptions, silence. Plus, the thread with the Loader is not running anymore.
So nothing past this line SQLiteDatabase db=DatabaseHelper.getInstance(this.getContext()).getWritableDatabase(); gets executed.
What can possibly go wrong on this line?
I have a scale that connect to PC through RS232, I send "W" to receive the weight. The scale sends the weight all the time as it's read. How do I catch the weight that is being read?
Can i get any C# sample code?
Hi,
How to properly construct regular expression for "grep" linux program, to find all email in, say /etc directory ?
Currently, my script is following:
grep -srhw "[[:alnum:]]*@[[:alnum:]]*" /etc
It working OK - a see some of the emails, but when i modify it, to catch the one-or-more charactes before- and after the "@" sign ...
grep -srhw "[[:alnum:]]+@[[:alnum:]]+" /etc
.. it stops working at all
Also, it does't catches emails of form "[email protected]"
Help !
I have a program that throws an uncaught exception somewhere. All I get is a report of an exception being thrown, and no information as to where it was thrown. It seems illogical for a program compiled to contain debug symbols not to notify me of where in my code an exception was generated.
Is there any way to tell where my exceptions are coming from short of setting 'catch throw' in gdb and calling a backtrace for every single thrown exception?
The problem is in being able to catch the instance of the player to control it i.e. Stop it, Play it etc. The code by default creates multiple instances of the same player and overlaps the songs. I am being unable to reference the player specifically.
Do you have an idea as to how we can do so?
Thanks,
Arun
Hi all iam working on servlets, so i need to upload a file by using servlet as follows my code.
package com.limrasoft.image.servlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.sql.*;
@WebServlet(name="serv1",value="/s1")
public class Account extends HttpServlet{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connecection con=null;
try{
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","sajid");
PrintWriter pw=res.getWriter();
res.setContentType("text/html");
String s1=req.getParameter("un");
string s2=req.getParameter("pwd");
String s3=req.getParameter("g");
String s4=req.getParameter("uf");
PreparedStatement ps=con.prepareStatement("insert into account(?,?,?,?)");
ps.setString(1,s1);
ps.setString(2,s2);
ps.setString(3,s3);
File file=new File("+s4+");
FileInputStream fis=new FileInputStream(fis);
int len=(int)file.length();
ps.setBinaryStream(4,fis,len);
int c=ps.executeUpdate();
if(c==0){pw.println("<h1>Registratin fail");}
else{pw.println("<h1>Registration fail");}
}
finally{if(con!=null)con.close();}
}
catch(ClassNotFoundException ce){pw.println("<h1>Registration Fail");}
catch(SQLException se){pw.println("<h1>Registration Fail");}
pw.flush();
pw.close();
}
}
I have written the above code for file upload into database, but it giving error as "HTTP Status 500 - Servlet3.java (The system cannot find the file specified)"
Could you plz help me to do this code,thanks in advanse.
i try to write simplest possible server app in Java, displaying html form with textarea input, which after submitting gives me possibility to parse xml typed in thet textarea. For now i build simple serversocket based server like that:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class WebServer {
protected void start() {
ServerSocket s;
String gets = "";
System.out.println("Start on port 80");
try {
// create the main server socket
s = new ServerSocket(80);
} catch (Exception e) {
System.out.println("Error: " + e);
return;
}
System.out.println("Waiting for connection");
for (;;) {
try {
// wait for a connection
Socket remote = s.accept();
// remote is now the connected socket
System.out.println("Connection, sending data.");
BufferedReader in = new BufferedReader(new InputStreamReader(
remote.getInputStream()));
PrintWriter out = new PrintWriter(remote.getOutputStream());
String str = ".";
while (!str.equals("")) {
str = in.readLine();
if (str.contains("GET")){
gets = str;
break;
}
}
out.println("HTTP/1.0 200 OK");
out.println("Content-Type: text/html");
out.println("");
// Send the HTML page
String method = "get";
out.print("<html><form method="+method+">");
out.print("<textarea name=we></textarea></br>");
out.print("<input type=text name=a><input type=submit></form></html>");
out.println(gets);
out.flush();
remote.close();
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}
public static void main(String args[]) {
WebServer ws = new WebServer();
ws.start();
}
}
After form (textarea with xml and one additional text input) is submitted in 'gets' String-type variable I have Urlencoded values of my variables (also displayed on the screen, it looks like that:
gets = GET /?we=%3Cnetwork+ip_addr%3D%2210.0.0.0%2F8%22+save_ip%3D%22true%22%3E%0D%0A%3Csubnet+interf_used%3D%22200%22+name%3D%22lan1%22+%2F%3E%0D%0A%3Csubnet+interf_used%3D%22254%22+name%3D%22lan2%22+%2F%3E%0D%0A%3C%2Fnetwork%3E&a=fooBar HTTP/1.1
What can i do to change GET to POST method (if i simply change it in form and than put " if (str.contains("GET")){" it gives me string like
gets = POST / HTTP/1.1
with no variables. And after that, how i can use xml from my textarea field (called 'we')?
can I do something like this:
using (var scope = new TransactionScope())
{
using (var conn = new SqlConnection(Cs))
{
using (var cmd = conn.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
...
scope.complete();
}
}
}
is going to be the same thing as using the SqlTransaction with catch(){rollback;}
HI ALL,
I got an error java.lang.UnsatisfiedLinkError, I am not getting wat the problem is.
public static void main(String[] args) {
try {
System.loadLibrary("pfcasyncmt");
}catch(){
}
}
ERROR-
xception in thread "main" java.lang.UnsatisfiedLinkError: no pfcasyncmt in java.library.path
Hi,
I created one blackberry application which will play a video on a button click.This is my code,
invocation=new Invocation("file:///SDCard/Blackberry/videos/PlayingVideo/funny.mp4");
registry=Registry.getRegistry("net.rim.device.api.content.BlackBerryContentHandler");
try
{
registry.invoke(invocation);
}
catch(Exception e)
{
}
Now i can play the Video file.After clicking the Back button the native player is going to the background.It always running in the background.But i want to close that player.I have no idea about how to do it.Anybody knows please help me.
I've got a number of tasks/servlets that are hitting the HardDeadlineExceededError which is leaving everything hanging in an 'still executing' state.
The work being done can easily exceed the 29 second threshold.
I try to catch the DeadlineExceededException and base Exception in order to save the exit
state but neither of these exception handlers are being caught...
Is there a way to determine which tasks are in the queue or currently executing?
Are there any other strategies for dealing with this situation?
I have a SurfaceView and I want the Bitmap Logo inside it in the canvas to be movable
What I'm doing wrong ?
static float x, y;
Bitmap logo;
SurfaceView ss = (SurfaceView) findViewById(R.id.svSS);
logo = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
x = 40;
y = 415;
ss.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent me) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
switch(me.getAction()) {
case MotionEvent.ACTION_DOWN:
x = me.getX();
y = me.getY();
break;
case MotionEvent.ACTION_UP:
x = me.getX();
y = me.getY();
break;
case MotionEvent.ACTION_MOVE:
x = me.getX();
y = me.getY();
break;
}
return true;
}
});
public class OurView extends SurfaceView implements Runnable{
Thread t = null;
SurfaceHolder holder;
boolean isItOK = false;
public OurView(Context context) {
super(context);
holder = getHolder();
}
public void run (){
while (isItOK == true){
//canvas DRAWING
if (!holder.getSurface().isValid()){
continue;
}
Canvas c = holder.lockCanvas();
c.drawARGB(255, 200, 100, 100);
c.drawBitmap(logo, x,y,null);
holder.unlockCanvasAndPost(c);
}
}
public void pause(){
isItOK = false;
while(true){
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
}
t = null;
}
public void resume(){
isItOK = true;
t = new Thread(this);
t.start();
}
}
Now the surface view is just black .. nothing happens also its not colored 200, 100, 100