Search Results

Search found 4181 results on 168 pages for 'exit'.

Page 16/168 | < Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >

  • Cancelling WPF Application.Shutdown

    - by MarkPearl
    Today I spent the better part of an hour trying to figure out what I had had done wrong. I had an application that when the user click’s “exit”, it should prompt if they want to save the last unsaved file, or cancel the exit. If the select cancel it should not exit the application. Everything seemed fine in my code, all I was doing was calling Application.Current.Shutdown(); And then capturing the Closing event and setting cancel to true.. (see SO question here) Long story short, If should not have been calling Application.Current.Shutdown() but rather Application.Current.MainWindow.Close(). grrrr… <I must read documentation properly>

    Read the article

  • puma init.d for centos 6 fails with runuser: user /var/log/puma.log does not exist

    - by Rubytastic
    Trying to get a init.d/puma to work on Centos 6. It throws error runuser: user /var/log/puma.log does not exist I run this from the /srv/books/current folder but it fails. I tried to debug the values but not quite get what is missing and why it throws this error. #! /bin/sh # puma - this script starts and stops the puma daemon # # chkconfig: - 85 15 # description: Puma # processname: puma # config: /etc/puma.conf # pidfile: /srv/books/current/tmp/pids/puma.pid # Author: Darío Javier Cravero &lt;[email protected]> # # Do NOT "set -e" # Original script https://github.com/puma/puma/blob/master/tools/jungle/puma # It was modified here by Stanislaw Pankevich <[email protected]> # to run on CentOS 5.5 boxes. # Script works perfectly on CentOS 5: script uses its native daemon(). # Puma is being stopped/restarted by sending signals, control app is not used. # Source function library. . /etc/rc.d/init.d/functions # Source networking configuration. . /etc/sysconfig/network # Check that networking is up. [ "$NETWORKING" = "no" ] && exit 0 # PATH should only include /usr/* if it runs after the mountnfs.sh script PATH=/usr/local/bin:/usr/local/sbin/:/sbin:/usr/sbin:/bin:/usr/bin DESC="Puma rack web server" NAME=puma DAEMON=$NAME SCRIPTNAME=/etc/init.d/$NAME CONFIG=/etc/puma.conf JUNGLE=`cat $CONFIG` RUNPUMA=/usr/local/bin/run-puma # Skipping the following non-CentOS string # Load the VERBOSE setting and other rcS variables # . /lib/init/vars.sh # CentOS does not have these functions natively log_daemon_msg() { echo "$@"; } log_end_msg() { [ $1 -eq 0 ] && RES=OK; logger ${RES:=FAIL}; } # Define LSB log_* functions. # Depend on lsb-base (>= 3.0-6) to ensure that this file is present. . /lib/lsb/init-functions # # Function that performs a clean up of puma.* files # cleanup() { echo "Cleaning up puma temporary files..." echo $1; PIDFILE=$1/tmp/puma/puma.pid STATEFILE=$1/tmp/puma/puma.state SOCKFILE=$1/tmp/puma/puma.sock rm -f $PIDFILE $STATEFILE $SOCKFILE } # # Function that starts the jungle # do_start() { log_daemon_msg "=> Running the jungle..." for i in $JUNGLE; do dir=`echo $i | cut -d , -f 1` user=`echo $i | cut -d , -f 2` config_file=`echo $i | cut -d , -f 3` if [ "$config_file" = "" ]; then config_file="$dir/puma/config.rb" fi log_file=`echo $i | cut -d , -f 4` if [ "$log_file" = "" ]; then log_file="$dir/puma/puma.log" fi do_start_one $dir $user $config_file $log_file done } do_start_one() { PIDFILE=$1/puma/puma.pid if [ -e $PIDFILE ]; then PID=`cat $PIDFILE` # If the puma isn't running, run it, otherwise restart it. if [ "`ps -A -o pid= | grep -c $PID`" -eq 0 ]; then do_start_one_do $1 $2 $3 $4 else do_restart_one $1 fi else do_start_one_do $1 $2 $3 $4 fi } do_start_one_do() { log_daemon_msg "--> Woke up puma $1" log_daemon_msg "user $2" log_daemon_msg "log to $4" cleanup $1; daemon --user $2 $RUNPUMA $1 $3 $4 } # # Function that stops the jungle # do_stop() { log_daemon_msg "=> Putting all the beasts to bed..." for i in $JUNGLE; do dir=`echo $i | cut -d , -f 1` do_stop_one $dir done } # # Function that stops the daemon/service # do_stop_one() { log_daemon_msg "--> Stopping $1" PIDFILE=$1/tmp/puma/puma.pid STATEFILE=$1/tmp/puma/puma.state echo $PIDFILE if [ -e $PIDFILE ]; then PID=`cat $PIDFILE` echo "Pid:" echo $PID if [ "`ps -A -o pid= | grep -c $PID`" -eq 0 ]; then log_daemon_msg "---> Puma $1 isn't running." else log_daemon_msg "---> About to kill PID `cat $PIDFILE`" # pumactl --state $STATEFILE stop # Many daemons don't delete their pidfiles when they exit. kill -9 $PID fi cleanup $1 else log_daemon_msg "---> No puma here..." fi return 0 } # # Function that restarts the jungle # do_restart() { for i in $JUNGLE; do dir=`echo $i | cut -d , -f 1` do_restart_one $dir done } # # Function that sends a SIGUSR2 to the daemon/service # do_restart_one() { PIDFILE=$1/tmp/puma/puma.pid i=`grep $1 $CONFIG` dir=`echo $i | cut -d , -f 1` if [ -e $PIDFILE ]; then log_daemon_msg "--> About to restart puma $1" # pumactl --state $dir/tmp/puma/state restart kill -s USR2 `cat $PIDFILE` # TODO Check if process exist else log_daemon_msg "--> Your puma was never playing... Let's get it out there first" user=`echo $i | cut -d , -f 2` config_file=`echo $i | cut -d , -f 3` if [ "$config_file" = "" ]; then config_file="$dir/config/puma.rb" fi log_file=`echo $i | cut -d , -f 4` if [ "$log_file" = "" ]; then log_file="$dir/log/puma.log" fi do_start_one $dir $user $config_file $log_file fi return 0 } # # Function that statuss then jungle # do_status() { for i in $JUNGLE; do dir=`echo $i | cut -d , -f 1` do_status_one $dir done } # # Function that sends a SIGUSR2 to the daemon/service # do_status_one() { PIDFILE=$1/tmp/puma/pid i=`grep $1 $CONFIG` dir=`echo $i | cut -d , -f 1` if [ -e $PIDFILE ]; then log_daemon_msg "--> About to status puma $1" pumactl --state $dir/tmp/puma/state stats # kill -s USR2 `cat $PIDFILE` # TODO Check if process exist else log_daemon_msg "--> $1 isn't there :(..." fi return 0 } do_add() { str="" # App's directory if [ -d "$1" ]; then if [ "`grep -c "^$1" $CONFIG`" -eq 0 ]; then str=$1 else echo "The app is already being managed. Remove it if you want to update its config." exit 1 fi else echo "The directory $1 doesn't exist." exit 1 fi # User to run it as if [ "`grep -c "^$2:" /etc/passwd`" -eq 0 ]; then echo "The user $2 doesn't exist." exit 1 else str="$str,$2" fi # Config file if [ "$3" != "" ]; then if [ -e $3 ]; then str="$str,$3" else echo "The config file $3 doesn't exist." exit 1 fi fi # Log file if [ "$4" != "" ]; then str="$str,$4" fi # Add it to the jungle echo $str >> $CONFIG log_daemon_msg "Added a Puma to the jungle: $str. You still have to start it though." } do_remove() { if [ "`grep -c "^$1" $CONFIG`" -eq 0 ]; then echo "There's no app $1 to remove." else # Stop it first. do_stop_one $1 # Remove it from the config. sed -i "\\:^$1:d" $CONFIG log_daemon_msg "Removed a Puma from the jungle: $1." fi } case "$1" in start) [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME" if [ "$#" -eq 1 ]; then do_start else i=`grep $2 $CONFIG` dir=`echo $i | cut -d , -f 1` user=`echo $i | cut -d , -f 2` config_file=`echo $i | cut -d , -f 3` if [ "$config_file" = "" ]; then config_file="$dir/config/puma.rb" fi log_file=`echo $i | cut -d , -f 4` if [ "$log_file" = "" ]; then log_file="$dir/log/puma.log" fi do_start_one $dir $user $config_file $log_file fi case "$?" in 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; esac ;; stop) [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME" if [ "$#" -eq 1 ]; then do_stop else i=`grep $2 $CONFIG` dir=`echo $i | cut -d , -f 1` do_stop_one $dir fi case "$?" in 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; esac ;; status) # TODO Implement. log_daemon_msg "Status $DESC" "$NAME" if [ "$#" -eq 1 ]; then do_status else i=`grep $2 $CONFIG` dir=`echo $i | cut -d , -f 1` do_status_one $dir fi case "$?" in 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; esac ;; restart) log_daemon_msg "Restarting $DESC" "$NAME" if [ "$#" -eq 1 ]; then do_restart else i=`grep $2 $CONFIG` dir=`echo $i | cut -d , -f 1` do_restart_one $dir fi case "$?" in 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; esac ;; add) if [ "$#" -lt 3 ]; then echo "Please, specifiy the app's directory and the user that will run it at least." echo " Usage: $SCRIPTNAME add /path/to/app user /path/to/app/config/puma.rb /path/to/app/config/log/puma.log" echo " config and log are optionals." exit 1 else do_add $2 $3 $4 $5 fi case "$?" in 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; esac ;; remove) if [ "$#" -lt 2 ]; then echo "Please, specifiy the app's directory to remove." exit 1 else do_remove $2 fi case "$?" in 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; esac ;; *) echo "Usage:" >&2 echo " Run the jungle: $SCRIPTNAME {start|stop|status|restart}" >&2 echo " Add a Puma: $SCRIPTNAME add /path/to/app user /path/to/app/config/puma.rb /path/to/app/config/log/puma.log" echo " config and log are optionals." echo " Remove a Puma: $SCRIPTNAME remove /path/to/app" echo " On a Puma: $SCRIPTNAME {start|stop|status|restart} PUMA-NAME" >&2 exit 3 ;; esac :

    Read the article

  • How do I solve this "unexpected '}' syntax error" in my bash script?

    - by WASasquatch
    I have a piece of code that has some serious issues and I was hoping to get it solved soon but no one has offered any help. I thought I'd try some Ubuntu users since this is the OS running the script. mc_addplugin() { if pgrep -u $USERNAME -f $SERVICE > /dev/null then echo "$SERVICE is running! Please stop the service before adding a plugin." else echo "Paste the URL to the .JAR Plugin..." read JARURL JARNAME=$(basename "$JARURL") if [ -d "$TEMPPLUGINS" ] then as_user "cd $PLUGINSPATH && wget -r -A.jar $JARURL -o temp_plugins/$JARNAME" else as_user "cd $PLUGINSPATH && mkdir $TEMPPLUGINS && wget -r -A.jar $JARURL -o temp_plugins/$JARNAME" fi if [ -f "$TMPDIR/$JARNAME" ] then if [ -f "$PLUGINSPATH/$JARNAME" ] then if `diff $PLUGINSPATH/$JARNAME $TMPDIR/$JARNAME >/dev/null` then echo "You are already running the latest version of $JARNAME." else NOW=`date "+%Y-%m-%d_%Hh%M"` echo "Are you sure you want to overwrite this plugin? [Y/n]" echo "Note: Your old plugin will be moved to the "$TEMPPLUGINS" folder with todays date." select yn in "Yes" "No"; do case $yn in Yes ) as_user "mv $PLUGINSPATH/$JARNAME $TEMPPLUGINS/${JARNAME}_${NOW} && mv $TEMPPLUGINS/$JARNAME $PLUGINSPATH/$JARNAME"; break;; No ) echo "The plugin has not been installed! Removing temporary plugin and exiting..." as_user "rm $TEMPPLUGINS/$JARNAME"; exit;; esac done echo "Would you like to start the $SERVICE now? [Y/n]" select yn in "Yes" "No"; do case $yn in Yes ) mc_start; break;; No ) "$SERVICE not running! To start the service run: /etc/init.d/craftbukkit start"; exit;; esac done fi else echo "Are you sure you want to add this new plugin? [Y/n]" select yn in "Yes" "No"; do case $yn in Yes ) as_user "mv $PLUGINSPATH/$JARNAME $TEMPPLUGINS/${JARNAME}_${NOW} && mv $TEMPPLUGINS/$JARNAME $PLUGINSPATH/$JARNAME"; break;; No ) echo "The plugin has not been installed! Removing temporary plugin and exiting..." as_user "rm $TEMPPLUGINS/$JARNAME"; exit;; esac done echo "Would you like to start the $SERVICE now? [Y/n]?" select yn in "Yes" "No"; do case $yn in Yes ) mc_start; break;; No ) "$SERVICE not running! To start the service run: /etc/init.d/craftbukkit start"; exit;; esac done fi else echo "Failed to download the plugin from the URL you specified!" exit; fi } It throws it at the closing bracket at the end of the function.

    Read the article

  • Send User-Agent through CONNECT and POST with WinHTTP?

    - by Duncan Bayne
    I'm trying to POST to a secure site using WinHttp, and running into a problem where the User-Agent header isn't being sent along with the CONNECT. I am using a lightly-modified code sample from MSDN: HINTERNET hHttpSession = NULL; HINTERNET hConnect = NULL; HINTERNET hRequest = NULL; WINHTTP_AUTOPROXY_OPTIONS AutoProxyOptions; WINHTTP_PROXY_INFO ProxyInfo; DWORD cbProxyInfoSize = sizeof(ProxyInfo); ZeroMemory( &AutoProxyOptions, sizeof(AutoProxyOptions) ); ZeroMemory( &ProxyInfo, sizeof(ProxyInfo) ); hHttpSession = WinHttpOpen(L"WinHTTP AutoProxy Sample/1.0", WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if(!hHttpSession) goto Exit; hConnect = WinHttpConnect( hHttpSession, L"server.com", INTERNET_DEFAULT_HTTPS_PORT, 0 ); if( !hConnect ) goto Exit; hRequest = WinHttpOpenRequest(hConnect, L"POST", L"/resource", NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE ); if( !hRequest ) goto Exit; WINHTTP_PROXY_INFO proxyInfo; proxyInfo.dwAccessType = WINHTTP_ACCESS_TYPE_NAMED_PROXY; proxyInfo.lpszProxy = L"192.168.1.2:3199"; proxyInfo.lpszProxyBypass = L""; WinHttpSetOption(hHttpSession, WINHTTP_OPTION_PROXY, &proxyInfo, sizeof(proxyInfo)); WinHttpSetCredentials(hRequest, WINHTTP_AUTH_TARGET_PROXY, WINHTTP_AUTH_SCHEME_BASIC, L"proxyuser", L"proxypass", NULL); if( !WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, "content", 7, 7, 0)) { goto Exit; } if(!WinHttpReceiveResponse(hRequest, NULL)) goto Exit; /* handle result */ Exit: if( ProxyInfo.lpszProxy != NULL ) GlobalFree(ProxyInfo.lpszProxy); if( ProxyInfo.lpszProxyBypass != NULL ) GlobalFree( ProxyInfo.lpszProxyBypass ); if( hRequest != NULL ) WinHttpCloseHandle( hRequest ); if( hConnect != NULL ) WinHttpCloseHandle( hConnect ); if( hHttpSession != NULL ) WinHttpCloseHandle( hHttpSession ); What this does is connect to my server through an authenticated proxy at 192.168.1.2:3199, and make a POST. This works, but when I examine the proxy logs the User-Agent string ("WinHTTP AutoProxy Sample/1.0") is not being sent as part of the CONNECT. It is however sent as part of the POST. Could someone please tell me how I can change this code to have the User-Agent header sent during both the CONNECT and POST? Edited to add: we are observing this problem only on Windows 7. If we run the same code on a Windows Vista box, we can see the User-Agent header being sent on CONNECT.

    Read the article

  • Python: some newbie questions on sys.stderr and using function as argument

    - by Cawas
    I'm just starting on Python and maybe I'm worrying too much too soon, but anyways... log = "/tmp/trefnoc.log" def logThis (text, display=""): msg = str(now.strftime("%Y-%m-%d %H:%M")) + " TREfNOC: " + text if display != None: print msg + display logfile = open(log, "a") logfile.write(msg + "\n") logfile.close() return msg def logThisAndExit (text, display=""): msg = logThis(text, display=None) sys.exit(msg + display) That is working, but I don't like how it looks. Is there a better way to write this (maybe with just 1 function) and is there any other thing I should be concerned under exiting? Now to some background... Sometimes I will call logThis just to log and display. Other times I want to call it and exit. Initially I was doing this: logThis ("ERROR. EXITING") sys.exit() Then I figured that wouldn't properly set the stderr, thus the current code shown on the top. My first idea was actually passing "sys.exit" as an argument, and defining just logThis ("ERROR. EXITING", call=sys.exit) defined as following (showing just the relevant differenced part): def logThis (text, display="", call=print): msg = str(now.strftime("%Y-%m-%d %H:%M")) + " TREfNOC: " + text call msg + display But that obviously didn't work. I think Python doesn't store functions inside variables. I couldn't (quickly) find anywhere if Python can have variables taking functions or not! Maybe using an eval function? I really always try to avoid them, tho. Sure I thought of using if instead of another def, but that wouldn't be any better or worst. Anyway, any thoughts?

    Read the article

  • Handling TclErrors in Python

    - by anteater7171
    In the following code I'll get the following error if I right click the window that pops up. Then go down to the very bottom entry widget then delete it's contents. It seems to be giving me a TclError. How do I go about handeling such an error? The Error Exception in Tkinter callback Traceback (most recent call last): File "C:\Python26\Lib\lib-tk\Tkinter.py", line 1410, in __call__ return self.func(*args) File "C:\Python26\CPUDEMO.py", line 503, in I TL.sclS.set(S1) File "C:\Python26\Lib\lib-tk\Tkinter.py", line 2765, in set self.tk.call(self._w, 'set', value) TclError: expected floating-point number but got "" The Code #F #PIthon.py # Import/Setup import Tkinter import psutil,time import re from PIL import Image, ImageTk from time import sleep class simpleapp_tk(Tkinter.Tk): def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.initialize() def initialize(self): Widgets self.menu = Tkinter.Menu(self, tearoff = 0 ) M = [ "Options...", "Exit"] self.selectedM = Tkinter.StringVar() self.menu.add_radiobutton( label = 'Hide', variable = self.selectedM, command = self.E ) self.menu.add_radiobutton( label = 'Bump', variable = self.selectedM, command = self.E ) self.menu.add_separator() self.menu.add_radiobutton( label = 'Options...', variable = self.selectedM, command = self.E ) self.menu.add_separator() self.menu.add_radiobutton( label = 'Exit', variable = self.selectedM, command = self.E ) self.frame1 = Tkinter.Frame(self,bg='grey15',relief='ridge',borderwidth=4,width=185, height=39) self.frame1.grid() self.frame1.grid_propagate(0) self.frame1.bind( "<Button-3><ButtonRelease-3>", self.D ) self.frame1.bind( "<Button-2><ButtonRelease-2>", self.C ) self.frame1.bind( "<Double-Button-1>", self.C ) self.labelVariable = Tkinter.StringVar() self.label = Tkinter.Label(self.frame1,textvariable=self.labelVariable,fg="lightgreen",bg="grey15",borderwidth=1,font=('arial', 10, 'bold')) self.label.grid(column=1,row=0,columnspan=1,sticky='nsew') self.label.bind( "<Button-3><ButtonRelease-3>", self.D ) self.label.bind( "<Button-2><ButtonRelease-2>", self.C ) self.label.bind( "<Double-Button-1>", self.C ) self.F() self.overrideredirect(1) self.wm_attributes("-topmost", 1) global TL1 TL1 = Tkinter.Toplevel(self) TL1.wm_geometry("+0+5000") TL1.overrideredirect(1) TL1.button = Tkinter.Button(TL1,text="? CPU",fg="lightgreen",bg="grey15",activeforeground="lightgreen", activebackground='grey15',borderwidth=4,font=('Arial', 8, 'bold'),command=self.J) TL1.button.pack(ipadx=1) Events def Reset(self): self.label.configure(font=('arial', 10, 'bold'),fg='Lightgreen',bg='grey15',borderwidth=0) self.labela.configure(font=('arial', 8, 'bold'),fg='Lightgreen',bg='grey15',borderwidth=0) self.frame1.configure(bg='grey15',relief='ridge',borderwidth=4,width=224, height=50) self.label.pack(ipadx=38) def helpmenu(self): t2 = Tkinter.Toplevel(self) Tkinter.Label(t2, text='This is a help menu', anchor="w",justify="left",fg="darkgreen",bg="grey90",relief="ridge",borderwidth=5,font=('Arial', 10)).pack(fill='both', expand=1) t2.resizable(False,False) t2.title('Help') menu = Tkinter.Menu(self) t2.config(menu=menu) filemenu = Tkinter.Menu(menu) menu.add_cascade(label="| Exit |", menu=filemenu) filemenu.add_command(label="Exit", command=t2.destroy) def aboutmenu(self): t1 = Tkinter.Toplevel(self) Tkinter.Label(t1, text=' About:\n\n CPU Usage v1.0\n\n Publisher: Drew French\n Date: 05/09/10\n Email: [email protected] \n\n\n\n\n\n\n Written in Python 2.6.4', anchor="w",justify="left",fg="darkgreen",bg="grey90",relief="sunken",borderwidth=5,font=('Arial', 10)).pack(fill='both', expand=1) t1.resizable(False,False) t1.title('About') menu = Tkinter.Menu(self) t1.config(menu=menu) filemenu = Tkinter.Menu(menu) menu.add_cascade(label="| Exit |", menu=filemenu) filemenu.add_command(label="Exit", command=t1.destroy) def A (self,event): TL.entryVariable1.set(TL.sclY.get()) TL.entryVariable2.set(TL.sclX.get()) Y = TL.sclY.get() X = TL.sclX.get() self.wm_geometry("+" + str(X) + "+" + str(Y)) def B(self,event): Y1 = TL.entryVariable1.get() X1 = TL.entryVariable2.get() self.wm_geometry("+" + str(X1) + "+" + str(Y1)) TL.sclY.set(Y1) TL.sclX.set(X1) def C(self,event): s = self.wm_geometry() geomPatt = re.compile(r"(\d+)?x?(\d+)?([+-])(\d+)([+-])(\d+)") m = geomPatt.search(s) X3 = m.group(4) Y3 = m.group(6) M = int(Y3) - 150 P = M + 150 while Y3 > M: sleep(0.0009) Y3 = int(Y3) - 1 self.update_idletasks() self.wm_geometry("+" + str(X3) + "+" + str(Y3)) sleep(2.00) while Y3 < P: sleep(0.0009) Y3 = int(Y3) + 1 self.update_idletasks() self.wm_geometry("+" + str(X3) + "+" + str(Y3)) def D(self, event=None): self.menu.post( event.x_root, event.y_root ) def E(self): if self.selectedM.get() =='Options...': Setup global TL TL = Tkinter.Toplevel(self) menu = Tkinter.Menu(TL) TL.config(menu=menu) filemenu = Tkinter.Menu(menu) menu.add_cascade(label="| Menu |", menu=filemenu) filemenu.add_command(label="Instruction Manual...", command=self.helpmenu) filemenu.add_command(label="About...", command=self.aboutmenu) filemenu.add_separator() filemenu.add_command(label="Exit Options", command=TL.destroy) filemenu.add_command(label="Exit", command=self.destroy) helpmenu = Tkinter.Menu(menu) menu.add_cascade(label="| Help |", menu=helpmenu) helpmenu.add_command(label="Instruction Manual...", command=self.helpmenu) helpmenu.add_separator() helpmenu.add_command(label="Quick Help...", command=self.helpmenu) Title TL.label5 = Tkinter.Label(TL,text="CPU Usage: Options",anchor="center",fg="black",bg="lightgreen",relief="ridge",borderwidth=5,font=('Arial', 18, 'bold')) TL.label5.pack(padx=15,ipadx=5) X Y scale TL.separator = Tkinter.Frame(TL,height=7, bd=1, relief='ridge', bg='grey95') TL.separator.pack(pady=5,padx=5) # TL.sclX = Tkinter.Scale(TL.separator, from_=0, to=1500, orient='horizontal', resolution=1, command=self.A) TL.sclX.grid(column=1,row=0,ipadx=27, sticky='w') TL.label1 = Tkinter.Label(TL.separator,text="X",anchor="s",fg="black",bg="grey95",font=('Arial', 8 ,'bold')) TL.label1.grid(column=0,row=0, pady=1, sticky='S') TL.sclY = Tkinter.Scale(TL.separator, from_=0, to=1500, resolution=1, command=self.A) TL.sclY.grid(column=2,row=1,rowspan=2,sticky='e', padx=4) TL.label3 = Tkinter.Label(TL.separator,text="Y",fg="black",bg="grey95",font=('Arial', 8 ,'bold')) TL.label3.grid(column=2,row=0, padx=10, sticky='e') TL.entryVariable2 = Tkinter.StringVar() TL.entry2 = Tkinter.Entry(TL.separator,textvariable=TL.entryVariable2, fg="grey15",bg="grey90",relief="sunken",insertbackground="black",borderwidth=5,font=('Arial', 10)) TL.entry2.grid(column=1,row=1,ipadx=20, pady=10,sticky='EW') TL.entry2.bind("<Return>", self.B) TL.label2 = Tkinter.Label(TL.separator,text="X:",fg="black",bg="grey95",font=('Arial', 8 ,'bold')) TL.label2.grid(column=0,row=1, ipadx=4, sticky='W') TL.entryVariable1 = Tkinter.StringVar() TL.entry1 = Tkinter.Entry(TL.separator,textvariable=TL.entryVariable1, fg="grey15",bg="grey90",relief="sunken",insertbackground="black",borderwidth=5,font=('Arial', 10)) TL.entry1.grid(column=1,row=2,sticky='EW') TL.entry1.bind("<Return>", self.B) TL.label4 = Tkinter.Label(TL.separator,text="Y:", anchor="center",fg="black",bg="grey95",font=('Arial', 8 ,'bold')) TL.label4.grid(column=0,row=2, ipadx=4, sticky='W') TL.label7 = Tkinter.Label(TL.separator,text="Text Colour:",fg="black",bg="grey95",font=('Arial', 8 ,'bold')) TL.label7.grid(column=1,row=3,stick="W",ipady=10) TL.selectedP = Tkinter.StringVar() TL.opt1 = Tkinter.OptionMenu(TL.separator, TL.selectedP,'Normal', 'White','Black', 'Blue', 'Steel Blue','Green','Light Green','Yellow','Orange' ,'Red',command=self.G) TL.opt1.config(fg="black",bg="grey90",activebackground="grey90",activeforeground="black", anchor="center",relief="raised",direction='right',font=('Arial', 10)) TL.opt1.grid(column=1,row=4,sticky='EW',padx=20,ipadx=20) TL.selectedP.set('Normal') TL.label7 = Tkinter.Label(TL.separator,text="Refresh Rate:",fg="black",bg="grey95",font=('Arial', 8 ,'bold')) TL.label7.grid(column=1,row=5,stick="W",ipady=10) TL.sclS = Tkinter.Scale(TL.separator, from_=10, to=2000, orient='horizontal', resolution=10, command=self.H) TL.sclS.grid(column=1,row=6,ipadx=27, sticky='w') TL.sclS.set(650) TL.entryVariableS = Tkinter.StringVar() TL.entryS = Tkinter.Entry(TL.separator,textvariable=TL.entryVariableS, fg="grey15",bg="grey90",relief="sunken",insertbackground="black",borderwidth=5,font=('Arial', 10)) TL.entryS.grid(column=1,row=7,ipadx=20, pady=10,sticky='EW') TL.entryS.bind("<Return>", self.I) TL.entryVariableS.set(650) # TL.resizable(False,False) TL.title('Options') geomPatt = re.compile(r"(\d+)?x?(\d+)?([+-])(\d+)([+-])(\d+)") s = self.wm_geometry() m = geomPatt.search(s) X = m.group(4) Y = m.group(6) TL.sclY.set(Y) TL.sclX.set(X) if self.selectedM.get() == 'Exit': self.destroy() if self.selectedM.get() == 'Bump': s = self.wm_geometry() geomPatt = re.compile(r"(\d+)?x?(\d+)?([+-])(\d+)([+-])(\d+)") m = geomPatt.search(s) X3 = m.group(4) Y3 = m.group(6) M = int(Y3) - 150 P = M + 150 while Y3 > M: sleep(0.0009) Y3 = int(Y3) - 1 self.update_idletasks() self.wm_geometry("+" + str(X3) + "+" + str(Y3)) sleep(2.00) while Y3 < P: sleep(0.0009) Y3 = int(Y3) + 1 self.update_idletasks() self.wm_geometry("+" + str(X3) + "+" + str(Y3)) if self.selectedM.get() == 'Hide': s = self.wm_geometry() geomPatt = re.compile(r"(\d+)?x?(\d+)?([+-])(\d+)([+-])(\d+)") m = geomPatt.search(s) X3 = m.group(4) Y3 = m.group(6) M = int(Y3) + 5000 self.update_idletasks() self.wm_geometry("+" + str(X3) + "+" + str(M)) TL1.wm_geometry("+0+190") def F (self): G = round(psutil.cpu_percent(), 1) G1 = str(G) + '%' self.labelVariable.set(G1) try: S2 = TL.entryVariableS.get() except ValueError, e: S2 = 650 except NameError: S2 = 650 self.after(int(S2), self.F) def G (self,event): if TL.selectedP.get() =='Normal': self.label.config( fg = 'lightgreen' ) TL1.button.config( fg = 'lightgreen',activeforeground='lightgreen') if TL.selectedP.get() =='Red': self.label.config( fg = 'red' ) TL1.button.config( fg = 'red',activeforeground='red') if TL.selectedP.get() =='Orange': self.label.config( fg = 'orange') TL1.button.config( fg = 'orange',activeforeground='orange') if TL.selectedP.get() =='Yellow': self.label.config( fg = 'yellow') TL1.button.config( fg = 'yellow',activeforeground='yellow') if TL.selectedP.get() =='Light Green': self.label.config( fg = 'lightgreen' ) TL1.button.config( fg = 'lightgreen',activeforeground='lightgreen') if TL.selectedP.get() =='Normal': self.label.config( fg = 'lightgreen' ) TL1.button.config( fg = 'lightgreen',activeforeground='lightgreen') if TL.selectedP.get() =='Steel Blue': self.label.config( fg = 'steelblue1' ) TL1.button.config( fg = 'steelblue1',activeforeground='steelblue1') if TL.selectedP.get() =='Blue': self.label.config( fg = 'blue') TL1.button.config( fg = 'blue',activeforeground='blue') if TL.selectedP.get() =='Green': self.label.config( fg = 'darkgreen' ) TL1.button.config( fg = 'darkgreen',activeforeground='darkgreen') if TL.selectedP.get() =='White': self.label.config( fg = 'white' ) TL1.button.config( fg = 'white',activeforeground='white') if TL.selectedP.get() =='Black': self.label.config( fg = 'black') TL1.button.config( fg = 'black',activeforeground='black') def H (self,event): TL.entryVariableS.set(TL.sclS.get()) S = TL.sclS.get() def I (self,event): S1 = TL.entryVariableS.get() TL.sclS.set(S1) TL.sclS.set(TL.sclS.get()) S1 = TL.entryVariableS.get() TL.sclS.set(S1) def J (self): s = self.wm_geometry() geomPatt = re.compile(r"(\d+)?x?(\d+)?([+-])(\d+)([+-])(\d+)") m = geomPatt.search(s) X3 = m.group(4) Y3 = m.group(6) M = int(Y3) - 5000 self.update_idletasks() self.wm_geometry("+" + str(X3) + "+" + str(M)) TL1.wm_geometry("+0+5000") Loop if name == "main": app = simpleapp_tk(None) app.mainloop()

    Read the article

  • Polled I/O on MIPS

    - by Krewie
    Hello , i'm currently implementing a calculator in MIPS which uses the polled I/O method for fetching information. I put a beq $v0, 120, exit # exit if input = ('x') on the main part of the code to tell that whenever something is fetched is equal to x, it should branch the exit function. The only problem is that my code works fine with the keyboard/display simulator on MARS but i get the interrupt exception 6 on SPIM. Why is this happening and how can i help it ? //Thx in advance

    Read the article

  • Java System.in issue

    - by theo
    `public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { if (sc.next().equals("exit")){ System.out.println("EXITING"); System.exit(0); } else { System.out.println("IM STILL WORKING ok?"); } } } }` So here is a piece of code i was writing the other day to try and figure sth out (doesn't really matter what). The result of executing this code is : eIM STILL WORKING ok? eIM STILL WORKING ok? exit IM STILL WORKING ok? exit EXITING Can somebody kindly explain why this has happened?

    Read the article

  • how to serialize / deserialize classes defined in .proto (protobuf)

    - by make
    Hi, Could someone please help me with serialization/deserialization classes defined in .proto (protobuf). here is an exp that I am trying to build: file.proto message Data{ required string x1 = 1; required uint32 x2 = 2; required float x3 = 3; } message DataExge { repeated Data data = 1; } client.cpp ... void serialize(const DataExge &data_snd){ try { ofstream ofs("DataExge"); data_snd.SerializeToOstream(&ofs); } catch(exception &e) { cerr << "serialize/exception: " << e.what() << endl; exit(1); } } void deserialize(DataExge &data_rec){ try { ifstream ifs("DataExge"); data_rec.ParseFromIstream(&ifs); } catch(exception& e) { cerr << "deserialize/exception: " << e.what() << endl; exit(1); } } int main(){ ... DataExge dataexge; Data *dat = dataexge.add_data(); char *y1 = "operation1"; uint32_t y2 = 123 ; float y3 = 3.14; // assigning data to send() dat->set_set_x1(y1); dat->set_set_x2(y2); dat->set_set_x3(y3); //sending data to the client serialize(dataexge); if (send(socket, &dataexge, sizeof(dataexge), 0) < 0) { cerr << "send() failed" ; exit(1); } //receiving data from the server deserialize(dataexge); if (recv(socket, &dataexge, sizeof(dataexge), 0) < 0) { cerr << "recv() failed"; exit(1); } //printing received data cout << dat->x1() << "\n"; cout << dat->x2() << "\n"; cout << dat->x3() << "\n"; ... } server.cpp ... void serialize(const DataExge &data_snd){ try { ofstream ofs("DataExge"); data_snd.SerializeToOstream(&ofs); } catch(exception &e) { cerr << "serialize/exception: " << e.what() << endl; exit(1); } } void deserialize(DataExge &data_rec){ try { ifstream ifs("DataExge"); data_rec.ParseFromIstream(&ifs); } catch(exception& e) { cerr << "deserialize/exception: " << e.what() << endl; exit(1); } } int main(){ ... DataExge dataexge; Data *dat = dataexge.add_data(); //receiving data from the client deserialize(dataexge); if (recv(socket, &dataexge, sizeof(dataexge), 0) < 0) { cerr << "recv() failed"; exit(1); } //printing received data cout << dat->x1() << "\n"; cout << dat->x2() << "\n"; cout << dat->x3() << "\n"; // assigning data to send() dat->set_set_x1("operation2"); dat->set_set_x2(dat->x2() + 1); dat->set_set_x3(dat->x3() + 1.1); //sending data to the client serialize(dataexge); //error// I am getting error at this line ... if (send(socket, &dataexge, sizeof(dataexge), 0) < 0) { cerr << "send() failed" ; exit(1); } ... } Thanks for your help and replies -

    Read the article

  • How to dispose of variables in windows close button

    - by cmrhema
    Hi, I have a windows forms application, where I have declared some static variables. On the click of exit button, I have disposed of some datatable which i have declared static. Many a times the user instead of clicking the exit button, will just exit the windows application by clicking the X button on the left corner top. What should be done to ensure that even if the user clicks the X button, everything is disposed of properly. Thanks Regards Hema

    Read the article

  • How to know if the client has terminated in sockets

    - by shadyabhi
    Suppose, I have a connected socket after writing this code.. if ((sd = accept(socket_d, (struct sockaddr *)&client_addr, &alen)) < 0) { perror("accept failed\n"); exit(1); } How can I know at the server side that client has exited. My whole program actually does the following.. Accepts a connection from client Starts a new thread that reads messages from that particular client and then broadcast this message to all the connected clients. If you want to see the whole code... In this whole code. I am also struggling with one more problem that whenever I kill a client with Ctrl+C, my server terminates abruptly.. It would be nice if anyone could suggest what the problem is.. #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <errno.h> #include <pthread.h> /*CONSTANTS*/ #define DEFAULT_PORT 10000 #define LISTEN_QUEUE_LIMIT 6 #define TOTAL_CLIENTS 10 #define CHAR_BUFFER 256 /*GLOBAL VARIABLE*/ int current_client = 0; int connected_clients[TOTAL_CLIENTS]; extern int errno; void *client_handler(void * socket_d); int main(int argc, char *argv[]) { struct sockaddr_in server_addr;/* structure to hold server's address*/ int socket_d; /* listening socket descriptor */ int port; /* protocol port number */ int option_value; /* needed for setsockopt */ pthread_t tid[TOTAL_CLIENTS]; port = (argc > 1)?atoi(argv[1]):DEFAULT_PORT; /* Socket Server address structure */ memset((char *)&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; /* set family to Internet */ server_addr.sin_addr.s_addr = INADDR_ANY; /* set the local IP address */ server_addr.sin_port = htons((u_short)port); /* Set port */ /* Create socket */ if ( (socket_d = socket(PF_INET, SOCK_STREAM, 0)) < 0) { fprintf(stderr, "socket creation failed\n"); exit(1); } /* Make listening socket's port reusable */ if (setsockopt(socket_d, SOL_SOCKET, SO_REUSEADDR, (char *)&option_value, sizeof(option_value)) < 0) { fprintf(stderr, "setsockopt failure\n"); exit(1); } /* Bind a local address to the socket */ if (bind(socket_d, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) { fprintf(stderr, "bind failed\n"); exit(1); } /* Specify size of request queue */ if (listen(socket_d, LISTEN_QUEUE_LIMIT) < 0) { fprintf(stderr, "listen failed\n"); exit(1); } memset(connected_clients,0,sizeof(int)*TOTAL_CLIENTS); for (;;) { struct sockaddr_in client_addr; /* structure to hold client's address*/ int alen = sizeof(client_addr); /* length of address */ int sd; /* connected socket descriptor */ if ((sd = accept(socket_d, (struct sockaddr *)&client_addr, &alen)) < 0) { perror("accept failed\n"); exit(1); } else printf("\n I got a connection from (%s , %d)\n",inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port)); if (pthread_create(&tid[current_client],NULL,(void *)client_handler,(void *)sd) != 0) { perror("pthread_create error"); continue; } connected_clients[current_client]=sd; current_client++; /*Incrementing Client number*/ } return 0; } void *client_handler(void *connected_socket) { int sd; sd = (int)connected_socket; for ( ; ; ) { ssize_t n; char buffer[CHAR_BUFFER]; for ( ; ; ) { if (n = read(sd, buffer, sizeof(char)*CHAR_BUFFER) == -1) { perror("Error reading from client"); pthread_exit(1); } int i=0; for (i=0;i<current_client;i++) { if (write(connected_clients[i],buffer,sizeof(char)*CHAR_BUFFER) == -1) perror("Error sending messages to a client while multicasting"); } } } } My client side is this (Maye be irrelevant while answering my question) #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <string.h> #include <stdlib.h> void error(char *msg) { perror(msg); exit(0); } void *listen_for_message(void * fd) { int sockfd = (int)fd; int n; char buffer[256]; bzero(buffer,256); printf("YOUR MESSAGE: "); fflush(stdout); while (1) { n = read(sockfd,buffer,256); if (n < 0) error("ERROR reading from socket"); if (n == 0) pthread_exit(1); printf("\nMESSAGE BROADCAST: %sYOUR MESSAGE: ",buffer); fflush(stdout); } } int main(int argc, char *argv[]) { int sockfd, portno, n; struct sockaddr_in serv_addr; struct hostent *server; pthread_t read_message; char buffer[256]; if (argc < 3) { fprintf(stderr,"usage %s hostname port\n", argv[0]); exit(0); } portno = atoi(argv[2]); sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) error("ERROR opening socket"); server = gethostbyname(argv[1]); if (server == NULL) { fprintf(stderr,"ERROR, no such host\n"); exit(0); } bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(portno); if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0) error("ERROR connecting"); bzero(buffer,256); if (pthread_create(&read_message,NULL,(void *)listen_for_message,(void *)sockfd) !=0 ) { perror("error creating thread"); } while (1) { fgets(buffer,255,stdin); n = write(sockfd,buffer,256); if (n < 0) error("ERROR writing to socket"); bzero(buffer,256); } return 0; }

    Read the article

  • Speech Recognition Server Does Not Stay Open

    - by Waffle
    I am trying to create a simple program that loops for user speech input using com.apple.speech.recognitionserver. My code thus far is as follows: set user_response to "start" repeat while user_response is not equal to "Exit" tell application id "com.apple.speech.recognitionserver" set user_response to listen for {"Time", "Weather", "Exit"} with prompt "Good Morning" end tell if user_response = "Time" then set curr_time to time string of (the current date) set curr_day to weekday of (the current date) say "It is" say curr_time say "on" say curr_day say "day" else if user_response = "Weather" then say "It is hot outside. What do you expect?" end if end repeat say "Have a good day" If the above is run on my system it says good morning and it then pops up with the speech input system and waits for either Time, Weather, or Exit. They all do what they say they are going to do, but instead of looping if I say Time and Weather and asking again until I say exit the speechserver times out and never pops up again. Is there a way of either keeping that application open until the program ends or is applescript not capable of looping for user speech input?

    Read the article

  • Why servlet halt a moment in concurrent request.

    - by Hlex
    I use Axis for webservice service. when more than 8 concurrent , there are some request halt randomly for about 30 seconds. I debug by log in every line and found from my code: public class foo{ void bar(){ a(); log.debug('exit from a'); } void a(){ log.debug('exit a'); } the time between "exit a" and "exit from a" are delay about 30 second. This is no reason. I try to increase web container thread pool , heap but didn't help ============== Enviroment websphere 6.1 Spring 2.5 , Hibernate 3 ,Axis 1.6.5 Min heap to 768 Max heap to 1024 Thread pool defult max to 300 Thread pool web container max to 500 ===============

    Read the article

  • image not displaying in midlet

    - by user316843
    Hello all,am new here. i have a slight problem; PLease look at the following code and tell me if am doing something wrong because the image is not displaying. i have made it really small so it should fit but its not displaying. i have images displaying in other screens but this main midlet would not. Here is the code: import java.io.IOException; import javax.microedition.midlet.*; import javax.microedition.lcdui.*; /** * @author jay */ public class WShop extends MIDlet implements CommandListener { /* Declare display variables*/ private Form mainForm; private Display display; private Command OK,Exit,wView, mView, myView; /* */ Categories categories = new Categories(this); Image image; public WShop() { /* initialize Screen and Command buttons that will be used when the application starts in the class constructor*/ mainForm = new Form("Wind Shopper"); OK = new Command("OK", Command.OK, 2); Exit = new Command("Exit", Command.EXIT, 0); wview= new Command("wview", Command.OK, 0); mview= new Command("mview", Command.OK, 0); try { /* retrieving the main image of the application*/ image = Image.createImage("/main.png"); } catch (IOException ex) { ex.printStackTrace(); } mainForm.addCommand(OK); mainForm.addCommand(Exit); mainForm.addCommand(wView); mainForm.addCommand(mView); mainForm.setCommandListener(this); } public void startApp() { /* checks to see if the display is currently empty and then sets it to the current screen */ if (display == null) { display = Display.getDisplay(this); } display.setCurrent(mainForm); } /* paused state of the application*/ public void pauseApp() { } /* Destroy Midlet state*/ public void destroyApp(boolean unconditional) { } Thanks in advance.

    Read the article

  • Reading a child process's /proc/pid/mem file from the parent

    - by Amittai Aviram
    In the program below, I am trying to cause the following to happen: Process A assigns a value to a stack variable a. Process A (parent) creates process B (child) with PID child_pid. Process B calls function func1, passing a pointer to a. Process B changes the value of variable a through the pointer. Process B opens its /proc/self/mem file, seeks to the page containing a, and prints the new value of a. Process A (at the same time) opens /proc/child_pid/mem, seeks to the right page, and prints the new value of a. The problem is that, in step 6, the parent only sees the old value of a in /proc/child_pid/mem, while the child can indeed see the new value in its /proc/self/mem. Why is this the case? Is there any way that I can get the parent to to see the child's changes to its address space through the /proc filesystem? #include <fcntl.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <unistd.h> #define PAGE_SIZE 0x1000 #define LOG_PAGE_SIZE 0xc #define PAGE_ROUND_DOWN(v) ((v) & (~(PAGE_SIZE - 1))) #define PAGE_ROUND_UP(v) (((v) + PAGE_SIZE - 1) & (~(PAGE_SIZE - 1))) #define OFFSET_IN_PAGE(v) ((v) & (PAGE_SIZE - 1)) # if defined ARCH && ARCH == 32 #define BP "ebp" #define SP "esp" #else #define BP "rbp" #define SP "rsp" #endif typedef struct arg_t { int a; } arg_t; void func1(void * data) { arg_t * arg_ptr = (arg_t *)data; printf("func1: old value: %d\n", arg_ptr->a); arg_ptr->a = 53; printf("func1: address: %p\n", &arg_ptr->a); printf("func1: new value: %d\n", arg_ptr->a); } void expore_proc_mem(void (*fn)(void *), void * data) { off_t frame_pointer, stack_start; char buffer[PAGE_SIZE]; const char * path = "/proc/self/mem"; int child_pid, status; int parent_to_child[2]; int child_to_parent[2]; arg_t * arg_ptr; off_t child_offset; asm volatile ("mov %%"BP", %0" : "=m" (frame_pointer)); stack_start = PAGE_ROUND_DOWN(frame_pointer); printf("Stack_start: %lx\n", (unsigned long)stack_start); arg_ptr = (arg_t *)data; child_offset = OFFSET_IN_PAGE((off_t)&arg_ptr->a); printf("Address of arg_ptr->a: %p\n", &arg_ptr->a); pipe(parent_to_child); pipe(child_to_parent); bool msg; int child_mem_fd; char child_path[0x20]; child_pid = fork(); if (child_pid == -1) { perror("fork"); exit(EXIT_FAILURE); } if (!child_pid) { close(child_to_parent[0]); close(parent_to_child[1]); printf("CHILD (pid %d, parent pid %d).\n", getpid(), getppid()); fn(data); msg = true; write(child_to_parent[1], &msg, 1); child_mem_fd = open("/proc/self/mem", O_RDONLY); if (child_mem_fd == -1) { perror("open (child)"); exit(EXIT_FAILURE); } printf("CHILD: child_mem_fd: %d\n", child_mem_fd); if (lseek(child_mem_fd, stack_start, SEEK_SET) == (off_t)-1) { perror("lseek"); exit(EXIT_FAILURE); } if (read(child_mem_fd, buffer, sizeof(buffer)) != sizeof(buffer)) { perror("read"); exit(EXIT_FAILURE); } printf("CHILD: new value %d\n", *(int *)(buffer + child_offset)); read(parent_to_child[0], &msg, 1); exit(EXIT_SUCCESS); } else { printf("PARENT (pid %d, child pid %d)\n", getpid(), child_pid); printf("PARENT: child_offset: %lx\n", child_offset); read(child_to_parent[0], &msg, 1); printf("PARENT: message from child: %d\n", msg); snprintf(child_path, 0x20, "/proc/%d/mem", child_pid); printf("PARENT: child_path: %s\n", child_path); child_mem_fd = open(path, O_RDONLY); if (child_mem_fd == -1) { perror("open (child)"); exit(EXIT_FAILURE); } printf("PARENT: child_mem_fd: %d\n", child_mem_fd); if (lseek(child_mem_fd, stack_start, SEEK_SET) == (off_t)-1) { perror("lseek"); exit(EXIT_FAILURE); } if (read(child_mem_fd, buffer, sizeof(buffer)) != sizeof(buffer)) { perror("read"); exit(EXIT_FAILURE); } printf("PARENT: new value %d\n", *(int *)(buffer + child_offset)); close(child_mem_fd); printf("ENDING CHILD PROCESS.\n"); write(parent_to_child[1], &msg, 1); if (waitpid(child_pid, &status, 0) == -1) { perror("waitpid"); exit(EXIT_FAILURE); } } } int main(void) { arg_t arg; arg.a = 42; printf("In main: address of arg.a: %p\n", &arg.a); explore_proc_mem(&func1, &arg.a); return EXIT_SUCCESS; } This program produces the output below. Notice that the value of a (boldfaced) differs between parent's and child's reading of the /proc/child_pid/mem file. In main: address of arg.a: 0x7ffffe1964f0 Stack_start: 7ffffe196000 Address of arg_ptr-a: 0x7ffffe1964f0 PARENT (pid 20376, child pid 20377) PARENT: child_offset: 4f0 CHILD (pid 20377, parent pid 20376). func1: old value: 42 func1: address: 0x7ffffe1964f0 func1: new value: 53 PARENT: message from child: 1 CHILD: child_mem_fd: 4 PARENT: child_path: /proc/20377/mem CHILD: new value 53 PARENT: child_mem_fd: 7 PARENT: new value 42 ENDING CHILD PROCESS.

    Read the article

  • error in midlet while implementing command..

    - by garima
    hi I have imported import com.sun.lwuit.Command; import javax.microedition.midlet.; import javax.microedition.lcdui.; in my code but still the following errors are coming... exitCommand = new Command("Exit", Command.EXIT, 2); //line 1 textbox.addCommand(exitCommand); //line 2 Command.EXIT cannot be resolved.. The method addCommand(Command) in the type Displayable is not applicable for the arguments (Command)

    Read the article

  • Apply a Quartz filter while saving PDF under Mac OS X 10.6.3

    - by olpa
    Using Mac OS X API, I'm trying to save a PDF file with a Quartz filter applied, just like it is possible from the "Save As" dialog in the Preview application. So far I've written the following code (using Python and pyObjC, but it isn't important for me): -- filter-pdf.py: begin from Foundation import * from Quartz import * import objc page_rect = CGRectMake (0, 0, 612, 792) fdict = NSDictionary.dictionaryWithContentsOfFile_("/System/Library/Filters/Blue \ Tone.qfilter") in_pdf = CGPDFDocumentCreateWithProvider(CGDataProviderCreateWithFilename ("test .pdf")) url = CFURLCreateWithFileSystemPath(None, "test_out.pdf", kCFURLPOSIXPathStyle, False) c = CGPDFContextCreateWithURL(url, page_rect, fdict) np = CGPDFDocumentGetNumberOfPages(in_pdf) for ip in range (1, np+1): page = CGPDFDocumentGetPage(in_pdf, ip) r = CGPDFPageGetBoxRect(page, kCGPDFMediaBox) CGContextBeginPage(c, r) CGContextDrawPDFPage(c, page) CGContextEndPage(c) -- filter-pdf.py: end Unfortunalte, the filter "Blue Tone" isn't applied, the output PDF looks exactly as the input PDF. Question: what I missed? How to apply a filter? Well, the documentation doesn't promise that such way of creating and using "fdict" should cause that the filter is applied. But I just rewritten (as far as I can) sample code /Developer/Examples/Quartz/Python/filter-pdf.py, which was distributed with older versions of Mac (meanwhile, this code doesn't work too): ----- filter-pdf-old.py: begin from CoreGraphics import * import sys, os, math, getopt, string def usage (): print ''' usage: python filter-pdf.py FILTER INPUT-PDF OUTPUT-PDF Apply a ColorSync Filter to a PDF document. ''' def main (): page_rect = CGRectMake (0, 0, 612, 792) try: opts,args = getopt.getopt (sys.argv[1:], '', []) except getopt.GetoptError: usage () sys.exit (1) if len (args) != 3: usage () sys.exit (1) filter = CGContextFilterCreateDictionary (args[0]) if not filter: print 'Unable to create context filter' sys.exit (1) pdf = CGPDFDocumentCreateWithProvider (CGDataProviderCreateWithFilename (args[1])) if not pdf: print 'Unable to open input file' sys.exit (1) c = CGPDFContextCreateWithFilename (args[2], page_rect, filter) if not c: print 'Unable to create output context' sys.exit (1) for p in range (1, pdf.getNumberOfPages () + 1): #r = pdf.getMediaBox (p) r = pdf.getPage(p).getBoxRect(p) c.beginPage (r) c.drawPDFDocument (r, pdf, p) c.endPage () c.finish () if __name__ == '__main__': main () ----- filter-pdf-old.py: end

    Read the article

  • How to code a time delay between plotting points in JFreeCharts?

    - by Javajava
    Is there a way to animate the plotting process of an xy-line chart using JFreeCharts? I want to be able to watch the program draw each line segment and connect them. For example, if I paste this into the TextArea, "gtgtaaacaatatatggcg," I want to watch it graph each line segment one by one. Thanks in advance! :) My code is below: import java.util.Scanner; import java.applet.Applet; import java.awt.; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import org.jfree.chart.; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.xy.*; public class RandomWalkComplete extends Applet implements ActionListener { Panel panel; TextArea textarea, outputArea; Button move,exit; String thetext; Scanner reader = new Scanner(System.in); String thetext2; Label instructions; int x,y; public void init() { setSize(500,250); //set size of applet instructions=new Label("Paste the gene sequences in the " + "text field and press the graph button."); add(instructions); panel = new Panel(); add(panel); setVisible(true); textarea= new TextArea(10,20); add(textarea); move=new Button("Graph"); move.addActionListener(this); add(move); exit=new Button("Exit"); exit.addActionListener(this); add(exit); } public void actionPerformed(ActionEvent e) { XYSeries series = new XYSeries("DNA Walk",false,true); x= 0; y = 0; series.add(x,y); if(e.getSource() == move) { thetext=textarea.getText(); //the text is the DNA bases pasted thetext=thetext.replaceAll(" ",""); //removes spaces thetext2 = ""; for(int i=0; i<thetext.length(); i++) { char a = thetext.charAt(i); switch (a) { case 'A': case 'a'://moves right x+=1; y+=0; series.add(x,y); break; case 'C': case 'c': //moves up x+=0; y+=1; series.add(x,y); break; case 'G': case 'g': //move left x-=1; y+=0; series.add(x,y); break; case 'T': case 't'://move down x+=0; y-=1; series.add(x,y); break; default: // series.add(0,0); break; } } XYDataset xyDataset = new XYSeriesCollection(series); JFreeChart chart = ChartFactory.createXYLineChart ("DNA Random Walk", "", "", xyDataset, PlotOrientation.VERTICAL, true, true, false); ChartFrame frame1=new ChartFrame("DNA Random Walk",chart); frame1.setVisible(true); frame1.setSize(300,300); } if(e.getSource()==exit) {System.exit(0);} } public void stop(){} }

    Read the article

  • Find directories not containing a specific directory

    - by Morgan ARR Allen
    Been searching around for a bit and cannot find a solution for this one. I guess I'm looking for a leaf-directory by name. In this example I'd like to get a list of directories call 'modules' that do NOT have a subdirectory called module. modules/package1/modules/spackage1 modules/package1/modules/spackage2 modules/package1/modules/spackage3/modules modules/package1/modules/spackage3/modules/spackage1 modules/package2/modules/ The list I desire would contain modules/package1/modules/spackage3/modules/ modules/package2/modules/ All the directories named module that do not have a subdirectory called module I started with trying something this with no luck find . -name modules \! -exec sh -c 'find -name modules' \; -exec works on exit code, okay lets pass the count as exit code find . -name modules -exec sh -c 'exit $(find {} -name modules|grep -n ""|tail -n1|cut -d: -f1)' \; This should take the count of each subdirectory called modules and exit with it. No such love.

    Read the article

  • C socket programming: select() is returning 0 despite messages sent from server

    - by Fantastic Fourier
    Hey all, I'm using select() to recv() messages from server, using TCP/IP. When I send() messages from the server, it returns a reasonable number of bytes, saying it's sent successful. And it does get to the client successfully when I use while loop to just recv(). Everything is fine and dandy. while(1) recv() // obviously pseudocode However, when I try to use select(), select() returns 0 from timeout (which is set to 1 second) and for the life of me I cannot figure out why it doesn't see the messages sent from the server. I should also mention that when the server disconnects, select() doesn't see that either, where as if I were to use recv(), it would return 0 to indicate that the connection using the socket has been closed. Any inputs or thoughts are deeply appreciated. #include <arpa/inet.h> #include <errno.h> #include <fcntl.h> #include <netdb.h> #include <netinet/in.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <sys/select.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/types.h> #include <time.h> #include <unistd.h> #define SERVER_PORT 10000 #define MAX_CONNECTION 20 #define MAX_MSG 50 struct client { char c_name[MAX_MSG]; char g_name[MAX_MSG]; int csock; int host; // 0 = not host of a multicast group struct sockaddr_in client_address; struct client * next_host; struct client * next_client; }; struct fd_info { char c_name[MAX_MSG]; int socks_inuse[MAX_CONNECTION]; int sock_fd, max_fd; int exit; struct client * c_sys; struct sockaddr_in c_address[MAX_CONNECTION]; struct sockaddr_in server_address; struct sockaddr_in client_address; fd_set read_set; }; struct message { char c_name[MAX_MSG]; char g_name[MAX_MSG]; char _command[3][MAX_MSG]; char _payload[MAX_MSG]; struct sockaddr_in client_address; struct client peer; }; int main(int argc, char * argv[]) { char * host; char * temp; int i, sockfd; int msg_len, rv, ready; int connection, management, socketread; int sockfds[MAX_CONNECTION]; // for three threads that handle new connections, user inputs and select() for sockets pthread_t connection_handler, manager, socket_reader; struct sockaddr_in server_address, client_address; struct hostent * hserver, cserver; struct timeval timeout; struct message msg; struct fd_info info; info.exit = 0; // exit information: if exit = 1, threads quit info.c_sys = NULL; // looking up from the host database if (argc == 3) { host = argv[1]; // server address strncpy(info.c_name, argv[2], strlen(argv[2])); // client name } else { printf("plz read the manual, kthxbai\n"); exit(1); } printf("host is %s and hp is %p\n", host, hserver); hserver = gethostbyname(host); if (hserver) { printf("host found: %s\n", hserver->h_name ); } else { printf("host not found\n"); exit(1); } // setting up address and port structure information on serverside bzero((char * ) &server_address, sizeof(server_address)); // copy zeroes into string server_address.sin_family = AF_INET; memcpy(&server_address.sin_addr, hserver->h_addr, hserver->h_length); server_address.sin_port = htons(SERVER_PORT); bzero((char * ) &client_address, sizeof(client_address)); // copy zeroes into string client_address.sin_family = AF_INET; client_address.sin_addr.s_addr = htonl(INADDR_ANY); client_address.sin_port = htons(SERVER_PORT); // opening up socket sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) exit(1); else { printf("socket is opened: %i \n", sockfd); info.sock_fd = sockfd; } // sets up time out option for the bound socket timeout.tv_sec = 1; // seconds timeout.tv_usec = 0; // micro seconds ( 0.5 seconds) setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(struct timeval)); // binding socket to a port rv = bind(sockfd, (struct sockaddr *) &client_address, sizeof(client_address)); if (rv < 0) { printf("MAIN: ERROR bind() %i: %s\n", errno, strerror(errno)); exit(1); } else printf("socket is bound\n"); printf("MAIN: %li \n", client_address.sin_addr.s_addr); // connecting rv = connect(sockfd, (struct sockaddr *) &server_address, sizeof(server_address)); info.server_address = server_address; info.client_address = client_address; info.sock_fd = sockfd; info.max_fd = sockfd; printf("rv = %i\n", rv); if (rv < 0) { printf("MAIN: ERROR connect() %i: %s\n", errno, strerror(errno)); exit(1); } else printf("connected\n"); fd_set readset; FD_ZERO(&readset); FD_ZERO(&info.read_set); FD_SET(info.sock_fd, &info.read_set); while(1) { readset = info.read_set; printf("MAIN: %i \n", readset); ready = select((info.max_fd)+1, &readset, NULL, NULL, &timeout); if(ready == -1) { sleep(2); printf("TEST: MAIN: ready = -1. %s \n", strerror(errno)); } else if (ready == 0) { sleep(2); printf("TEST: MAIN: ready = 0. %s \n", strerror(errno)); } else if (ready > 0) { printf("TEST: MAIN: ready = %i. %s at socket %i \n", ready, strerror(errno), i); for(i = 0; i < ((info.max_fd)+1); i++) { if(FD_ISSET(i, &readset)) { rv = recv(sockfd, &msg, 500, 0); if(rv < 0) continue; else if(rv > 0) printf("MAIN: TEST: %s %s \n", msg._command[0], msg._payload); else if (rv == 0) { sleep(3); printf("MAIN: TEST: SOCKET CLOSEDDDDDD \n"); } FD_CLR(i, &readset); } } } info.read_set = readset; } // close connection close(sockfd); printf("socket closed. BYE! \n"); return(0); }

    Read the article

  • C# Simple IF OR question

    - by Jamie
    Hi all, Sorry to ask this as I thought I knew the answer, I want to exit the program if userName is greater than 4 characters or userName is not an account called student. However this even if the userName is only 3 characters and is not student I'm still hitting Application.Exit. What am I doing wrong? if (userName.Length > 4 | userName != "student") { Application.Exit(); } Shame on me :-(

    Read the article

  • Command Not working in separate thread in J2me.

    - by RishiPatel
    I am creating a bluetooth application. I created a simple midlet with a exit command and i create a thread for finding the service and discovering the device. While doing so it displays a animated screen on which i added the parent commandListener for exit command. After successful connection both user is represented with greetings(Current screen calls the parent Display method setCurrent for displaying itself). This screen also have CommandListener set to the parent. Now i want to add few more commands. I Implemented the CommandLIstener Interface in this class, added few commands but the commands are not working. I dont whats wen wrong. I am giving u Code snippets to fully describle my issue : - package name Imports here public class MyMidlet extends MIDlet implements CommandListener { public CommandListener theListener; public Display theDisplay; public Command exitCommand; public MyMidlet() { // Retrieve the display for this MIDlet //Create the initial screen } public void startApp() throws MIDletStateChangeException { } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void commandAction(Command c, Displayable d) { // Determine if the exit command was selected if (c == exitCommand) { //End application here notifyDestroyed(); } else { //Start the new thread here } } } Now here is the code for the class which is invoked by the above midlet in a separate thread; package here; imports here public class MyService implements Runnable, CommandListener { private MyMidlet parent; private StreamConnection conn; private OutputStream output; private InputStream input; public Command sendCommand; private TextField messageToSend Form form; public BChatService(boolean isServer, BChatMidlet parent) { //some stuff here this.parent = parent; } public void run() { //functino for showing animation here try { input = conn.openInputStream(); output = conn.openOutputStream(); } catch (IOException e) { displayError("IO Error", "An error occurred while opening " + "the input and output streams" + "(IOException: " + e.getMessage() + ")"); try { conn.close(); } catch (Exception ex) { } return; } // Create the Form here when service is discoverd and greets the users Command sendCommand = new Command("Send", Command.ITEM, 2); exitCommand = new Command("Exit", Command.EXIT, 1); form.addCommand(exitCommand); form.addCommand(sendCommand); parent.theDisplay.setCurrent(form); form.setCommandListener(this); public void commandAction(Command c, Displayable d) { if (c == exitCommand) { // End the game parent.destroyApp(true); parent.notifyDestroyed(); } if(c == sendCommand) { form.append("SOme text here"); } } } When i select the Send command, the string doesnt append in form neither exit command works. What can be the possible cause for it?? I need to implement this functionality...Is there any other way to achieve this??

    Read the article

  • Form Closing help

    - by Michael Quiles
    How can I call the button1_Click event in the form closing event so I don't have to copy and paste the code from button1_Click? public void button1_Click(object sender, EventArgs e) { //Yes or no message box to exit the application DialogResult Response; Response = MessageBox.Show("Are you sure you want to Exit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (Response == DialogResult.Yes) // Exits the application Application.Exit(); } public void xGameThemeComboBox_SelectedIndexChanged(object sender, EventArgs e) { string folder = Application.StartupPath; string theme = (string)xGameThemeComboBox.Items[xGameThemeComboBox.SelectedIndex]; string path = System.IO.Path.Combine(folder, theme + ".jpg"); Image newImage = new Bitmap(path); if (this.BackgroundImage != null) this.BackgroundImage.Dispose(); { this.BackgroundImage = newImage; } } private void xGameForm_FormClosing(object sender, FormClosingEventArgs e) { // call button1_Click here }

    Read the article

  • Prolog Cut Not Working

    - by user2295607
    Im having a problem with Prolog since cut is not doing what (i believe) its supposed to do: % line-column handlers checkVallEle(_, _, 6, _):- write('FAIL'), !, fail. checkVallEle(TABULEIRO, VALUE, LINE, COLUMN):- COLUMN>5, NL is LINE+1, checkVallEle(TABULEIRO, VALUE, NL, 0). % if this fails, it goes to the next checkVallEle(TABULEIRO, VALUE, LINE, COLUMN):- (checkHorizontal(TABULEIRO, VALUE, LINE, COLUMN, 0), write('HORIZONTAL '); checkVertical(TABULEIRO, VALUE, LINE, COLUMN, 0), write('VERTICAL'); checkDiagonalRight(TABULEIRO, VALUE, LINE, COLUMN, 0), write('DIAGONALRIGHT'); checkDiagonalLeft(TABULEIRO, VALUE, LINE, COLUMN, 0), write('DIAGONALLEFT')), write('WIN'). % goes to the next if above fails checkVallEle(TABULEIRO, VALUE, LINE, COLUMN):- NC is COLUMN+1, checkVallEle(TABULEIRO, VALUE, LINE, NC). What I wish to do is that if the code ever reaches the first statement, that is, if the line is ever 6, it fails (since it went out of range), without checking for more possibilities. But what happens is, when it reaches the first statement, it keeps going to the below statements and ignores the cut symbol, and I dont see why. I just want the statement to fail when it reaches the first line. I also made an experience... run(6):-write('done'), !, fail. run(X):-X1 is X+1, run(X1). And this is what i get from tracing: | ?- run(0). 1 1 Call: run(0) ? 2 2 Call: _1079 is 0+1 ? 2 2 Exit: 1 is 0+1 ? 3 2 Call: run(1) ? 4 3 Call: _3009 is 1+1 ? 4 3 Exit: 2 is 1+1 ? 5 3 Call: run(2) ? 6 4 Call: _4939 is 2+1 ? 6 4 Exit: 3 is 2+1 ? 7 4 Call: run(3) ? 8 5 Call: _6869 is 3+1 ? 8 5 Exit: 4 is 3+1 ? 9 5 Call: run(4) ? 10 6 Call: _8799 is 4+1 ? 10 6 Exit: 5 is 4+1 ? 11 6 Call: run(5) ? 12 7 Call: _10729 is 5+1 ? 12 7 Exit: 6 is 5+1 ? 13 7 Call: run(6) ? 14 8 Call: write(done) ? done 14 8 Exit: write(done) ? 13 7 Fail: run(6) ? 11 6 Fail: run(5) ? 9 5 Fail: run(4) ? 7 4 Fail: run(3) ? 5 3 Fail: run(2) ? 3 2 Fail: run(1) ? 1 1 Fail: run(0) ? no What are all those Fails after the write? is it still backtracing to previous answers? Is this behaviour the reason why cut is failing in my first code? Please enlighten me.

    Read the article

< Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >