text
stringlengths
8
267k
meta
dict
Q: Replace strings only outside of quotes using RegEx I have a string like: varA*varB%+Length('10%') I want to replace all the "%" characters not within single quotes with "/100" to end up with varA*varB/100+Length('10%') Methinks this is a job for a RegEx? A: non regex solution and not that dirty either ;) string a = "varA*varB%+Length('10%')"; string[] b = a.Split('\''); string c = string.Empty; int i = 0; foreach (string sbs in b) { c += i%2==0?sbs.Replace("%","/100"):"'" + sbs + "'";//for the every odd value of i "%" is within single quotes i++; } A: A slightly more efficient solution then the accepted answer. string a = "varA*varB%+Length('10%')"; string[] parts = a.Split('\''); for (int i = 0; i < parts.Length; i = i + 2) { parts[i] = _parts[i].Replace("%","/100"); } a = string.Join("'", parts); A: Try the one below. You have to use group and back reference in regex. I've tried it in Ultraedit with Perl regex syntax. It worked well. %([^']) --> /100\1 This regex means: find a % which is not followed by ', like %a will be matched. Then replace % with /100 and the one character which follows %. In this case, it is a. string str = "varA*varB%+Length('10%')"; string output=Regex.Replace(str, "%([^'])", @"/100$1"); string str2 = "varA*varB%+Length('10%')+varA*varB%+Length('10%')+bob%"; string output2 = Regex.Replace(str2, "%([^']|$)", @"/100$1");
{ "language": "en", "url": "https://stackoverflow.com/questions/7529827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Need to add textboxes to gridview cell on Edit select I could really use some help on this. I have been searching for a solution on the web but haven't been able to find much help. I need to add textboxes to a gridview edit cell, based on the number of rows of text in one of the cells. I have coded the capture of the number of textboxes I need to add. But I am not sure which Gridview event to add the code, when going into edit mode, to run the loop that will insert additional Textboxes in a specific column of the row selected to edit. The user sees colA that has text with line vbCRLF's embedded say: "This is sample text." "Line2" "Line3" My code reads three Carriage Return, Line feeds. So when the user goes into Edit mode I want to provide one text box for each line or more accurately, add two more as one will already exist. Thanks for any possible help on this. Regards, UPDATE: Here is the solution...... Private Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound If (e.Row.RowState And DataControlRowState.Edit) > 0 Then Dim ph As PlaceHolder = DirectCast(e.Row.FindControl("PlaceHolder1"), PlaceHolder) For I = 1 To BoxesNeeded Dim txtB As New TextBox txtB.ID = "txtBEdit" & I.ToString("D2") ph.Controls.Add(txtB) Dim litCtrl As New Literal litCtrl.ID = "litCtrl" & I.ToString("D2") litCtrl.Text = "<br />" ph.Controls.Add(litCtrl) Next I End If End Sub A: Here is the solution.... Private Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound If (e.Row.RowState And DataControlRowState.Edit) > 0 Then Dim ph As PlaceHolder = DirectCast(e.Row.FindControl("PlaceHolder1"), PlaceHolder) For I = 1 To BoxesNeeded Dim txtB As New TextBox txtB.ID = "txtBEdit" & I.ToString("D2") ph.Controls.Add(txtB) Dim litCtrl As New Literal litCtrl.ID = "litCtrl" & I.ToString("D2") litCtrl.Text = "<br />" ph.Controls.Add(litCtrl) Next I End If thanks,
{ "language": "en", "url": "https://stackoverflow.com/questions/7529833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: want to remove textview on top of screen How to remove textview right under status bar?. Its used to display app name by default. Even I delete main.xml, it does not work. I want move up widgets after removing textview. Thanks A: The textview you are talking about is knowing as Title bar of the application, which is mostly used to display title of current activity. Programmatically: //Remove title bar this.requestWindowFeature(Window.FEATURE_NO_TITLE); //Remove status bar this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); Design time: just make changes inside the AndroidManifest.xml file <activity android:name=".MainActivity" android:label="@string/app_name" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"> A: You want to remove the title bar of your app. Add this to your manifest file in application tag: android:theme="@android:style/Theme.NoTitleBar"
{ "language": "en", "url": "https://stackoverflow.com/questions/7529845", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dimension error in MATLAB's Neural Network Toolbox (NNtool) target matrix I am exploring MATLAB's Neural Network Toolbox (NNtool), and I am running into a problem of having incompatible dimensions of target matrix. The exact error message is: com.mathworks.jmi.MatlabException: Insufficient number of outputs from right hand side of equal sign to satisfy assignment. Let me explain in detail. I have an image which has some elliptical image in it, and I want to estimate the eliiptical parameters using a neural network, for that purpose, I have training data with all the target values. So, I am giving image as an input (I first read the image, convert it into mat2gray() format, and then import it in NNtool), and then I set the target matrix (my target matrix contains two values, since my neural network will be outputing two values, I have tried formatting the output in both ways, [0.5 0.9] and also [0.5; 0.9], but still I am getting the same error. I have also tried by keeping the number of columns the same for the input and target matrix. I made my input matrix as [2304,1] (I have a 48*48 image, that is equal to 2304) and my target matrix is [2,1] dimensions, but again, the same error occurs. While searching, I read that this is some sort of insufficient memory error. I am not sure if that is correct or not. Is that the case? For this neural network, I have to train 40,000 images. Each image is 48*48 dimensions. How can I input these many images into NNtool? A: From http://www.mathworks.ch/support/solutions/en/data/1-BBJCDC/index.html This enhancement has been incorporated in Release 2010b (R2010b). For previous product releases, read below for any possible workarounds: The error message: Error in ==> nntool at 681 [errmsg,errid] = me.message; is due to an out of memory error that happened earlier during the call to TRAIN in a TRY CATCH block. The ability to show the standard out of memory error message is not available in NNTOOL in Neural Network Toolbox 6.0.3 (R2009b). As a workaround reduce the huge number of inputs, since they are generating huge internal temporary matrices when calculating the training steps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .NET Logging WebService I work on some ASP.NET projects in collaboration with other developpers and I'm thinking about building a homemade logging solution. But before starting anything I would like to know if something similar to what I'm intended to code already exists. I'm looking for a tool, framework or whatever, that can be used to create a logging webservice. The service will be reachable by all our websites. It offers a set of methods to send logging information to the service which will store them in a database. We can imagine a method named "Trace(String message, TraceLevel level)" where the first argument can be an XML string containing a set of structured useful information (error, debug or access). One interesting feature will be that people can subscribe to a set of logs. For example, if I'm working on a "AnotherStackOverlow.com" project and I want to receive error logs, I can easily subscribe to the system choosing the corresponding TraceLevel. Has anyone already used a system like this? I'm also interested in general comments about security issues, coding issues, design problems and so on. Thanks A: In my opinion, doing logging through a web service is a very bad idea. You are relying on a connection between machines that may or may not be there which is going to lead to lost data. I would take a look at Elmah which is a fairly easy ASP.NET logging tool to use. You can have Elmah do the logging for you. You can then write a separate application to aggregate all of the log data (which is pretty trivial if you configure Elmah to log to a database) so that it can be viewed from a single location.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: kqoauth including I have downloaded kqoauth. I had a really hard time to include it in my project. Finally, I used its .dll and added it using LIBS += -itsDLL. It was working great on the simulator. However, when I try to deploy for the symbian, building fails and the error is: warning: Missing dependency detected: C:/QtSDK/Symbian/SDKs/Symbian3Qt473/epoc32/release/armv5/lib/kqoauthd0.dso My problem is that there is no trace of such .dso file!? What is this? Extra error details: :-1: error: Recipe linkandpostlink failed with exit code 1. :-1: Running command: C:/QtSDK/Symbian/SDKs/Symbian3Qt473/epoc32/tools/checklib.exe stdc++ --elf C:/QtSDK/Symbian/SDKs/Symbian3Qt473/epoc32/release/armv5/udeb/qtmain.lib Running command: C:/QtSDK/Symbian/tools/gcce4/bin/arm-none-symbianelf-g++.exe -Wl,-Ttext,0x8000 -Wl,--no-undefined -nodefaultlibs -Wl,-shared -Wl,-Tdata,0x400000 -Wl,--default-symver '-Wl,-soname=dubizzle{000a0000}[e5f5fb1c].exe' -Wl,--entry=_E32Startup -Wl,-u,_E32Startup,C:/QtSDK/Symbian/SDKs/Symbian3Qt473/epoc32/release/armv5/udeb/eexe.lib -o C:/QtSDK/Symbian/SDKs/Symbian3Qt473/epoc32/release/armv5/udeb/dubizzle.exe.sym -Wl,-Map=C:/QtSDK/Symbian/SDKs/Symbian3Qt473/epoc32/release/armv5/udeb/dubizzle.exe.map @C:/QtSDK/Symbian/SDKs/Symbian3Qt473/epoc32/build/dubizzle/c_aad491c882e3389e/dubizzle_exe/armv5/udeb/dubizzle_udeb_objects.via --start-group C:/QtSDK/Symbian/SDKs/Symbian3Qt473/epoc32/release/armv5/udeb/usrt3_1.lib --end-group C:/QtSDK/Symbian/SDKs/Symbian3Qt473/epoc32/release/armv5/udeb/usrt3_1.lib C:/QtSDK/Symbian/SDKs/Symbian3Qt473/epoc32/release/armv5/udeb/qtmain.lib C:/QtSDK/Symbian/SDKs/Symbian3Qt473/epoc32/release/armv5/lib/kqoauthd0.dso C:/QtSDK/Symbian/SDKs/Symbian3Qt473/epoc32/release/armv5/lib/libstdcppv5.dso C:/QtSDK/Symbian/SDKs/Symbian3Qt473/epoc32/release/armv5/lib/QtDeclarative.dso C:/QtSDK/Symbian/SDKs/Symbian3Qt473/epoc32/release/armv5/lib/QtGui.dso C:/QtSDK/Symbian/SDKs/Symbian3Qt473/epoc32/release/armv5/lib/QtNetwork.dso C:/QtSDK/Symbian/SDKs/Symbian3Qt473/epoc32/release/armv5/lib/QtCore.dso C:/QtSDK/Symbian/SDKs/Symbian3Qt473/epoc32/release/armv5/lib/libpthread.dso C:/QtSDK/Symbian/SDKs/Symbian3Qt473/epoc32/release/armv5/lib/libc.dso C:/QtSDK/Symbian/SDKs/Symbian3Qt473/epoc32/release/armv5/lib/libm.dso C:/QtSDK/Symbian/SDKs/Symbian3Qt473/epoc32/release/armv5/lib/euser.dso C:/QtSDK/Symbian/SDKs/Symbian3Qt473/epoc32/release/armv5/lib/libdl.dso C:/QtSDK/Symbian/SDKs/Symbian3Qt473/epoc32/release/armv5/lib/stdnew.dso C:/QtSDK/Symbian/SDKs/Symbian3Qt473/epoc32/release/armv5/lib/drtaeabi.dso C:/QtSDK/Symbian/SDKs/Symbian3Qt473/epoc32/release/armv5/lib/dfpaeabi.dso -lsupc++ -lgcc arm-none-symbianelf-g++.exe: C:/QtSDK/Symbian/SDKs/Symbian3Qt473/epoc32/release/armv5/lib/kqoauthd0.dso: No such file or directory A: Solved !!! The problem was that I am including a .dll library, this works great for the simulator but not for the device, so the idea was to include all .h and .cpp files if the target is a symbian device, and the .dll library if the target is the simulator.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529851", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Android: Custom preference screen size problem I'm using a custom layout to display preferences so that I can insert an ad banner at the bottom of the screen. The idea is to have the banner stick to the bottom of the page, and have the preferences displayed in the rest of the screen in a scrollview. I have a problem with the height taken by the preferences. I've currently hardcoded it to "2000dip" in the XML layout below. It works fine, the banner stays at the bottom, preferences at the top in a scrollable view. But having a hardcoded height value is bad and I'd like it to automatically being set to the exact height taken by the preferences because currently it is either too short or too long (with a blank area after the preferences). I've tried to replace the hardcoded value with wrap_content or fill_parent with no success. Any idea? In my PreferenceActivity I've included the following two lines: setContentView(R.layout.preferences_scrollable); addPreferencesFromResource(R.layout.preferences); And I've defined a layout preferences_scrollable in the xml file preferences_scrollable.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <ScrollView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" android:id="@+id/pref_scrollable_sv"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:id="@+id/pref_scrollable_ll"> <ListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="2000dip"> </ListView> </LinearLayout> </ScrollView> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical"> <com.google.ads.AdView android:id="@+id/ad" ads:adSize="BANNER" android:layout_width="fill_parent" ads:loadAdOnCreate="true" ads:adUnitId="xxx" android:layout_height="wrap_content" android:layout_weight="0"/> </LinearLayout> </LinearLayout> A: Using the attribute "android:fillViewport" in the scrollview makes it have a correct height. So that would be the solution except that with this attribute, the view doesn't scroll, or scrolls very badly. Looks like an Android bug to me. Anyway, the solution that works is to drop the ScrollView and instead use a LinearLayout (that supports scrolling as well). The layout correctly working with a scrollable preference list (content filled from Java code) on top and an ad banner on the bottom is given below. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <LinearLayout android:layout_width="fill_parent" android:id="@+id/ad_layout" android:layout_height="wrap_content" android:orientation="vertical" android:layout_alignParentBottom="true"> <com.google.ads.AdView android:id="@+id/ad" ads:adSize="BANNER" android:layout_width="fill_parent" ads:loadAdOnCreate="true" ads:adUnitId="xxx" android:layout_height="wrap_content" primaryTextColor="#FFFFFF" secondaryTextColor="#CCCCCC" /> </LinearLayout> <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal" android:layout_above="@+id/ad_layout"> <ListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="wrap_content"> </ListView> </LinearLayout> </RelativeLayout> A: Try to set <android:layout_marginRight="10dp" android:layout_marginBottom="10dp" android:layout_marginLeft="5dp>" in layout properties. A: Use a RelativeLayout for your outer layout. Example: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" .....> <LinearLayout android:layout_alignParentBottom="true" android:id="@+id/adsLayout" ...> <!-- This is the ads part of it, which will remain the same as you have above--> </LinearLayout> <!-- You have to have the ads part first, so you are able to reference it with the scrollview --> <ScrollView .... android:layout_above="@+id/adsLayout"> <!-- This ScrollView contents will remain the same --> </ScrollView> </RelativeLayout> So, in the ads portion of the layout, you use android:layout_alignParentBottom="true" to put it at the bottom of the screen. Then in the ScrollView, you put android:layout_above="@+id/adsLayout", so it goes above the ads view. This will format it as you need. That should work. Just comment if you have issues.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Retrieving multiple arguments for a single option using getopts in Bash I need help with getopts. I created a Bash script which looks like this when run: $ foo.sh -i env -d directory -s subdirectory -f file It works correctly when handling one argument from each flag. But when I invoke several arguments from each flag I am not sure how to pull the multiple variable information out of the variables in getopts. while getopts ":i:d:s:f:" opt do case $opt in i ) initial=$OPTARG;; d ) dir=$OPTARG;; s ) sub=$OPTARG;; f ) files=$OPTARG;; esac done After grabbing the options I then want to build directory structures from the variables foo.sh -i test -d directory -s subdirectory -s subdirectory2 -f file1 file2 file3 Then the directory structure would be /test/directory/subdirectory/file1 /test/directory/subdirectory/file2 /test/directory/subdirectory/file3 /test/directory/subdirectory2/file1 /test/directory/subdirectory2/file2 /test/directory/subdirectory2/file3 Any ideas? A: There actually is a way to retrieve multiple arguments using getopts, but it requires some manual hacking with getopts' OPTIND variable. See the following script (reproduced below): https://gist.github.com/achalddave/290f7fcad89a0d7c3719. There's probably an easier way, but this was the quickest way I could find. #!/bin/sh usage() { cat << EOF $0 -a <a1> <a2> <a3> [-b] <b1> [-c] -a First flag; takes in 3 arguments -b Second flag; takes in 1 argument -c Third flag; takes in no arguments EOF } is_flag() { # Check if $1 is a flag; e.g. "-b" [[ "$1" =~ -.* ]] && return 0 || return 1 } # Note: # For a, we fool getopts into thinking a doesn't take in an argument # For b, we can just use getopts normal behavior to take in an argument while getopts "ab:c" opt ; do case "${opt}" in a) # This is the tricky part. # $OPTIND has the index of the _next_ parameter; so "\${$((OPTIND))}" # will give us, e.g., ${2}. Use eval to get the value in ${2}. # The {} are needed in general for the possible case of multiple digits. eval "a1=\${$((OPTIND))}" eval "a2=\${$((OPTIND+1))}" eval "a3=\${$((OPTIND+2))}" # Note: We need to check that we're still in bounds, and that # a1,a2,a3 aren't flags. e.g. # ./getopts-multiple.sh -a 1 2 -b # should error, and not set a3 to be -b. if [ $((OPTIND+2)) -gt $# ] || is_flag "$a1" || is_flag "$a2" || is_flag "$a3" then usage echo echo "-a requires 3 arguments!" exit fi echo "-a has arguments $a1, $a2, $a3" # "shift" getopts' index OPTIND=$((OPTIND+3)) ;; b) # Can get the argument from getopts directly echo "-b has argument $OPTARG" ;; c) # No arguments, life goes on echo "-c" ;; esac done A: I know this question is old, but I wanted to throw this answer on here in case someone comes looking for an answer. Shells like BASH support making directories recursively like this already, so a script isn't really needed. For instance, the original poster wanted something like: $ foo.sh -i test -d directory -s subdirectory -s subdirectory2 -f file1 file2 file3 /test/directory/subdirectory/file1 /test/directory/subdirectory/file2 /test/directory/subdirectory/file3 /test/directory/subdirectory2/file1 /test/directory/subdirectory2/file2 /test/directory/subdirectory2/file3 This is easily done with this command line: pong:~/tmp [10] rmclean$ mkdir -pv test/directory/{subdirectory,subdirectory2}/{file1,file2,file3} mkdir: created directory ‘test’ mkdir: created directory ‘test/directory’ mkdir: created directory ‘test/directory/subdirectory’ mkdir: created directory ‘test/directory/subdirectory/file1’ mkdir: created directory ‘test/directory/subdirectory/file2’ mkdir: created directory ‘test/directory/subdirectory/file3’ mkdir: created directory ‘test/directory/subdirectory2’ mkdir: created directory ‘test/directory/subdirectory2/file1’ mkdir: created directory ‘test/directory/subdirectory2/file2’ mkdir: created directory ‘test/directory/subdirectory2/file3’ Or even a bit shorter: pong:~/tmp [12] rmclean$ mkdir -pv test/directory/{subdirectory,subdirectory2}/file{1,2,3} mkdir: created directory ‘test’ mkdir: created directory ‘test/directory’ mkdir: created directory ‘test/directory/subdirectory’ mkdir: created directory ‘test/directory/subdirectory/file1’ mkdir: created directory ‘test/directory/subdirectory/file2’ mkdir: created directory ‘test/directory/subdirectory/file3’ mkdir: created directory ‘test/directory/subdirectory2’ mkdir: created directory ‘test/directory/subdirectory2/file1’ mkdir: created directory ‘test/directory/subdirectory2/file2’ mkdir: created directory ‘test/directory/subdirectory2/file3’ Or shorter, with more conformity: pong:~/tmp [14] rmclean$ mkdir -pv test/directory/subdirectory{1,2}/file{1,2,3} mkdir: created directory ‘test’ mkdir: created directory ‘test/directory’ mkdir: created directory ‘test/directory/subdirectory1’ mkdir: created directory ‘test/directory/subdirectory1/file1’ mkdir: created directory ‘test/directory/subdirectory1/file2’ mkdir: created directory ‘test/directory/subdirectory1/file3’ mkdir: created directory ‘test/directory/subdirectory2’ mkdir: created directory ‘test/directory/subdirectory2/file1’ mkdir: created directory ‘test/directory/subdirectory2/file2’ mkdir: created directory ‘test/directory/subdirectory2/file3’ Or lastly, using sequences: pong:~/tmp [16] rmclean$ mkdir -pv test/directory/subdirectory{1..2}/file{1..3} mkdir: created directory ‘test’ mkdir: created directory ‘test/directory’ mkdir: created directory ‘test/directory/subdirectory1’ mkdir: created directory ‘test/directory/subdirectory1/file1’ mkdir: created directory ‘test/directory/subdirectory1/file2’ mkdir: created directory ‘test/directory/subdirectory1/file3’ mkdir: created directory ‘test/directory/subdirectory2’ mkdir: created directory ‘test/directory/subdirectory2/file1’ mkdir: created directory ‘test/directory/subdirectory2/file2’ mkdir: created directory ‘test/directory/subdirectory2/file3’ A: getopts options can only take zero or one argument. You might want to change your interface to remove the -f option, and just iterate over the remaining non-option arguments usage: foo.sh -i end -d dir -s subdir file [...] So, while getopts ":i:d:s:" opt; do case "$opt" in i) initial=$OPTARG ;; d) dir=$OPTARG ;; s) sub=$OPTARG ;; esac done shift $(( OPTIND - 1 )) path="/$initial/$dir/$sub" mkdir -p "$path" for file in "$@"; do touch "$path/$file" done A: The original question deals with getopts, but there is another solution that provides more flexible functionality without getopts (this is perhaps a bit more verbose, but provides a far more flexible command line interface). Here is an example: while [[ $# > 0 ]] do key="$1" case $key in -f|--foo) nextArg="$2" while ! [[ "$nextArg" =~ -.* ]] && [[ $# > 1 ]]; do case $nextArg in bar) echo "--foo bar found!" ;; baz) echo "--foo baz found!" ;; *) echo "$key $nextArg found!" ;; esac if ! [[ "$2" =~ -.* ]]; then shift nextArg="$2" else shift break fi done ;; -b|--bar) nextArg="$2" while ! [[ "$nextArg" =~ -.* ]] && [[ $# > 1 ]]; do case $nextArg in foo) echo "--bar foo found!" ;; baz) echo "--bar baz found!" ;; *) echo "$key $nextArg found!" ;; esac if ! [[ "$2" =~ -.* ]]; then shift nextArg="$2" else shift break fi done ;; -z|--baz) nextArg="$2" while ! [[ "$nextArg" =~ -.* ]] && [[ $# > 1 ]]; do echo "Doing some random task with $key $nextArg" if ! [[ "$2" =~ -.* ]]; then shift nextArg="$2" else shift break fi done ;; *) echo "Unknown flag $key" ;; esac shift done In this example we are looping through all of the command line options looking for parameters that match our accepted command line flags (such as -f or --foo). Once we find a flag, we loop through every parameter until we run out of parameters or encounter another flag. This breaks us back out into our outer loop which only processes flags. With this setup, the following commands are equivalent: script -f foo bar baz script -f foo -f bar -f baz script --foo foo -f bar baz script --foo foo bar -f baz You can also parse incredibly disorganized parameter sets such as: script -f baz derp --baz herp -z derp -b foo --foo bar -q llama --bar fight To get the output: --foo baz found! -f derp found! Doing some random task with --baz herp Doing some random task with -z derp --bar foo found! --foo bar found! Unknown flag -q Unknown flag llama --bar fight found! A: #!/bin/bash myname=$(basename "$0") # help function help () { cat <<EOP $myname: -c cluster [...] -a action [...] -i instance [...] EOP } # parse sub options get_opts () { rs='' && rc=0 # return string and return code while [[ $# -gt 0 ]]; do shift [[ "$1" =~ -.* ]] && break || rs="$rs $1" && rc=$((rc + 1)) done echo "$rs" } #parse entire command-line while [[ $# -gt 0 ]]; do case $1 in "-a") ACTS="$(get_opts $@)" ;; "-i") INSTS=$(get_opts $@) ;; "-c") CLUSTERS=$(get_opts $@) ;; "-h") help ;; ?) echo "sorry, I dont do $1" exit ;; esac shift done A: The following link should be a general solution for this requirement. It's easy to inject and clear enough to understand also minimizes the impact on the original code. Multiple option arguments using getopts (bash) function getopts-extra () { declare i=1 # if the next argument is not an option, then append it to array OPTARG while [[ ${OPTIND} -le $# && ${!OPTIND:0:1} != '-' ]]; do OPTARG[i]=${!OPTIND} let i++ OPTIND++ done } # Use it within the context of `getopts`: while getopts s: opt; do case $opt in s) getopts-extra "$@" args=( "${OPTARG[@]}" ) esac done A: If you want to specify any number of values for an option, you can use a simple loop to find them and stuff them into an array. For example, let's modify the OP's example to allow any number of -s parameters: unset -v sub while getopts ":i:d:s:f:" opt do case $opt in i ) initial=$OPTARG;; d ) dir=$OPTARG;; s ) sub=("$OPTARG") until [[ $(eval "echo \${$OPTIND}") =~ ^-.* ]] || [ -z $(eval "echo \${$OPTIND}") ]; do sub+=($(eval "echo \${$OPTIND}")) OPTIND=$((OPTIND + 1)) done ;; f ) files=$OPTARG;; esac done This takes the first argument ($OPTARG) and puts it into the array $sub. Then it will continue searching through the remaining parameters until it either hits another dashed parameter OR there are no more arguments to evaluate. If it finds more parameters that aren't a dashed parameter, it adds it to the $sub array and bumps up the $OPTIND variable. So in the OP's example, the following could be run: foo.sh -i test -d directory -s subdirectory1 subdirectory2 -f file1 If we added these lines to the script to demonstrate: echo ${sub[@]} echo ${sub[1]} echo $files The output would be: subdirectory1 subdirectory2 subdirectory2 file1 A: I fixed the same problem you had like this: Instead of: foo.sh -i test -d directory -s subdirectory -s subdirectory2 -f file1 file2 file3 Do this: foo.sh -i test -d directory -s "subdirectory subdirectory2" -f "file1 file2 file3" With the space separator you can just run through it with a basic loop. Here's the code: while getopts ":i:d:s:f:" opt do case $opt in i ) initial=$OPTARG;; d ) dir=$OPTARG;; s ) sub=$OPTARG;; f ) files=$OPTARG;; esac done for subdir in $sub;do for file in $files;do echo $subdir/$file done done Here's a sample output: $ ./getopts.sh -s "testdir1 testdir2" -f "file1 file2 file3" testdir1/file1 testdir1/file2 testdir1/file3 testdir2/file1 testdir2/file2 testdir2/file3 A: You can use the same option multiple times and add all values to an array. For the very specific original question here, Ryan's mkdir -p solution is obviously the best. However, for the more general question of getting multiple values from the same option with getopts, here it is: #!/bin/bash while getopts "m:" opt; do case $opt in m) multi+=("$OPTARG");; #... esac done shift $((OPTIND -1)) echo "The first value of the array 'multi' is '$multi'" echo "The whole list of values is '${multi[@]}'" echo "Or:" for val in "${multi[@]}"; do echo " - $val" done The output would be: $ /tmp/t The first value of the array 'multi' is '' The whole list of values is '' Or: $ /tmp/t -m "one arg with spaces" The first value of the array 'multi' is 'one arg with spaces' The whole list of values is 'one arg with spaces' Or: - one arg with spaces $ /tmp/t -m one -m "second argument" -m three The first value of the array 'multi' is 'one' The whole list of values is 'one second argument three' Or: - one - second argument - three A: As you don't show how you hope to construct your list /test/directory/subdirectory/file1 . . . test/directory/subdirectory2/file3 it's a little unclear how to proceed, but basically you need to keep appending any new values to the appropriate variable, i.e. case $opt in d ) dirList="${dirList} $OPTARG" ;; esac Note that on the first pass dir will be empty, and you'll wind up with a space leading at the from of your final value for ${dirList}. (If you really need code that doesn't include any extra spaces, front or back, there is a command I can show you, but it will be hard to understand, and it doesn't seem that you'll need it here, but let me know) You can then wrap your list variables in for loops to emit all the values, i.e. for dir in ${dirList} do for f in ${fileList} ; do echo $dir/$f done done Finally, it is considered good practice to 'trap' any unknown inputs to your case statement, i.e. case $opt in i ) initial=$OPTARG;; d ) dir=$OPTARG;; s ) sub=$OPTARG;; f ) files=$OPTARG;; * ) printf "unknown flag supplied "${OPTARG}\nUsageMessageGoesHere\n" exit 1 ;; esac I hope this helps. A: This is a simple way to pass multiple arguments for a single option. #!/bin/bash #test.sh -i 'input1 input2' #OR #test.sh -i 'input*' while getopts "i:" opt; do case $opt in i ) input=$OPTARG;; esac done inputs=( $input ) echo "First input is "$inputs"" echo "Second input is "${inputs[1]}"" echo "All inputs: "${inputs[@]}""
{ "language": "en", "url": "https://stackoverflow.com/questions/7529856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "74" }
Q: emacs: How to stop search after file ending? I somehow could not figure out how I can search in Aquamacs so that the search stops at the file end and does not "wrap around" (continuing from the file beginning). If one steps through the search result, one could manually stop at the last item, but I typically step through quite fast so that I accidentally jump over the file ending and continue at the file beginning. Any ideas? A: There is a variable isearch-wrap-function which is unset by default. Set it to an empty function and then it won't wrap: (setq isearch-wrap-function (lambda ())) You can also set it so that it throws an error and aborts isearch: (setq isearch-wrap-function (lambda () (error "no more matches"))) A: Hmmm. It seems like such a terrible idea. But apparently you aren't the first person to want this. For the record, you can just un-wrap with C-r. This question has an answer with defadvice that does that you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Delegate problem when calling function from EventHandler I am trying to use the timer class in C# for this TCM Updater and I keep getting an error: "Delegate to an instance method cannot have null 'this'." I thought I would just have to add "this" to the beginning of the function, but still getting that error. Any idea what I might need to do? this is the code I am using (error on function call 5 lines down): public Form1() { InitializeComponent(); updateTimer = new System.Timers.Timer(10000); updateTimer.Elapsed += new ElapsedEventHandler(this.onUpdateEvent); <--- Error here updateTimer.Interval = 2000; updateTimer.Enabled = true; } private void OnUpdateEvent(object source, ElapsedEventArgs e) { Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime); } A: aside from the typo: why not just write updateTimer.Elapsed += OnUpdateEvent; A: Change this: updateTimer.Elapsed += new ElapsedEventHandler(this.onUpdateEvent); To this: updateTimer.Elapsed += new ElapsedEventHandler(OnUpdateEvent); Or the simplified syntax (as others have suggested): updateTimer.Elapsed += OnUpdateEvent; A: try this if this works for you! public Form1() { InitializeComponent(); System.Windows.Forms.Timer timer = newSystem.Windows.Forms.Timer(); timer.Interval = 2000; timer.Tick += new EventHandler(Timer_Tick); timer.Start(); } void Timer_Tick(object sender, EventArgs e) { // } A: a very simple solution is to make the method OnUpdateEvent static, if you don't need any instance members.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ggplot2 not present in rpy2 for python? I am working with rpy2 v2.1.9 in Python3.2, I don't understand why I can't use the library ggplot2 import rpy2 from rpy2.robjects import r r.library("ggplot2") Here is the error message I got Error in function (package, help, pos = 2, lib.loc = NULL, character.only = FALSE, : there is no package called 'ggplot2' Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.2/dist-packages/rpy2/robjects/functions.py", line 82, in __call__ return super(SignatureTranslatedFunction, self).__call__(*args, **kwargs) File "/usr/local/lib/python3.2/dist-packages/rpy2/robjects/functions.py", line 34, in __call__ res = super(Function, self).__call__(*new_args, **new_kwargs) rpy2.rinterface.RRuntimeError: Error in function (package, help, pos = 2, lib.loc = NULL, character.only = FALSE, : there is no package called 'ggplot2' A: See the tail of the first error message: there is no package called 'ggplot2' You need to install the ggplot2 package first. Fire up R itself, and say install.packages("ggplot2")
{ "language": "en", "url": "https://stackoverflow.com/questions/7529862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Best way to do jquery form validation? Okay, so we have input boxes for the following: firstname, lastname, email, password, city, state, captcha, terms and conditions I've done the validation for all of these input boxes. This validation is seperate for each ID, and works via change() The e-mail and captcha use ajax, and if they are successful, it returns true. I also have all of the validation inside the form submit() But when the form is submitted, the validation on the ajax takes place again and the form is submitted WHILE the ajax request is processing. How would I make the form delay submitting until the validation has ran and then auto submit? Like a sort of delay feature? Each part of validation returns a var named error - error can either be true or false If the error is false, it prevents form submit by returning false. I've been thinking of scrapping the whole submit() validation, as its just a duplicate validation running on submit and basically running in a loop, and I was thinking of disabling the submit button with jquery unless everything is validated via change()? A: Code excerpts would be handy but I'd say make your AJAX oncomplete function call your submit. Since you have multiple AJAX functions going on you may need to daisy chain them, i.e. when one finishes call the next and so on until the final one finishes and you call the submit function. Otherwise try having the AJAX only called once after field blur and not again on submit? Again, need to see code to understand what's really going on.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Beginner WCF Service setup I'm trying to figure out WCF Services. I got 1 to work 1 time and now I can't seem to get this to work at all (even following the previous examples). I don't understand several things about the WCF Services. For example why does it need endpoints. What purpose do they serve? However, if any one could help me get past this error that would be great. I'm trying to setup a default WCF Service. I haven't added any code. I'm just trying to get the service to display. I have pilltrakr.cs using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; namespace serviceContract { public class pilltrakr : Ipilltrakr { public void DoWork() { } } } I have Ipilltrakr: namespace serviceContract { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "Ipilltrakr" in both code and config file together. [ServiceContract] public interface Ipilltrakr { [OperationContract] void DoWork(); } } I have: pilltrakr.svc <%@ ServiceHost Language="C#" Debug="true" Service="pilltrakr" CodeBehind="~/App_Code/pilltrakr.cs" %> In my web.config I have the following: <system.serviceModel> <services> <service name="serviceContract.pilltrakr" behaviorConfiguration="InternalWebService"> <endpoint contract="serviceContract.Ipilltrakr" binding="basicHttpBinding" address="pilltrakr" bindingConfiguration="InternalHttpBinding" bindingNamespace="serviceContract"/> </service> </services> </system.serviceModel> I'm getting the following error: Server Error in '/pilltrakr' Application. The type 'pilltrakr', provided as the Service attribute value in the ServiceHost directive, or provided in the configuration element system.serviceModel/serviceHostingEnvironment/serviceActivations could not be found. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidOperationException: The type 'pilltrakr', provided as the Service attribute value in the ServiceHost directive, or provided in the configuration element system.serviceModel/serviceHostingEnvironment/serviceActivations could not be found. A: You need to specify the exact name of the service class in your .svc file including namespace: <%@ ServiceHost Language="C#" Debug="true" Service="serviceContract.pilltrakr" CodeBehind="~/App_Code/pilltrakr.cs" %> As far as your question about endpoints is concerned, they are used to define at what address the service will respond and what binding it will use. For example you could expose your service on 2 different endpoints => one using SOAP and other using REST.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ruby on Rails: Updating data after form submission This is my form: <table> <tbody> <% form_for :HhActiveCarrier, @carriers, :url => { :action => "update" } do |f| %> <% for carrier in @carriers %> <tr> <%= render :partial => "summary_detail", :locals => {:carrier => carrier, :f => f} %> </tr> <% end %> </tbody> </table> <%= submit_tag "Update" %> <% end %> With my partial: <td class="tn"><%= h(carrier.name.to_s()) -%></td> <td class="sc"><%= h(carrier.country.to_s()) -%></td> <td class="sc"><%= select(:carrier, "country", @countries) -%></td> This is the controller where I define the variables: class ActiveCarriersController < ApplicationController def index @carriers = HhActiveCarrier.find(:all) for carrier in @carriers country = carrier["country"] if country.nil? carrier["country"] = "none" end end @countries = ["USA", "UK", "Canada"] end def update carriers = HhActiveCarrier.find(:all) for carrier in carriers carrier.update_attributes(params[:country]) end redirect_to( :action => "index" ) end What I want to happen is after I click the "Update" button, I want the new country selected from the drop down list to be put into the HHActiveCarrier model. With the code I have right now, I get this error: OCIError: ORA-00904: "ID": invalid identifier: UPDATE hh_active_carriers SET name = 'AT&T', country = null WHERE id = null How would I go about updating the attributes this? I am using ruby on rails 2.3.8. Edit: Added parameters hash from development log: parameters: {"commit"=>"Update", "carrier"=>{"country"=>"USA"}, "action"=>"update", "controller"=>"active_carriers"} content_type: # accepts: [#, #, #] raw_post: "carrier%5Bcountry%5D=USA&carrier%5Bcountry%5D=USA&carrier%5Bcountry%5D=USA&carrier%5Bcountry%5D=USA&commit=Update" query_parameters: {} request_parameters: {"commit"=>"Update", "action"=>"update", "carrier"=>{"country"=>"USA"}, "controller"=>"active_carriers"} Edit3: Form: <table> <tbody> <% form_for :HhActiveCarrier, :url => { :action => "update" } do |f| %> <% for carrier in @carriers %> <tr> <%= render :partial => "layouts/summary_detail", :locals => {:carrier => carrier, :f => f} %> </tr> <% end %> </tbody> </table> <%= submit_tag "Update" %> <% end %> Partial: <td class="tn"><%= h(carrier.name.to_s()) %></td> <td class="sc"><%= h(carrier.id.to_s()) %></td> <td class="sc"><%= h(carrier.country.to_s()) %></td> <td class="sc"><%= f.collection_select :country, HhActiveCarrier::COUNTRIES, :to_s, :to_s %></td> Controller: class ActiveCarriersController < ApplicationController def index @carriers = HhActiveCarrier.find(:all) for carrier in @carriers country = carrier["country"] if country.nil? carrier["country"] = "none" end end end def update #update code redirect_to( :action => "index" ) end end A: A few things: * *Adjust your form so it uses the fields_for helper for each of the carriers (scroll down almost 1/2 way, for the code snippet that's labeled "Or a collection to be used:") *Add a hidden field in your partial that indicates the ID of the carrier being updated (right now, your params hash doesn't include the ID of the record to be updated, so the update fails) *Don't loop through all carriers in your controller. You want to loop through the hash instead. So, the hash you want from the form should look something like: params => {:carrier[1] => {:country => "USA", :id=>"5"}, carrier[2] => {:country => "Brazil", :id=>"17"}} Then in your controller, you would loop through params[:carrier].each to update your carriers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WCF returns object with only default values I have a test class CustObject which has DataContract and DataMember attributes. When I return this to the client, however, all values are the default value. Service Side: [DataContract] public class CustObject { [DataMember (IsRequired = true)] public int n1; [DataMember (IsRequired = true)] public int n2; [DataMember] public int val1 = 552; [DataMember] public int? val2 = 88; [DataMember] int val3 = 11; [DataMember] string val4 = "hello world"; public CustObject() { n1 = 1; n2 = 2; } private int nprivate = 18; } public class CalculatorService : ICalculator { public CustObject Foo() { Console.WriteLine(); CustObject test = new CustObject(); Console.WriteLine("Should read that n1 = {0} and n2 = {1}", test.n1, test.n2); return test; } } [ServiceContract] public interface ICalculator { [OperationContract] CustObject Foo(); } Client side: public static void Main () { CalculatorClient client = new CalculatorClient( new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:8000/ServiceModelSamples/Service/CalculatorService")); CustObject custObj = client.Foo(); Console.WriteLine(custObj.val1 + ", " + custObj.val2 + ", " + custObj.val1 + ", " + custObj.val2 + ", " + custObj.val3 + ", " + custObj.val4); //Step 3: Closing the client gracefully closes the connection and cleans up resources. client.Close (); Console.WriteLine (); Console.WriteLine ("Press <ENTER> to terminate client."); Console.ReadLine (); } } And the output is just 0, 0, 0, 0, 0, (the last value is an empty string) I have read a ton of stuff to try to figure out this problem. It seems that even though the values are initialized, the xml conversion is just giving every field a default value. I can't figure out why. I used svutil to create the proxy file. A: One of the issues with using a generated proxies, whether is is through svutil or adding a service reference, is updating your service. Any time I find I am not getting the expected values in a field, it is because I changed something in my service and didn't re-generate my proxy code. If you renamed a property (even changing case), or change a data type, rather than throwing an exception, you just get the default value for that data type. Try running svutil again. Note: This is one of the reasons I stopped using generated proxies and now use a ChannelFactory to conenct to WCF. A: After an entire day, I found the solution. This may apply to all those using Mono! Very useful solution. I am using Mono and the svutil for Mono (at least on ubuntu) generates output code that is correct except one particularly important point. The proxy class for the custom class must be contained within the same namespace as the actual custom class defined in the service! For the example above, in the output.cs file generated by svutil, I had to surround the proxy CustObject with the Service namespace. I figured this out by running the .NET version of svutil in Windows and comparing the generated code files. I would say this is probably a bug in Mono's svutil.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: taking input from a file i have the following file named asmfile.txt copy start 1000 read ldx zero rd indev rloop tix k100 in order to take linewise input from this file i wrote the following code.... void aviasm::crsymtab() { ifstream in(asmfile,ios::in);//opening the asmfile in.seekg(0,ios::beg); char c; string str[3]; string subset; long locctr=0; int i=0; while((c=in.get())!=EOF) { in.putback(c); str[0]=""; str[1]=""; str[2]=""; while((c=in.get())!='\n') { in.putback(c); in>>str[i]; i==2?i=0:i++; //limiting i to 2.... } cout<<str[0]<<" "<<str[1]<<" "<<str[2]<<endl; } in.close(); } //now the problem is that the first three lines are being successfully input into str...but the last line is not being input to str....i know this because when running the program on console i see... copy start 1000 read ldx zero rd indev 'rd indev' indentation changes because str[0]="rd" and str[1]="indev".....plz tell me why the fourth line is not being input into str.... A: I don't know what's the aim of reading the file character by character and putting them back into the stream. The line string str[3]; defines strings str[0] to str[2]. Writing to non-existing str[3]is undefined behaviour. A cleaner approach would be std::ifstream in(asmfile); std::vector<std::string> lines; std::string line; while (std::getline(in, line)) { lines.push_back(line); } Afterwards lines.size() gives the numbers of lines read successfully. for (size_t i = 0; i < lines.size(); ++i) { std::cout << i << " : " << lines[i] << '\n'; } A: As to why your code fails: while((c=in.get())!='\n') enters infinite loop when there's no new-line character in the last line of asmfile. Change i==2?i=0:i++; to i++ and move int i=0; in while loop, edit asmfile so it'll have a new-line character behind last line and your code will work. That said, you really SHOULD be doing it like Rene suggested. Code like this is messy and error prone. A: I'm having trouble debugging your code, because I don't understand your intent -- what is the deal with the get() and pushback() calls?. So, instead of answering your immediate question, let me rewrite your code: #include <string> #include <sstream> #include <iostream> #include <fstream> const char * asmfile("/tmp/asm.txt"); void crsymtab() { std::ifstream in(asmfile); // opening the asmfile std::string line; while(std::getline(in, line)) { std::istringstream sline(line); std::string str[3]; if(sline.peek() == ' ') sline >> str[1] >> str[2]; else sline >> str[0] >> str[1] >> str[2]; std::cout << str[0] << " " << str[1] << " " << str[2] << "\n"; } } int main() { crsymtab(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7529881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What would this phone number regex look like? (555) 555 - 5555 Everything above would be required - spacing and all. A: Try with: /\(\d{3}\) \d{3} - \d{4}/ A: see below example, only (555) 555 - 5555 will be grepped out: kent$ cat a (555) 555 - 5555 (5554) 555 - 5555 (555)555 - 5555 (555) 5554 - 5555 (555) 555 - 55554 (555)555 - 5555555 kent$ grep -P "^\(\d{3}\) \d{3} - \d{4}$" a (555) 555 - 5555 A: There are several options. For example, /\(\d{3}\)\ \d{3}\ \-\ \d{4}/ A: Assuming: (1-3 digits) 2-3 digits - 4-6 digits would be: ^\(\d{1,3}\) \d{2,3} - \d{4,6}$ You can adjust the allowed number of digits according to your needs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Control Entry to static library (.a) and never returns I have linked the static library with my code (.a) . But during run time , the control passes to library on the call to API, but it never returns, ex: archived test_func.o in test.a which has implementation test_func(), calling test_func() from main.c Printf("inside main now") test_func(); Printf("returned from lib - in main"); the second printf, never gets called and the message never gets displayed on the console. Can some one suggest what could be the problem? A: If it never prints the second message then either it's exiting in the function (in which case your program should complete) or test_func() has an infinite loop (though keep in mind that it could just be taking longer than you're prepared to wait). Without seeing the code to test_func(), we can't say for sure where the problem lies specifically. If you don't have the source code to test_func(), then the best you'll be able to do is run it and then cause a core dump from outside, such as with kill -6. Then you could load the executable and core file into gdb to try and figure out what it was doing. I should stress this won't be easy if the objects within the library don't include debugging information but you have to play the cards you're dealt.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529891", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UPDATE multiple rows to Value from another table (FK) I have imported an excel document into MySQL to tidy up and make better use of the data but I am having problems running an update. All tables used as examples below; Tables asset_register phone sim team The asset_register contains the following cols; id INT, serialNo VARCHAR, simNo INT, team VARCHAR The problem is that I want to create a team table and the reference the teamId in the asset_register table. Does that make sense? Instead of storing the actual team name i want a foreign key to the teams table. The problem lies in updating all the data in the asset_register table which was imported from excel. There are nearly the same no of teams as users (~500) and I need to write a query or Stored Procedure to update all of them. I thought that a stored procedure would be the way to go. So far i have the following but it updated the value of team to 'NULL' instead of the teamId. DELIMITER // DROP PROCEDURE `updateCrews`// CREATE DEFINER=`root`@`localhost` PROCEDURE `updateCrews`() BEGIN DECLARE rowCount INT; DECLARE crewNameFromRegister VARCHAR(7); DECLARE currentRow INT; DECLARE newCrewdata VARCHAR(7); SET rowCount=(SELECT COUNT(*) FROM asset_register); SET currentRow = 1; myUpdateLoop: WHILE (currentRow < rowCount) DO SET crewNameFromRegister = (SELECT crewID FROM asset_register WHERE id = currentRow); SET newCrewData = (SELECT id FROM crews WHERE crewName = crewNameFromRegister); UPDATE asset_register SET crewID = newCrewData; SET currentRow = currentRow + 1; END WHILE myUpdateLoop; END// DELIMITER ; Any help would be greatly appreciated, there is probably a better way to do this and a nudge in the right direction would be great. A: If I good understand your question I suggest you to use a mutli table update syntax describe in mysql manual in this article : MutliTableUpdate. You try to change a string key by an id, be carreful of data type / conversion. The idea should be: UPDATE asset_register, crews SET asset_register.crewID = crews.id WHERE crews.crewName = asset_register.crewID But it could be safer if you use an other column column to do it and check the intermediate result. On your first example: id INT, serialNo VARCHAR, simNo INT, team VARCHAR you can add a teamID column, do the update and rename your column
{ "language": "en", "url": "https://stackoverflow.com/questions/7529893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Apply Formating across multiple sheets I have searched and tried multiple different codes and way out there, but have had no luck finding a solution. I am trying to take a macro setup to format one sheet, which works perfectly, and apply the same code to all sheets in the workbook. I have searched multiple codes and sheet array formulas but are unable to either apply them to the code I have or understand them enough to change what needs to be changed in order for them to work. I am fairly new to the macro world and do not understand the programming language at all. I appreciate anyone's time that they put into helping me on this as I have been struggling with this for several weeks now. Thank you. The following code is what i have thus far: Sub DARprintready() ' ' DARprintready Macro ' ' Columns("A:A").Select Selection.columnwidth = 2.86 Columns("B:B").Select Selection.columnwidth = 4.57 Columns("C:C").Select Selection.columnwidth = 13.57 Columns("D:D").Select Selection.columnwidth = 8.57 Columns("E:E").Select Selection.columnwidth = 20.86 Columns("F:F").Select Selection.columnwidth = 8.43 Columns("G:H").Select Selection.columnwidth = 9.43 Columns("I:I").Select Selection.columnwidth = 9.14 Columns("J:J").Select Selection.columnwidth = 9.43 Columns("K:K").Select Selection.columnwidth = 50.4 Columns("L:L").Select Selection.columnwidth = 9 Range("E:E,K:K").Select Range("K1").Activate Selection.NumberFormat = "@" With Selection .HorizontalAlignment = xlGeneral .VerticalAlignment = xlBottom .WrapText = True .Orientation = 0 .AddIndent = False .IndentLevel = 0 .ShrinkToFit = False .ReadingOrder = xlContext .MergeCells = False End With ActiveWindow.SmallScroll Down:=-15 Columns("A:L").Select With Selection .HorizontalAlignment = xlGeneral .VerticalAlignment = xlCenter .Orientation = 0 .AddIndent = False .IndentLevel = 0 .ShrinkToFit = False .ReadingOrder = xlContext .MergeCells = False End With ActiveWindow.SmallScroll Down:=-6 Columns("A:A").Select ActiveWindow.SmallScroll Down:=-15 Range("A1").Select Sheets("Header").Select Range("A1:L4").Select Selection.Copy Sheets("Firmwide").Select Rows("1:1").Select Selection.Insert Shift:=xlDown Application.CutCopyMode = False With ActiveSheet.PageSetup .LeftHeader = "" .CenterHeader = "" .RightHeader = "" .LeftFooter = "" .CenterFooter = "Page &P of &N" .RightFooter = "" .LeftMargin = Application.InchesToPoints(0.18) .RightMargin = Application.InchesToPoints(0.16) .TopMargin = Application.InchesToPoints(0.17) .BottomMargin = Application.InchesToPoints(0.39) .HeaderMargin = Application.InchesToPoints(0.17) .FooterMargin = Application.InchesToPoints(0.16) .PrintHeadings = False .PrintGridlines = True .PrintComments = xlPrintNoComments .PrintQuality = 600 .CenterHorizontally = False .CenterVertically = False .Orientation = xlLandscape .Draft = False .PaperSize = xlPaperLetter .FirstPageNumber = xlAutomatic .Order = xlDownThenOver .BlackAndWhite = False .Zoom = 80 .PrintErrors = xlPrintErrorsDisplayed .OddAndEvenPagesHeaderFooter = False .DifferentFirstPageHeaderFooter = False .ScaleWithDocHeaderFooter = True .AlignMarginsHeaderFooter = True .EvenPage.LeftHeader.Text = "" .EvenPage.CenterHeader.Text = "" .EvenPage.RightHeader.Text = "" .EvenPage.LeftFooter.Text = "" .EvenPage.CenterFooter.Text = "" .EvenPage.RightFooter.Text = "" .FirstPage.LeftHeader.Text = "" .FirstPage.CenterHeader.Text = "" .FirstPage.RightHeader.Text = "" .FirstPage.LeftFooter.Text = "" .FirstPage.CenterFooter.Text = "" .FirstPage.RightFooter.Text = "" End With End Sub A: To add a bit to the other answer, use a with statement as a shorthand for all of your changes, so you don't have to keep typing the sheet name over and over Sub ColWidth() Dim wkst As Worksheet For Each wkst In ThisWorkbook.Sheets With wkst .Columns("A:A").ColumnWidth = 2.86 .Columns("B:B").ColumnWidth = 4.57 .Columns("C:C").ColumnWidth = 13.57 .Columns("D:D").ColumnWidth = 8.57 End With Next End Sub (you'll have to adopt the rest of it to this form) Also, consider keeping your column widths in an array, and assigning them to the columns in a loop. It won't speed things up, but your code will be more compact, and, I think, readable. E.g., Dim i As Integer Dim widths() As Variant widths = Array(4.5, 3.67, 5, 6.45, 10) For i = 1 To 5 Columns(i).ColumnWidth = widths(i) `Thank you iDevlop for the less Rube Goldberg approach Next That way, you can add more columns in at will without having to type everything out. A: Step 1 will be learning some VBA. Fortunately the task you are attempting doesn't require you to learn a tonne. Assuming that you need EXACTLY the same formatting on ALL sheets, you need to loop through the sheets. In order to do this you'll need to do 3 things. * *Create a variable for the target sheet name *Put your formatting inside a Loop that goes through each sheet *Replace the hardcoded sheet names in your macro with your variable name Your code will end up something like this Sub DARprintready() ' ' DARprintready Macro ' dim Outputsheet as workhsheet for each Outputsheet in activeworkbook.sheets outputsheet.select 'your formatting code here next You'll need to change that explicit reference to the sheet firmwide with a reference to the variable you just created. replace this: Sheets("Firmwide").Select with this: Outputsheet.Select hope that helps, A: As usual, I'm a little late, but here's a better solution. Feel free to mark mine as right if you feel it is a better solution. This way formats all the sheets at once avoiding the loop and is much faster since it is internal to Excel where the loops happen. Dim shs As Sheets, wks As Worksheet Dim rFormat As Range Set wks = ActiveWorkbook.Worksheets("Sheet1") Set shs = ActiveWorkbook.Sheets(Array("Sheet1", "Sheet2")) shs.Select Set rFormat = wks.Range("A1:A2,C3:C4") rFormat.Select With Selection .Font.ColorIndex = 3 .Interior.ColorIndex = 6 .Interior.Pattern = xlSolid End With wks.Select A: For a quick method: Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Select Columns("A:E").EntireColumn.AutoFit A: The above code did not work in my case, because it was missing to activate one of the 3 (or more) worksheets to get formatted. Since I spent some time for solving this issue, I'm sharing that piece of code. Obviusliy this can be improved, for example using arrays also for the format patterns. Sub PivotTabsFormatting() ' ' PivotTabsFormatting Macro ' This formats a column range columns on multiple sheets ' Keyboard Shortcut: Ctrl+a ' By PhB- Dec'18 ' Dim shs As Sheets Dim wks As Worksheet Dim rFormat1 As Range Dim rFormat2 As Range Set wks = ActiveWorkbook.Worksheets("Sheet1") Set shs = ActiveWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3")) Set rFormat1 = wks.Columns("D:O") 'could also be : .Range("D4:M10") Set rFormat2 = wks.Columns("B:C") 'could also be : .Range("B6:C6") shs.Select wks.Activate ' --> this was missing With rFormat1 .ColumnWidth = 15 End With With rFormat2 .EntireColumn.AutoFit End With wks.Select wks.Range("A1").Select End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/7529900", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Syntax error in sqlite trying to create a database I am new to SQLite. I downloaded the latest version of SQLite (both shell and dll) and extract them to my D: drive. I execute the 'sqlite3.exe' file by double clicking on that. When I try to create the database with the command sqlite3 test.db;, I get this error. D:\Android Work\Sqlite\sqlite-shell-win32-x86-3070800>sqlite3.exe SQLite version 3.7.8 2011-09-19 14:49:19 Enter ".help" for instructions Enter SQL statements terminated with a ";" sqlite> sqlite3 test.db ...> ; Error: near "sqlite3": syntax error sqlite> Please help me.. A: If you're seeing sqlite> then you are inside SQLite. You need to come out with .quit and then type sqlite3 testDB.db to create a database file managed with SQLite Example below: sqlite> sqlite3 testDB.db ...> CREATE TABLE first(a int, b string); Error: near "sqlite3": syntax error sqlite> .quit C:\Users\>sqlite3 testDB.db SQLite version 3.22.0 2018-01-22 18:45:57 Enter ".help" for usage hints. sqlite> .databases main: C:\Users\testDB.db sqlite> A: I believe you have to type "sqlite3 test.db" from the command line prompt, not from inside the interactive SQLite interface. See here: $ sqlite3 test.db SQLite version 3.0.8 Enter ".help" for instructions sqlite> .quit $ A: when you type sqlite3 in terminal or cmd you're getting into SQLite command prompt which doesn't allow you to create DB so quit from cmd or terminal using this command .quit now run following command to create new DB "sqlite3 siya.db" where "siya" is database name and check created database using following command .databases(to check all the databases) A: open cmd and type cd\ and then C:>cd sqlite C:\sqlite>sqlite3 test.db SQLite version 3.39.2 2022-07-21 15:24:47 Enter ".help" for usage hints. sqlite> .databases main: C:\sqlite\test.db r/w sqlite>
{ "language": "en", "url": "https://stackoverflow.com/questions/7529901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: how to uninstall VMware Workstation from Slackware64-current? I'm trying to uninstall VMware-Workstation 7.x from Slackware64-current to install VMware-Workstation 8. When I run the bundle installer, it tries to uninstall version 7 before attempting to install version 8. But uninstallation process dies out. Since I've don't have version 7 installer at hand, I've attempted using the provided uninstall script with the following syntax as root: vmware-installer --console --uninstall-component=vmware-workstation It goes up 34% and closes. Then I try vmware-installer --list-components And v.7 is still there! Ideas are welcome! A: did your VMware display on pkgtool list view? #pkgtool or you could try this link as a reference. Regards,
{ "language": "en", "url": "https://stackoverflow.com/questions/7529907", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Should I put my ASP.NET websites in the wwwroot folder? I have a number of websites that run under IIS on a single machine. Should I put these websites inside of the C:\inetpub\wwwroot\ folder or inside the C:\inetpub\ folder? E.g. * *C:\inetpub\wwwroot\Website1\ *C:\inetpub\wwwroot\Website2\ or * *C:\inetpub\Website1\ *C:\inetpub\Website2\ Are there any pros/cons for either or another recommended location (I only have a C drive on this machine)? I am not sure whether there is a "correct" answer to this, but want to follow best practice if there is one. Many thanks, Jonathan A: Go the second route. wwwroot is simply there as the container for the default website for the server. If you delete the default website from within IIS, then you can safely remove this directory. Regardless, your sites have nothing to do with the default, so they should be in their own folders under inetpub. That said, we sometimes have multiple "types" of sites on the same server. For example DEV and QA. In this case I would structure it as: c:\inetpub\dev\site1 c:\inetpub\dev\site2 c:\inetpub\qa\site1 c:\inetpub\qa\site2 A: As variant: C:\WebSites\my.site1.com C:\WebSites\my.site2.com A: if you prefer you can put your application folder on desktop of your server. It is really up to you. You just need to make the proper configurations inside IIS and grant necessary access permissions to your folder. That's all. A: There is no definitive answer but * *C:\inetpub\wwwroot\Website1\ *C:\inetpub\wwwroot\Website2\ are the standard locations for web sites. For example c:\inetpub\ftproot could be used to host an FTP site.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "70" }
Q: jQuery highlight search term based on URL I am testing out the plugin "searchHighlight" to highlight search terms on our Search page when one searches for a keywords. The problem is that it only reads the referral URL and I do not know how to modify this so it only reads the current URL that your on instead of the referral. I.e. * *I use our search box from my home page *I search for 'glass door' *Results come up on the search page but no highlighting *I click a product with the words 'glass' or 'door' in it *On the product page it highlights the words I searched for ('glass' + 'door') Example URL Searched: http://tsqja.deznp.servertrust.com/SearchResults.asp?Search=glass+door&x=0&y=0 From the example I tried to give above you can see it is highlighting based off the Referral URL Keywords. I want it to use the actual search results. Given regex this is my search results page: [/^http:\/\/(tsqja\.)?deznp\.servertrust/i,/Search=([^&]+)/i] Anyone know how this can be achieved? Get highlighted search terms based off the above regex via jQuery preferably? A: Try the SearchHighlight plugin for jQuery. They have a demo page here A: Well, again it's not exactly the best solution...... but you could use this: if(document.referrer !== location.href) location.reload() That will reload the page if the current url is not the referrer. This will only run once provided the url is not constantly changed on page load. A: You can use the keys configuration option to set the highlighting up manually on the search page. You could use a small script to get the search term from the url using a regex, then pass the configuration into SearchHighlight: // Get the keys from the URL using a regex // http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript ... // Put the keys into the options var options = {keys: "Glass Door"} jQuery(document).SearchHighlight(options); Using the keys option completely disables the referrer checking.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529916", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Access table by offset (?) I have a 1000x1000 matrix, with some data in each entry. Is it possible to store it sequentially (ie, a row next to the previous one) in a table? I mean, if I could just access the table "by offset" (just like an array), given I won't add/delete any entry, I would save space for the key, which is blatantly redundant here. Is it possible? Thanks! A: Tables don't have an order. There is no sequence to them. The key is not redundant because it tells you how to access your data. If I were to model this I would do it like so: CREATE TABLE My_Matrix AS ( row_num SMALLINT NOT NULL, col_num SMALLINT NOT NULL, value INT NOT NULL, -- Or whatever data type is appropriate CONSTRAINT PK_My_Matrix PRIMARY KEY CLUSTERED (row_num, col_num), CONSTRAINT My_Matrix_row_num_chk CHECK (row_num BETWEEN 1 AND 1000), CONSTRAINT My_Matrix_col_num_chk CHECK (col_num BETWEEN 1 AND 1000) ) Now, if you want to get a value by row number and column number then you can quickly get that with: SELECT value FROM My_Matrix WHERE row_num = @row_num AND col_num = @col_num If you want to get it by an offset then you could use something like: SELECT value FROM My_Matrix WHERE row_num = @value%1000 AND col_num = @value/1000 As for saving storage, you're talking about 4 bytes per row here, with a matrix that has a maximum of 1M rows. For any serious RDBMS that's pretty irrelevant. A: A million rows is a reasonably small table so my starting assumption would be something like the following: CREATE TABLE tbl1 (x INT NOT NULL, y INT NOT NULL, ... some data ... , PRIMARY KEY (x,y));
{ "language": "en", "url": "https://stackoverflow.com/questions/7529921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: RVM Install bash script does nothing Trying to install RVM on Ubuntu 11.04 with no joy. I have installed Curl 7.22.0 When I run: bash < <(curl -s https://rvm.io/install/rvm) or bash < <(curl -sk https://rvm.io/install/rvm) from terminal, nothing happens, so if anybody has any suggestions A: Try doing curl -L https://get.rvm.io | bash -x I have personally verified this on RVM's testing cluster which tests against 4 different OSs as well as on OS X Lion. It works perfectly as does the multi-user installation. So something is going on in your environment on that machine. The -x will cause bash to output each command as its executing it. Also, you can do curl -L https://get.rvm.io -o rvm-installer ; chmod +x rvm-installer ; ./rvm-installer as detailed on the https://rvm.io/rvm/install/ page, just removing the --version x.x.x portion of the listed command there. This is not an issue, this is our default response when someone's environment is acting up. There's nothing wrong with the RVM installer at the moment. A: I got the same problem. sudo apt-get install git curl -y installed the version of curl that don't support ssl, so you need to uninstall it using sudo apt-get remove curl then install curl by downloading the latest package from here http://packages.ubuntu.com/natty/curl (for natty), use this link [curl_7.21.3.orig.tar.gz], tar -xvzf curl_7.21.3.orig.tar.gz cd curl_7.21.3 ./configure && make check for errors, and if all fine type sudo make install now ssl is working, so you can install rvm simply using curl -L https://get.rvm.io | bash
{ "language": "en", "url": "https://stackoverflow.com/questions/7529923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: FtpWebRequest.GetRequestStream() after disconnect I'm prototyping an ftp utility that will save a user's progress, and re-upload a given file from where they started if their internet were to disconnect. (It's for clients with slower connections). The idea is to open a file stream and ftp stream, and write to the ftp stream in chunks of memory. If an exception rises (i.e. an IOException from a disconnect), then the number of bytes written to the ftp server will be saved in a log file and read on start up. This code works great if the transaction is cancelled, but if the client is to disconnect, then the ftp stream is never cleaned up on the server end - so I receive... The remote server returned an error: (550) File unavailable (e.g., file not found, no access). When re-requesting the ftp stream for the given file. The code looks like //Create FTP Web Request reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(builder.ToString())); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.Method = WebRequestMethods.Ftp.UploadFile; reqFTP.UsePassive = true; reqFTP.UseBinary = false; reqFTP.KeepAlive = false; reqFTP.ContentLength = fileInf.Length; reqFTP.ReadWriteTimeout = 5000; reqFTP.Timeout = 5000; using (ProgressDialog progressDialog = new ProgressDialog()) { progressDialog.backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork); progressDialog.backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted); progressDialog.backgroundWorker1.FileName = filename; progressDialog.ShowDialog(); } } private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { FTPBackgroundWorker worker = sender as FTPBackgroundWorker; //Get file progress (if user canceled or crashed) worker.NumBytesRead = GetFileProgress(worker.FileName); reqFTP.ContentOffset = worker.NumBytesRead; const int buffLength = 2048; byte[] buff = new byte[buffLength]; int contentLen; using (worker.FileStream = fileInf.OpenRead()) { worker.FileStream.Position = worker.NumBytesRead; worker.FTPStream = reqFTP.GetRequestStream(); //Exception occurs while (true) { bool throwException = false; if (worker.CancellationPending) { e.Cancel = true; break; } contentLen = worker.FileStream.Read(buff, 0, buffLength); if (contentLen == 0) break; //write file to ftp stream worker.FTPStream.Write(buff, 0, contentLen); worker.NumBytesRead += contentLen; //For testing purposes if (throwException) throw new Exception("user disconnected!"); worker.ReportProgress((int)(((double)worker.NumBytesRead / fileInf.Length) * 100)); } worker.FileStream.Close(); worker.FTPStream.Close(); } } void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { FTPBackgroundWorker worker = sender as FTPBackgroundWorker; if (e.Error != null) { MessageBox.Show(String.Format("Error occured uploading {0}: {1}",worker.FileName, e.Error), "Error"); if (worker.FileStream != null) worker.FileStream.Close(); if (worker.FTPStream != null) worker.FTPStream.Close(); if(worker.NumBytesRead > 0) { MessageBox.Show("Progress has been saved", "Notification"); WriteToLogFile(worker.FileName, worker.NumBytesRead); } } else if (e.Cancelled) { if (worker.FileStream != null) worker.FileStream.Close(); if (worker.FTPStream != null) worker.FTPStream.Close(); MessageBox.Show("Upload Canceled", "Cancel"); if (worker.NumBytesRead > 0 && MessageBox.Show("Would you like to save your upload progress?", "Notification", MessageBoxButtons.YesNo) == DialogResult.Yes) WriteToLogFile(worker.FileName, worker.NumBytesRead); } else { RemoveFromLogFile(worker.FileName); MessageBox.Show("Upload Complete", "Success"); } } My question is: Is there a way to check if there's a handle on the server end that's not letting go of a file path and remove it? Or am I approaching the problem with the wrong methodology? Thanks A: Why not decrement the timeout to a value that will expire before the connection tries to be initialized again or make the user wait to try to start the connection again?
{ "language": "en", "url": "https://stackoverflow.com/questions/7529929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Protect call to remote php script * *I have on a server a PHP scrip that updates a DB. *I want to be able to call this script from remote, either from another server or my localhost PC using a GET, or from the browser using AJAX, *But I don't want anyone to be able to call this script unless allowed. So far I simply added into the script a piece of code to verify a certain pin in the GET, i.e. //myscript.php if( isset($_GET['pin']) && $_GET['pin'] === '1234' ) { //update the DB... In this way remote caller must know the pin, i.e. file_get_contents(http://remoteserver.com/myscrip.php?pin=1234); //will work file_get_contents(http://remoteserver.com/myscrip.php?pin=5678); //will NOT work This seems so simple that I'm wondering if it's secure. What are other possible more secure alternatives (maybe not too more complicated)? For instance, I read about using an hash that changes over time, but is it worth it, how could it be done? A: you could password protect the folder (can be done easy if you are using cpanel or plesk) and use curl to access that url. $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_USERPWD, $username . ':' . $password); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); $output = curl_exec($ch); $info = curl_getinfo($ch); curl_close($ch); A: Your solution is secure, but only up to a point, so it depends on just how important it is that others don't call it. For instance, if someone monitored the network traffic to that server, they would have the password, since it never changes. Remember it's being sent in cleartext over the Internet. So I personally would not have this PHP script update my Swiss bank account. One option would be to have an algorithmic password based on the date and/or time so it would be different each time. Another solution would be to have the script check the IP address of the request, which would be MUCH harder to hack without physical access to the server. A: you can use Basic Authentication A: The one problem with your example is that it would be collected by a browser's history collector. So if you typed in this GET at home , and the next day your kid starts typing "rem...", the browser will display the URL and your lone credential. If updating your database is not a destructive thing (it wouldn't be the worst if it happened an extra time or two), and you are relatively careful and disciplined (clear history each time), then this isn't too bad. Since you're using PHP, you should look at PHP's preferred way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Capture click event in ItemsControl item This is a Windows Phone 7 Silverlight app. I have an ItemsControl that is displaying a scrolling list. I'm using a Grid as the container in the ItemTemplate. I want to capture a click event (touch) on the Grid to navigate to a details view for the item clicked. However, the only events I see available to me are mouse events that are also being used in scrolling. I'm more familiar with Android programming in which the framework differentiates a scroll event and a click event for me. How do I do the same on WP7? I want to ignore touch events when they're associated with scrolling but capture click events that are actual clicks by the user. The manual way is to handle MouseLeftButtonUp and just set a flag when scrolling that tells me to ignore the event, but I'd love to avoid having to write that myself every time I need to display a list. I would think this is a very common use case that has an easy solution. SOLUTION Matt's answer below worked, but here's a full description of how I got it to work for those who google this in the future. * *Download and install Silverlight Toolkit for WP7: http://silverlight.codeplex.com/releases/view/60291 *Add reference to Microsoft.Phone.Controls.Toolkit.dll in project *Include the toolkit namespaces *Add a GestureListener to the item that should receive tap events: Namespaces to add to pages and controls that need this functionality: xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit" xmlns:toolkitPrimitives="clr-namespace:Microsoft.Phone.Controls.Primitives;assembly=Microsoft.Phone.Controls.Toolkit" Updated list xaml (abbreviated): <ItemsControl ItemsSource="{Binding FeedItems}"> <ItemsControl.ItemTemplate> <DataTemplate> <!-- Container --> <Grid HorizontalAlignment="Stretch"> <toolkit:GestureService.GestureListener> <toolkit:GestureListener Tap="OnFeedItemTap" /> </toolkit:GestureService.GestureListener> A: If you're using the latest tools/targetting 7.1 (mango) devices then you can use the Tap event on the Grid. If you're still targetting 7.0 then you could use the Click event or use the GestureListener in the Toolkit to detect taps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529940", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Beanbinding vetoableChangeSupport addVetoableChangeListener Any one can tell what vetoableChangeSupport.addVetoableChangeListener is. I found this in Beansbinding. What vetoableChangeSupport.addVetoableChangeListener is for and its uses.Also you can go here. How can we get make use of it in beansbinding and application developing? Thank you A: From the JavaDoc: You can register a VetoableChangeListener with a source bean so as to be notified of any constrained property updates. And from the JavaDoc on the vetoableChange(...) method: PropertyVetoException - if the recipient wishes the property change to be rolled back. This indicates you use the VetoableChangeListener to listen for property changes and if a change would violate a constraint you impose through that listener, it throws a PropertyVetoException which should cause the change to be rolled back. Here's the JavaDoc for VetoableChangeSupport which includes examples: http://download.oracle.com/javase/7/docs/api/java/beans/VetoableChangeSupport.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7529941", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Close popover - Objective-c Good Day, I'm having a problem to close a popover after selecting a line (UITableView). I've tried the following methods, but were unsuccessful. [self dismissModalViewControllerAnimated:YES]; iMAPClientesPesquisar *a = [[iMAPClientesPesquisar alloc] init]; [a.popover dismissPopoverAnimated:YES]; I'm calling my popover as follows: - (IBAction)Filtro:(id)sender { iMAPClientesFiltro *ClientesFiltro = [[iMAPClientesFiltro alloc] init]; popover = [[UIPopoverController alloc] initWithContentViewController:ClientesFiltro]; [ClientesFiltro release]; [popover setPopoverContentSize:CGSizeMake(132, 132)]; [popover presentPopoverFromBarButtonItem:sender permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES]; } Any suggestion will be greatly appreciated. A: If you are trying to close the popover from the same view controller that the Filtro method is in (or in other words, popover would be an variable visible from within that class), you should be able to drop the "a." from your above line and just do: [popover dismissPopoverAnimated:YES]; A: The only way to dismiss the popover is to have a reference to the popover that is open. I'm a little confused why you are calling [self dismissModalViewControllerAnimated:YES]; as that has nothing to do with a UIPopoverController. You need to use the original popover reference to dismiss the popover. Something like [popover dimissPopoverAnimated:YES]; since popover appears to be a member variable of the object that had the function that originally opened the popover.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529942", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to display a confirmation box when I click a checkbox inside a datatable in websphere jsf portlet without using java script I am developing a websphere jsf portlet where I need to display a confirmation box when a check box inside dataTabale is clicked. All selected items will be updated in the database. I am avoiding pop up but since the user wants the program to be flexible enough to let them do the update in special occasions so all I can do is to double check with the user. But definitely w/o using javascript. I am using jsr 168 portlet and JSf 1.2 with IBM RAD 7.5 Thanks A: Well, this one is simple: you can't. Without Javascript you can not react to anything else than sending a form (by clicking a button or - if there is only one text input - pressing enter) or clicking a link. So unless you change the question - the answer is: what you want is impossible.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MongoDB dot notation when updating Answer: It was only a bug of 1.4.4. Upgrade to 2.0 has solved the problem. I have the following object in Mongo: { _id: "foo", bar: "baz", list: { 42: { some: "prop" } } } I want to add in the "list" a key 43, so I'm doing the following: db.collection.update({ _id: "foo" }, { $set: { "list.43": { some: "other prop" } } }) Everything is fine, but the 43 with new subobject became the only key in list property. Why? Why has 42 gone? Expected result: { _id: "foo", bar: "baz", list: { 42: { some: "prop" }, 43: { some: "other prop" } } } Real result: { _id: "foo", bar: "baz", list: { 43: { some: "other prop" } } } Update: In fact, the question is how to add a key into a nested object in one atomic call? A: That should work. Maybe you deleted it previously with a wrong update? Try it again.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's the best practice for handling mostly static data I want to use in all of my environments with Rails? Let's say for example I'm managing a Rails application that has static content that's relevant in all of my environments but I still want to be able to modify if needed. Examples: states, questions for a quiz, wine varietals, etc. There's relations between your user content and these static data and I want to be able to modify it live if need be, so it has to be stored in the database. I've always managed that with migrations, in order to keep my team and all of my environments in sync. I've had people tell me dogmatically that migrations should only be for structural changes to the database. I see the point. My counterargument is that this mostly "static" data is essential for the app to function and if I don't keep it up to date automatically (everyone's already trained to run migrations), someone's going to have failures and search around for what the problem is, before they figure out that a new mandatory field has been added to a table and that they need to import something. So I just do it in the migration. This also makes deployments much simpler and safer. The way I've concretely been doing it is to keep my test fixture files up to date with the good data (which has the side effect of letting me write more realistic tests) and re-importing it whenever necessary. I do it with connection.execute "some SQL" rather than with the models, because I've found that Model.reset_column_information + a bunch of Model.create sometimes worked if everyone immediately updated, but would eventually explode in my face when I pushed to prod let's say a few weeks later, because I'd have newer validations on the model that would conflict with the 2 week old migration. Anyway, I think this YAML + SQL process works explodes a little less, but I also find it pretty kludgey. I was wondering how people manage that kind of data. Is there other tricks available right in Rails? Are there gems to help manage static data? A: In an app I work with, we use a concept we call "DictionaryTerms" that work as look up values. Every term has a category that it belongs to. In our case, it's demographic terms (hence the data in the screenshot), and include terms having to do with gender, race, and location (e.g. State), among others. You can then use the typical CRUD actions to add/remove/edit dictionary terms. If you need to migrate terms between environments, you could write a rake task to export/import the data from one database to another via a CSV file. If you don't want to have to import/export, then you might want to host that data separate from the app itself, accessible via something like a JSON request, and have your app pull the terms from that request. That seems like a lot of extra work if your case is a simple one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529963", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Sending screenshot via C# I'm saving by capturing screenshot via that code. Graphics Grf; Bitmap Ekran = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppPArgb); Grf = Graphics.FromImage(Ekran); Grf.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy); Ekran.Save("screen.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); Then send this saved screenshot as e-mail: SmtpClient client = new SmtpClient(); MailMessage msg = new MailMessage(); msg.To.Add(kime); if (dosya != null) { Attachment eklenecekdosya = new Attachment(dosya); msg.Attachments.Add(eklenecekdosya); } msg.From = new MailAddress("aaaaa@xxxx.com", "Konu"); msg.Subject = konu; msg.IsBodyHtml = true; msg.Body = mesaj; msg.BodyEncoding = System.Text.Encoding.GetEncoding(1254); NetworkCredential guvenlikKarti = new NetworkCredential("bbbb@bbbb.com", "*****"); client.Credentials = guvenlikKarti; client.Port = 587; client.Host = "smtp.live.com"; client.EnableSsl = true; client.Send(msg); I want to do this : How can I send a screenshot directly as e-mail via smtp protocol without saving? A: Save the Bitmap to a Stream. Then attach the Stream to your mail message. Example: System.IO.Stream stream = new System.IO.MemoryStream(); Ekran.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); stream.Position = 0; // later: Attachment attach = new Attachment(stream, "MyImage.jpg"); A: Use this: using (MemoryStream ms = new MemoryStream()) { Ekran.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); using (Attachment att = new Attachment(ms, "attach_name")) { .... client.Send(msg); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7529968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Can't view any calendar view Has anyone seen it where a user cannot view any calendar views across site collections? He can see all the events in standard list view format, but any calendar-type view only shows the month and no events. Could this be an IE issue? A: This one took a little bit of thought. The user could access calendar views on other machines, so I had the user repair his MS Office Profile and reboot. That did the trick, as he was then able to see any calendar view across any site collection.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529969", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cookie doesn't store information in php? Why Cookies doesn't store information in php ? even in this simple code .. <? setcookie("test","Cookies teso"); echo "My cookie value: ".$_COOKIE["test"]; ?> A: They will be available on the next page load. From the documentation: Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);. Note that you need to set the cookies before any other script output is done: Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including and tags as well as any whitespace. A: page needs to be refreshed. $_COOKIE has the cookies from your browser from the start of the execution of the script. setcookie() sets the information in the browser, but that info isn't yet in the $_COOKIE array. it will be at the next page load, though
{ "language": "en", "url": "https://stackoverflow.com/questions/7529975", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Subversion: Get ip-address of user in pre-commit hook? We're hosting a subversion repository for distrubuted software development. So non-employees have access to some of our sorce code. Our company's IT security policy requires us to virusscan all files uploaded from outside of our corporate intranet. All internal computers are equipped with up to date virus scanners. We're planning on integration the virus scan in a Subversion precommit-hook. But this causes delays when performing large commits. So we would like to scan only the commits, that are originated outside of our intranet. To identify the origin, we need the IP adress of the user performing the commit. Since some of our employees work from home we can't use the usernames to identify commits from the internet. Thus finally my question: How can I get the IP-adress from which a commit ist performed in a subversion precommit hook? A: Let me imagine that you write your hook in Perl, in that case, you can use the following lib : DocumentationClientIP you can install the lib from Git thru this link : GITClientIP (or use the code included). After installation, you need to add something like that in your code : use SVN::Utils::ClientIP qw(ssh_client_ip); print "The client's IP address is ", ssh_client_ip(); A: I'm using lsof (bash-script pre-commit): srcip=$(/usr/sbin/lsof -Pn -p $PPID | grep ESTABLISHED) or, to get only the IP: srcip=$(/usr/sbin/lsof -Pn|grep ssh|grep ESTA|cut -d\> -f 2|cut -d: -f 1) While client connects to server, pre-commit is executed. lsof shows all open files (including TCP connections etc); I select all "files" for this process (-p $PPID) and grep for ESTABLISHED (this is the connection between client and server).
{ "language": "en", "url": "https://stackoverflow.com/questions/7529976", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jquery performing a selector on an element variable I'm having difficulty with performing a selector operation on an element variable. First I'm selecting my table element in my page using jquery. var $popup = null; $popup = $("#popup_List"); <div id="popup" class="popup_block"> <table id="popup_List"><tr><td>Name</td></tr></table> </div> I'm trying to perform a selector operation on the $popup variable. The following does not work $popup("tr:last").after("<tr><td>Name</td></tr"); I'd like to use the variable approach because $("#popup_List") would have to be referenced numerous times in the code otherwise. A: var last = $("tr:last", popup); just pass in the context for the jquery() method. A: $popup.find("tr:last").after("<tr><td>Name</td></tr"); A: You don't need to prefix with $ on your variable, only when you are instantiating the jquery object: var popup = $("#popup_List"); var last = popup.find("tr:last"); By the way, it is odd that you have the 'L' in List capitalized. This might lead to bugs, so I'd go with popup_list for consistency.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529982", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: jquery global var? how to do this? Okay I have this above my validation: var error = true; Below this all of my validation takes place, for example: /* FIRST NAME VALIDATION */ $("#firstname").change(function () { var firstname = $('#firstname').val(); if (firstname == ""){ $('#firstname').css({"border-color":"#3399ff"}); $('#firstname-err').html("You must enter your first name.").removeClass("success_msg").addClass("error_msg"); error = true; }else{ $('#firstname-err').html("Thank you " + firstname + ", thats perfect!").removeClass("error_msg").addClass("success_msg");; $('#firstname').css({"border-color":"#1f6d21"}); error = false; } }); and I have this at the bottom of my validation if(error == true) { $('#btn-join').css({"opacity":"0.4"}); $('#btn-join').attr("disabled", true); } else { $('#btn-join').css({"opacity":"1"}); $('#btn-join').attr("disabled", false); } Basically, I want it to run through each one and if they are all false, the submit button becomes enabled. How do I go about doing this? I'm fairly new to jQuery so sorry if I didn't make sense. A: All you have to do to get a global var in JavaScript or jQuery is to declare it at the broadest scope, then refer to it again (without the var keyword). I usually declare these variables before my jQuery ready() function. That should let you access the variable throughout the document in your scripts. Just make sure that you don't re-declare the variable with var or you'll get a localized version of it. One note on your logic - I am assuming that you're validating more than one field. Since any of these fields may set the error variable to true, you're going to want to avoid setting it to false on individual validation tests. Here's what I'd do: * *Declare the error variable outside the jQuery code. *When your validation function starts, initialize error to false. *Run each field's validation test. If the test fails, mark it visually for the user and set error to true. If the test passes, don't change the value of error. *Repeat for each field's test. *When all tests are finished, test the value of error to see if all the tests passed or if you have an error. Act accordingly. I hope that helps. A: Bind the change event to the form, then all of your form fields will trigger it. In that function validate all of the data. That way, whenever any value in the form is changed, the button will be updated with the correct state. A: I'm not really sure what your problem is here, or what you're asking. As far as the scope of the variable is concerned, as long as you declare it before the block of code then it should be in scope in your jquery code. I can forsee some problems with your method though. I would initially set var error = false;. You don't have any errors before you've started. Then you don't need to set error = false; anywhere in the code. If you do this then you're negating any time you've changed it to true before in the script. Lets say you validate first name and then second name afterwards. First name has an error so you set error = true. Second name doesn't have an error, so you set error = false. This will then confuse you because you've forgotten that there was an error with first name. Lastly an even better way to do it would be to set var error = '';. Then as you go through do: error += 'You need to fill in your first name.<br />'; or similar. That way when you get to the end instead of seeing if error === true you can see if error != ''. If that evaluates to true then you can output the error which will be contained in the error variable which will be an amalgamation of all the errors you've encountered throughout the running of the script. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: disable or lock mouse and keyboard in Python? Is there a way of disabling or locking mouse and keyboard using python? I want to freeze the mouse and disable the keyboard. A: Totally different take since all the solutions mentioned above use a quiet outdated library(pyhook) and this pyhook method personally didnt work for me. import keyboard from pynput.mouse import Controller from time import sleep def blockinput(): global block_input_flag block_input_flag = 1 t1 = threading.Thread(target=blockinput_start) t1.start() print("[SUCCESS] Input blocked!") def unblockinput(): blockinput_stop() print("[SUCCESS] Input unblocked!") def blockinput_start(): mouse = Controller() global block_input_flag for i in range(150): keyboard.block_key(i) while block_input_flag == 1: mouse.position = (0, 0) def blockinput_stop(): global block_input_flag for i in range(150): keyboard.unblock_key(i) block_input_flag = 0 blockinput() print("now blocking") sleep(5) print("now unblocking") A: I haven't tested (actually I've tested the mouse part, and it annoyingly works) but something like this using pyhook would do what you want: import pythoncom, pyHook def uMad(event): return False hm = pyHook.HookManager() hm.MouseAll = uMad hm.KeyAll = uMad hm.HookMouse() hm.HookKeyboard() pythoncom.PumpMessages() A: I just slightly modified the @Robert code and instead of the time I used external interrupt to close the program i.e. if you connect any external drive then the program gets close and your mouse and keyboard will be working perfectly. import pyHook from threading import Timer import win32gui import logging import win32file def locate_usb():#this will check any external Drives drive_list = [] drivebits = win32file.GetLogicalDrives() # print(drivebits) for d in range(1, 26): mask = 1 << d if drivebits & mask: # here if the drive is at least there drname = '%c:\\' % chr(ord('A') + d) t = win32file.GetDriveType(drname) if t == win32file.DRIVE_REMOVABLE: drive_list.append(drname) return drive_list class blockInput(): def OnKeyboardEvent(self,event): return False def OnMouseEvent(self,event): return False def unblock(self): try: self.hm.UnhookKeyboard() except: pass try: self.hm.UnhookMouse() except: pass def block(self ,keyboard = True, mouse = True): while(1): if mouse: self.hm.MouseAll = self.OnMouseEvent self.hm.HookMouse() if keyboard: self.hm.KeyAll = self.OnKeyboardEvent self.hm.HookKeyboard() win32gui.PumpWaitingMessages() cg= locate_usb() if cg: break def __init__(self): self.hm = pyHook.HookManager() if __name__ == '__main__': block = blockInput() block.block() block.unblock() I hope this code will help you A: Since 2018, you can now use pynput (v1.4+) to suppress keyboard and mouse events on Windows, Mac, and Linux. import pynput # Disable mouse and keyboard events mouse_listener = pynput.mouse.Listener(suppress=True) mouse_listener.start() keyboard_listener = pynput.keyboard.Listener(suppress=True) keyboard_listener.start() # Enable mouse and keyboard events mouse_listener.stop() keyboard_listener.stop() This also disables mouse scrolling and clicking. However, this does not stop users from pressing Ctrl+Alt+Del on Windows. But you can run the script in an elevated command prompt, and the mouse and keyboard will still be disabled, even if they opened Task Manager using Ctrl+Alt+Delete, so there is no harm done (apparently there are way to actually prevent Ctrl+Alt+Delete, but do your own research for that) A: I have extended Fábio Diniz's answer to a class which provides both a block() and an unblock() function which block (selectively) mouse/keyboard inputs. I also added a timeout functionality which (hopefully) addresses the annoyance of locking oneself out. import pyHook from threading import Timer import win32gui import logging class blockInput(): def OnKeyboardEvent(self,event): return False def OnMouseEvent(self,event): return False def unblock(self): logging.info(" -- Unblock!") if self.t.is_alive(): self.t.cancel() try: self.hm.UnhookKeyboard() except: pass try: self.hm.UnhookMouse() except: pass def block(self, timeout = 10, keyboard = True, mouse = True): self.t = Timer(timeout, self.unblock) self.t.start() logging.info(" -- Block!") if mouse: self.hm.MouseAll = self.OnMouseEvent self.hm.HookMouse() if keyboard: self.hm.KeyAll = self.OnKeyboardEvent self.hm.HookKeyboard() win32gui.PumpWaitingMessages() def __init__(self): self.hm = pyHook.HookManager() if __name__ == '__main__': logging.basicConfig(level=logging.INFO) block = blockInput() block.block() import time t0 = time.time() while time.time() - t0 < 10: time.sleep(1) print(time.time() - t0) block.unblock() logging.info("Done.") You can have a look at the main routine for example usage. A: For me, just two lines of programming solved the problem: from ctypes import * ok = windll.user32.BlockInput(True) #enable block #or ok = windll.user32.BlockInput(False) #disable block A: You can use pyautogui to do this. Though I recommend adding keyboard for making a stopping key. First, you want to install pyautogui and keyboard. Please note: this only disables the mouse not the keyboard, that is a very bad idea. pip install pyautogui pip install keyboard Ok, with that sorted, we have to actually make the disabler. import pyautogui import keyboard stopKey = "s" #The stopKey is the button to press to stop. you can also do a shortcut like ctrl+s maxX, maxY = pyautogui.size() #get max size of screen While True: if keyboard.is_pressed(stopKey): break else: pyautogui.moveTo(maxX/2, maxY/2) #move the mouse to the center of the screen Ok, but there is 2 ways to get out of this. pressing S, and also quickly moving the mouse to one of the corners of the screen (that is a pyautogui failsafe, but we can disable that). If you want to disable the failsafe, add this after the imports: pyautogui.FAILSAFE = False Please note that disabling the failsafe is NOT recommended! Ok, so now the only way to exit is the S key. If you want to stop this somewhere else in your program, do this: pyautogui.press(stopKey) Ok, so its not perfect, but it will stop you from doing basically anything with your mouse.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: Encrypt an integer to get only numeric characters in JAVA I have a database id that start from 1 to ... and I need encrypt this number to use for pursuit number. how to generate numeric string by encrypting the database id and decrypt it? pursuit number must be short as possible. A: How secure do you need this encryption to be? A simple XOR with another int might be what you need, though you might have to be careful with sign bits. Alternatively, if you want something more secure, just implement a simple 32 bit Feistel cypher. Here's one I prepared earlier: /** * IntegerPerm is a reversible keyed permutation of the integers. * This class is not cryptographically secure as the F function * is too simple and there are not enough rounds. * * @author Martin Ross */ public final class IntegerPerm { ////////////////// // Private Data // ////////////////// /** Non-zero default key, from www.random.org */ private final static int DEFAULT_KEY = 0x6CFB18E2; private final static int LOW_16_MASK = 0xFFFF; private final static int HALF_SHIFT = 16; private final static int NUM_ROUNDS = 4; /** Permutation key */ private int mKey; /** Round key schedule */ private int[] mRoundKeys = new int[NUM_ROUNDS]; ////////////////// // Constructors // ////////////////// public IntegerPerm() { this(DEFAULT_KEY); } public IntegerPerm(int key) { setKey(key); } //////////////////// // Public Methods // //////////////////// /** Sets a new value for the key and key schedule. */ public void setKey(int newKey) { assert (NUM_ROUNDS == 4) : "NUM_ROUNDS is not 4"; mKey = newKey; mRoundKeys[0] = mKey & LOW_16_MASK; mRoundKeys[1] = ~(mKey & LOW_16_MASK); mRoundKeys[2] = mKey >>> HALF_SHIFT; mRoundKeys[3] = ~(mKey >>> HALF_SHIFT); } // end setKey() /** Returns the current value of the key. */ public int getKey() { return mKey; } /** * Calculates the enciphered (i.e. permuted) value of the given integer * under the current key. * * @param plain the integer to encipher. * * @return the enciphered (permuted) value. */ public int encipher(int plain) { // 1 Split into two halves. int rhs = plain & LOW_16_MASK; int lhs = plain >>> HALF_SHIFT; // 2 Do NUM_ROUNDS simple Feistel rounds. for (int i = 0; i < NUM_ROUNDS; ++i) { if (i > 0) { // Swap lhs <-> rhs final int temp = lhs; lhs = rhs; rhs = temp; } // end if // Apply Feistel round function F(). rhs ^= F(lhs, i); } // end for // 3 Recombine the two halves and return. return (lhs << HALF_SHIFT) + (rhs & LOW_16_MASK); } // end encipher() /** * Calculates the deciphered (i.e. inverse permuted) value of the given * integer under the current key. * * @param cypher the integer to decipher. * * @return the deciphered (inverse permuted) value. */ public int decipher(int cypher) { // 1 Split into two halves. int rhs = cypher & LOW_16_MASK; int lhs = cypher >>> HALF_SHIFT; // 2 Do NUM_ROUNDS simple Feistel rounds. for (int i = 0; i < NUM_ROUNDS; ++i) { if (i > 0) { // Swap lhs <-> rhs final int temp = lhs; lhs = rhs; rhs = temp; } // end if // Apply Feistel round function F(). rhs ^= F(lhs, NUM_ROUNDS - 1 - i); } // end for // 4 Recombine the two halves and return. return (lhs << HALF_SHIFT) + (rhs & LOW_16_MASK); } // end decipher() ///////////////////// // Private Methods // ///////////////////// // The F function for the Feistel rounds. private int F(int num, int round) { // XOR with round key. num ^= mRoundKeys[round]; // Square, then XOR the high and low parts. num *= num; return (num >>> HALF_SHIFT) ^ (num & LOW_16_MASK); } // end F() } // end class IntegerPerm A: how about convert the Integer (DEC) -> Octal? well, 1-7 will not be 'encrypted' in this way. A: You can get a nice cryptographically-secure random number generator, add a table to the database that relates IDs to their encrypted versions, and you're set. Just generate a random number for each ID, ensure it's not already being used as an encrypted version of some other ID, and voila. This will foil anyone who tries to crack the scheme you use, since you're effectively not using one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: PHP character encoding � sign instead of à Hi this is a very strange error I have on some pages of this joomla website: http://www.pcsnet.it/news If you go into the details of a specific news the à character is correctly displayed. Other accented characters seem not affected. I've checked that UTF-8 encoding is default both in the MySql db and that the text files are in UTF-8 encoding. Other ideas? A: What is very interesting in your case is that it only affects the letter à! So it cannot be an encoding problem. Here is my take on your problem. The letter à is encoded in two bytes in utf8. The first byte is xC3, which is à in latin-1, the second byte is... non breaking space! (The other accented letters, such as è are encoded by à followed by an other accented letter in latin-1, and they are not affected). Therefore, my guess is that you have a script, somewhere, that removes, or replaces, the non-breaking space in latin-1, i.e., character xA0. The resulting lonely byte xC3 cannot be displayed properly, so the general placeholder � is displayed instead. (just load your page in latin-1, you will see that I am right). Find that script that removes non-breaking spaces, and you'll be fine. A: Are you by any chance using htmlentities, htmlspecialchars or html_entity_decode on the text you retrieved from the database ? If so, you need to force UTF8 in the third parameter because it's not the default charset of these functions. Example: htmlentities('£hello', null, 'utf-8'); A: A � sign is usually an indication that the character the browser is trying to display is not available in the font used. It's probably not an à, if that works on other pages (using the same font).
{ "language": "en", "url": "https://stackoverflow.com/questions/7529996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Compare the nearest cells I need to compare one cell with next and if next is greater more than 3 than first, than to make it's color. example: 1 2 6 3 2 8 1 compare with 2 = do not do nothing 2 compare with 6 = make it's color 6 compare with 3 = make it's color to 3 compare with 2 = do not do nothing 2 compare with 8 = make it's color. Here is code that make cells less then 4 color, but I can't understand how to diff one cell with next :( Sub Color() Dim i As Integer For i = 1 To 7 With ActiveSheet.Cells(i) If .Value < 4 Then .Interior.Color = QBColor(10) End If End With Next i End Sub Upd: Oh! Look like I have found solution! Sub Color() Dim i As Integer For i = 1 To 7 With ActiveSheet.Cells(i) If ActiveSheet.Cells(i) < ActiveSheet.Cells(i + 1) Then ActiveSheet.Cells(i + 1).Interior.Color = QBColor(10) End If End With Next i End Sub A: You could use conditional formatting for this rather than VBA, Debra covers this topic thoroughly here, http://www.contextures.com/xlcondFormat01.html In your case: * *Select A1:E1 *Conditional Formatting ... New Rule (different menu options depending on your Excel version) *Use a formula to determine what cells to format *use =B1-A1>3 to add a relative formula *Pick a fill colour screenshot from xl2010 below
{ "language": "en", "url": "https://stackoverflow.com/questions/7530001", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Flip flopping data tables in Postgres I have a table of several million records which I am running a query against and inserting the results into another table which clients will query. This process takes about 20 seconds. How can I run this query, building this new table without impacting any of the clients that might be running queries against the target table? For instance. I'm running BEGIN; DROP TABLE target_table; SELECT blah, blahX, blahY INTO target_table FROM source_table GROUP BY blahX, blahY COMMIT; Which is then blocking queries to: SELECT SUM(blah) FROM target_table WHERE blahX > x In the days of working with some SQL Server DBA's I recall them creating temporary tables, and then flipping these in over the current table. Is this doable/practical in Postgres? A: What you want here is to minimize the lock time, which of course if you include a query (that takes a while) in your transaction is not going to work. In this case, I assume you're in fact refreshing that 'target_table' which contains the positions of the "blah" objects when you run your script is that correct ? BEGIN; CREATE TEMP TABLE temptable AS SELECT blah, blahX, blahY FROM source_table GROUP BY blahX, blahY COMMIT; BEGIN; TRUNCATE TABLE target_table INSERT INTO target_table(blah,blahX,blahY) SELECT blah,blahX,blahY FROM temptable; DROP TABLE temptable; COMMIT; As mentioned in the comments, it will be faster to drop the index's before truncating and create them anew just after loading the data to avoid the unneeded index changes. For the full details of what is and is not possible with postgreSQL in that regard : http://postgresql.1045698.n5.nabble.com/ALTER-TABLE-REPLACE-WITH-td3305036i40.html A: There's ALTER TABLE ... RENAME TO ...: ALTER TABLE name RENAME TO new_name Perhaps you could select into an intermediate table and then drop target_table and rename the intermediate table to target_table. I have no idea how this would interact with any queries that may be running against target_table when you try to do the rename. A: You can create a table, drop a table, and rename a table in every version of SQL I've ever used. BEGIN; SELECT blah, blahX, blahY INTO new_table FROM source_table GROUP BY blahX, blahY; DROP TABLE target_table; ALTER TABLE new_table RENAME TO target_table; COMMIT; I'm not sure off the top of my head whether you could use a temporary table for this in PostgreSQL. PostgreSQL creates temp tables in a special schema; you don't get to pick the schema. But you might be able to create it as a temporary table, drop the existing table, and move it with SET SCHEMA. At some point, any of these will require a table lock. (Duh.) You might be able to speed things up a lot by putting the swappable table on a SSD.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error when using FileSize(F) in Delphi 2010 I'm writing an application to log microscope usage but the following piece of code generates an error E2010 incompatible types "WideString' and "TDataFile" at the line that reads: SetLength(Items, FileSize(F)); I have narrowed down the problem to FileSize(F), just a number instead gives no error and trying to assign i := fileSize(F); where i is an integer gives the same error. type TData = record Status : integer; // 0=operational 1=maintenance 2=fault OperatorName : string[255]; Client : string[255]; Specimen : string[255]; Memo : string[255]; TEM : TTEM; SEM : TSEM; FIB : TFIB; StartTime : string[22]; // YYYY/MM/DD HH:MM:SS AM FinishTime : string[22]; DataFileName : string[255]; end; TDataFile = File of TData; TDataArray = array of TData function LoadAllData(FileName: string; var Items: TDataArray):boolean; // Loads contents of Datafile into Items and returns true if successful else false var F : TDataFile; i : integer; begin AssignFile(F, FileName); try try Reset(F); SetLength(Items, FileSize(F)); // This is the problem line for i := 0 to High(Items) do Read(F, Items[i]); LoadAllData := true; except LoadAllData := false; end; finally CloseFile(F); end; end; I'm using delphi 2010 on Win7 64bit. Does anyone know why this is happening? Writing a small console app just to test i := FileSize(F); works without a problem.... A: It seems that you have a function called FileSize declared in another unit or part of your code, something like function FileSize(const f : WideString):integer; begin // end; to resolve the issue, add the unit name of the function (in this case System) before the function name to explicitly call the FileSize function. SetLength(Items, System.FileSize(F));
{ "language": "en", "url": "https://stackoverflow.com/questions/7530004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can I log an exception thrown and caught in 3rd-party (external) library? My application uses some third-party libraries. I need to log some exceptions that occur inside lib (e.g. exceptions about read file), but these exceptions are caught in the same library. Is there some way I can log these exceptions myself, even if they're not logged by the library? A: Look at AspectJ. You can write an advice around construction (and maybe even thrwoing) of the FileNotFoundException. Be advised though, that it will log every time the the pointcut is reached. With some expertise you will be able to control it. EDIT: Dave Newtwon pointed at at this example which shows how easy it is to do this once you get the hang of it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: javascript - replacing spaces with a string I'm new to Javascript and need a bit of help with program on a college course to replace all the spaces in a string with the string "spaces". I've used the following code but I just can't get it to work: <html> <body> <script type ="text/javascript"> // Program to replace any spaces in a string of text with the word "spaces". var str = "Visit Micro soft!"; var result = ""; For (var index = 0; index < str.length ; index = index + 1) { if (str.charAt(index)= " ") { result = result + "space"; } else { result = result + (str.charAt(index)); } } document.write(" The answer is " + result ); </script> </body> </html> A: For isn't capitalized: for and str.charAt(index)= " " needs to be: str.charAt(index) == " " JavaScript Comparison Operators for loops A: As others have mentioned there are a few obvious errors in your code: * *The control flow keyword for must be all lower-case. *The assignment operator = is different than the comparison operators == and ===. If you are allowed to use library functions then this problem looks like a good fit for the JavaScript String.replace(regex,str) function. A: Try this: str.replace(/(\s)/g, "spaces") Or take a look at this previous answer to a similar question: Fastest method to replace all instances of a character in a string Hope this help A: Another option would be to skip the for cycle altogether and use a regular expression: "Visit Micro soft!".replace(/(\s)/g, ''); A: You should use the string replace method. Inconvenienty, there is no replaceAll, but you can replace all anyways using a loop. Example of replace: var word = "Hello" word = word.replace('e', 'r') alert(word) //word = "Hrllo" The second tool that will be useful to you is indexOf, which tells you where a string occurs in a string. It returns -1 if the string does not appear. Example: var sentence = "StackOverflow is helpful" alert(sentence.indexOf(' ')) //alerts 13 alert(sentence.indexOf('z')) //alerts -1
{ "language": "en", "url": "https://stackoverflow.com/questions/7530008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Editing an animated GIF I'd like to edit an animated gif to change its background from white to #f5f5f5: Photoshop can import it and shows as layers, but saves only the first frame. Are there any editors, preferably online tools that allows it? Many thanks for your help! A: Graphics Gale is used by a lot of pixel art guys, it is rather good for working with animated GIFs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Validating iphone receipt from c++ I'm trying to validate an iphone receipt from a c++ server (I have the receipt encrypted with base64, I'm composing a json object according to apple docs, and then I open a socket to the sandbox and send a POST request). The server responds with error 503 Service Unavailable. I suspect that I don't compose the POST request correctly.Does anyone know how should look the POST request for the apple store ? Thanks A: I solved the problem, in this case the problem was that I was using the http instead of https.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Apache Velocity foreach loop #continue Is there a #continue command for jump to next iteration in foreach loop? A: Based on the documentation, Apache Velocity does not appear to have a #continue function for its foreach loop. In case it might help, it does have a foreach break directive, added in 2008. A: I have a bunch of velocity code but I don't think I've ever seen this. I believe you have to use a #foreach and then use and #if to check your skip condition within the loop. The VTL guide doesn't seem have a better approach.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: Auto-building a native install AIR app I'm developing an AIR application that will be run on both OSX and Windows (it's part of an internal tool chain). Part of the functionality of the application requires shelling out to external processes, so I've created a native installer package to get access to NativeProcess. The app also needs to automatically update when a new version is available, so I've used the NativeApplicationUpdater library. I'd like to set up automated builds of the app. Unfortunately, it looks like building a native installer for a particular OS requires you to build it on that OS, making automated builds of both OSX and Windows versions impossible (at least on the same build machine). If I could set up automated builds of a .air file, and then use that to update the native install, that would fit my workflow perfectly. My question is: is that possible? If not, are there any alternatives when it comes to auto-building a native install app? A: Yes, you can build a native installer from the .air file: adt -package -target EXE or DMG NATIVE_SIGNING_OPTIONS (windows only and optional) output input_package See http://help.adobe.com/en_US/air/build/WS901d38e593cd1bac1e63e3d128cdca935b-8000.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7530023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: dismiss the UIKeyboardTypeDecimalPad in UIScrollView background I am dealing with what seems to be a somewhat rudimentary problem. I am trying to dismiss a UIKeyboardTypeDecimalPad that has a UIScrollView background. I have seen some solutions that involve putting a done button where the decimal is if you have just a NumberPad. The problem is, I really need a decimal. My next thought was to dismiss the keypad when the user touches the background, but since the background is a scroll view, I couldn't seem to connect an action to pick up a touch? One solution was to perhaps created a Custom Scroll View Controller...all of this seems a bit messy just to dismiss a keypad. Do I really have to do this? A: Would it work for you if you put a UIBarButtonItem "Done" in your navigation bar? Have you explored the UITextField property inputAccessoryView?
{ "language": "en", "url": "https://stackoverflow.com/questions/7530025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Require BeautifulSoup in a Python Package - What's needed in setup.py? I'm writing a setup script for a python distribution, foo. My code requires BeautifulSoup, so currently my directory is structured like so: <root>/ setup.py __init__.py foo.py BeautifulSoup/ __init__.py BeautifulSoup.py etc. And setup.py currently looks like this (less meta info): setup(name='foo', version='0.9.0', py_modules=['foo'] ) I want to include BeautifulSoup in case the user doesn't have it installed already, but I also don't want to install it if they already have it installed at a particular version. I noticed in the Python 2.7.2 docs that I should included packages=[...] in my setup.py file. However, Section 2.4. Relationships between Distributions and Packages mentions that there's a way to specify that a particular version of the package is required. I couldn't find any examples of how to use a "requires expression" within setup.py, so I'm not sure if this is what I need. In short, I need a way to say: This package requires BeautifulSoup, with at least X.X.X version. If that version isn't installed, use the one that's provided. How do I do that? A: Directory structure: <root>/ setup.py foo.py Note: there is no __init__.py file. You could use distribute to specify dependencies, setup.py: from setuptools import setup setup(name='foo', version='0.9.0', py_modules=['foo'], install_requires=['BeautifulSoup >= X.X.X'], ) This will install required version of BeautifulSoup if it is not already present. You don't need to provide BeautifulSoup in this case. If you don't want to install BeautifulSoup automatically: <root>/ setup.py foobar/ __init__.py foo.py BeautifulSoup/ __init__.py BeautifulSoup.py etc. setup.py: from setuptools import setup, find_packages setup(name='foobar', version='0.9.0', packages=find_packages(), ) #NOTE: no install_requires Somewhere in in your modules: import pkg_resources try: pkg_resources.require("BeautifulSoup>=X.X.X") except pkg_resources.ResolutionError: from foobar import BeautifulSoup else: import BeautifulSoup It is a less desirable and unusual method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530026", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: MvcMiniProfiler profiling web app and lower layers I have MiniProfiler set up and working in my ASP.NET MVC app. My controllers make calls via WCF to a BLL which in turn talks to the database. I would like to see profiling from the WCF service alongside the existing profiling I see from the web app. Is it a case of making MiniProfiler a parameter in all service calls? A: In a recent release of the MvcMiniProfiler they added WCF support (version 1.8 or greater). This is a 3 step process to get this working: Add References First add references to the MvcMiniprofiler and MvcMiniProfiler.WCF in your UI layer and WCF layer via nuget (or download the source and compile your own). Setup WCF Host Second, within the web.config of the service host you have to add the miniprofiler as an endpoint behavior. All of the config sections belong in "configuration/system.serviceModel". <endpointBehaviors> <behavior name="miniProfilerBehavior"> <wcfMiniProfilerBehavior /> </behavior> </endpointBehaviors> Then add the behavior extension (Note the version number needs to match your version of the MvcMiniProfiler.WCF): <extensions> <behaviorExtensions> <add name="wcfMiniProfilerBehavior" type="MvcMiniProfiler.Wcf.WcfMiniProfilerBehavior, MvcMiniProfiler.Wcf, Version=1.8.0.0, Culture=neutral" /> </behaviorExtensions> </extensions> Then setup the endpoints to use the profiler behavior you setup: <services> <service behaviorConfiguration="BaseBehavior" name="BSI.Something"> <endpoint address="" behaviorConfiguration="miniProfilerBehavior" binding="basicHttpBinding" bindingConfiguration="http" contract="BSI.ISomething"/> </service> </services> Depends on your setup but I had to add one more web.config setting to run all managed modules for all requests. This config is in the root "configuration" section: <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> </system.webServer> Setup WCF Client Last, setup the wcf client to "turn on" the mvc profiler by doing much the same above. Add the extension: <extensions> <behaviorExtensions> <add name="wcfMiniProfilerBehavior" type="MvcMiniProfiler.Wcf.WcfMiniProfilerBehavior, MvcMiniProfiler.Wcf, Version=1.8.0.0, Culture=neutral" /> </behaviorExtensions> </extensions> Add a behavior: <behaviors> <endpointBehaviors> <behavior name="wcfMiniProfilerBehavior"> <wcfMiniProfilerBehavior /> </behavior> </endpointBehaviors> </behaviors> Setup the endpoints to use that behavior: <client> <endpoint address="http://something/Something.svc" behaviorConfiguration="wcfMiniProfilerBehavior" binding="BasicHttpBinding" bindingConfiguration="BasicHttpBinding_HTTP" contract="BSL.ISomething" name="BasicHttpBinding_ISomething" /> </client> And you're done! Side Note: How does the MvcMiniProfiler actually work over WCF? Basically the client behavior sets up a SOAP header that tells the wcf host to turn on the profiler. It passes that header along which is read by the endpoint behavior on the WCF host side. It then turns the profiler on in the host. Lastly when the WCF host is replying back to the client it stuffs all the profiler goodness into the SOAP response header which is in turn read by the WCF client. Pretty ingenious. A: That's one method, but in order to get the reference to the libraries you would have to add references in the lower layers for MvcMiniProfiler anyway. What I did in this very same situation is to take advantage of the global access point that MiniProfiler provides as a singleton. So, I just added the reference in the lower levels (deleted the stuff relative to MVC, such as the views) and just used MiniProfiler.Current as if I were on the upper layers. It works like a charm. :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7530027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Cakephp Newbie Model question I have a table familiars , a table mages and a table mages_familiars where I keep which familiar belongs to which Mage. How can I model this cross reference table? Thanks in advance A: You don't need the intermediary table unless it's possible that a familiar can belong to multiple mages and mages can have multiple familiars (a HABTM relationship). In that case the table should have fields id (int), created (datetime), modified (datetime), mage_id (int) and familiar_id (int). Also, the table should be named familiars_mages. If a familiar can belong to only one mage, a familiar belongsTo a mage and a mage hasMany familiars. The familiars table should have a mage_id field. If a familiar can belong to only one mage, and a mage can have only one familiar, you can use a hasOne relationship. In that case either the mages table has a familiar_id field or the familiars table has a mage_id field.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How do I select data from a select query in MySql? I am using MySQL 5.5. I have a query which returns results like this quantity| maxPrice| minPrice |avgPrice| counts "10" "23.50" "23.50" "23.500000" "1" "15" "15.75" "15.75" "15.750000" "1" "23" "100.71" "100.71" "100.710000" "1" "25" "210.00" "200.00" "205.000000" "2" now from this data I want to extract the maximum quantity tuple and sum of all counts... so that result would look like this quantity| maxPrice| minPrice |avgPrice| counts "25" "210.00" "200.00" "205.000000" 5 how do I write query for this? A: Use ORDER BY quantity DESC and LIMIT 1 to extract the tuple. Surround your query with another select and use SUM(counts) AS counts for the total. Example: SELECT x.quantity, x.maxPrice, x.minPrice, x.avgPrice, SUM(x.counts) AS counts FROM ( SELECT * FROM mytable ORDER BY quantity DESC ) AS x LIMIT 1; Replace SELECT * FROM mytable with your real query. A: SELECT max(s.quantity) as quantity , max(s.maxPrice) as maxPrice , max(s.minPrice) as minPrice , max(s.AvgPrice) as avgPrice , max(s.totalcounts) as totalcounts FROM ( SELECT t1.quantity,t1.maxPrice,t1.minPrice,t1.avgPrice, 0 as totalcounts FROM table1 t1 ORDER BY quantity DESC LIMIT 1 UNION SELECT 0,0,0,0,sum(t2.counts) as totalcounts FROM table1 t2 ) s
{ "language": "en", "url": "https://stackoverflow.com/questions/7530031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sqlite3 How to get number of rows in table without reading all the rows? Can some shed some light on hoe to get the number of rows (using php) in a table without actually having to read all the rows? I am using squlite to log data periodically and need to know the table row count before I actually access specific data? Apart from reading all rows and incrementing a counter, I cannot seem to work out how to do this quickly (it's a large database) rather simple requirement? I have tried the following php code but it only returns a boolean response rather that the actual number of rows? $result = $db->query('SELECT count(*) FROM mdata'); Normally the SELECT statement will also return the data object (if there is any?) A: Just use LIMIT 1 That should work!! It Limits the result to ONLY look at 1 row!! A: if you have record set then you get number or record by mysql_num_rows(#Record Set#);
{ "language": "en", "url": "https://stackoverflow.com/questions/7530032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: EditText Field Is Crashing My Android App Hi all i have updated my post to show the full xml file, which will show if i am doing something wrong. i implemented a custom dialog with an edit text field and it keeps crashing. I will also like to access the values filled in the text field. Any idea where i am going wrong? Thanks. Below is the offending/troublesome??? code First i show the xml file which contains my layout for the alert dialog. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content"> <ImageView android:id="@+id/ImageView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" /> <ScrollView android:id="@+id/ScrollView01" android:layout_width="wrap_content" android:layout_below="@+id/ImageView01" android:layout_height="200px"> <TextView android:text="@+id/TextView01" android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <EditText android:id="@+id/lastname" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="blah" /> </ScrollView> <Button android:id="@+id/Button01" android:layout_below="@id/ScrollView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:text="Cancel" /> </RelativeLayout> Then main activity file which implements my button click events...etc. ....... setContentView(R.layout.main); //this button will show the dialog Button button1main = (Button) findViewById(R.id.Button01main); button1main.setOnClickListener(new View.OnClickListener() { public void onClick(View OnClickListener) { //set up dialog final Dialog dialog = new Dialog(MoredialogActivity.this); dialog.setContentView(R.layout.maindialog); dialog.setTitle("This is my custom dialog box"); dialog.setCancelable(true); TextView text = (TextView) dialog.findViewById(R.id.TextView01); text.setText(R.string.lots_of_text); //set up image view ImageView img = (ImageView) dialog.findViewById(R.id.ImageView01); img.setImageResource(R.drawable.icon); //set up button Button button = (Button) dialog.findViewById(R.id.Button01); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { dialog.dismiss(); //finish(); } }); dialog.show(); } }); } } A: You have two items in your ScrollView. According to the doc : A ScrollView is a FrameLayout, meaning you should place one child in it containing the entire contents to scroll; this child may itself be a layout manager with a complex hierarchy of objects. So you should had another layout, like a linear layout : <ScrollView android:id="@+id/ScrollView01" android:layout_width="wrap_content" android:layout_below="@+id/ImageView01" android:layout_height="200px"> <LinearLayout android:layout_width="wrap_content" android:layout_height="fill_parent" android:orientation="vertical" android:gravity="center"> <TextView android:text="@+id/TextView01" android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <EditText android:id="@+id/lastname" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="blah" /> </LinearLayout> </ScrollView>
{ "language": "en", "url": "https://stackoverflow.com/questions/7530033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jqGrid table search How can I get a jQgrid without editing and having select search elements as like: http://www.ok-soft-gmbh.com/jqGrid/ToolbarSearchValidation.htm A: I think the demo that you've linked to is using jqGrid's filterToolbar feature: see: http://www.trirand.com/jqgridwiki/doku.php?id=wiki:toolbar_searching A: Here is how I solved: stype: "select", searchoptions: { sopt: ['eq', 'ne'], value: ":All;true:Yes;false:No"
{ "language": "en", "url": "https://stackoverflow.com/questions/7530035", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iOS SDK: Is there a way to recognize when a user double taps the home button and when he locks the screen Is there a way to make a difference between the user tapping the home button twice and the user locking the screen? I know that in both cases the app delegate's method applicationWillResignActive: is called, but I'd like to able to tell exactly which event has happened. Any method to do that? Thank you! A: From looking at UIApplicationDelegate Protocol Reference: applicationWillResignActive: // Then when its back, this gets called: applicationDidBecomeActive: are the only methods that gets called in this situation. So unfortunately, the answer is no, there is no way to tell the difference between locking the device, and double clicking the home button. A: Doesn't appear to be a way in a app store app. You can probably do this with private methods. I attempted to observe these changes, but the home store double press doesn't modify your frame or window data (like say the phone call status does). So you wouldn't be able to tell when you have been moved up to show the home button bar thru observation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Built in parsing of a string to a Scala case object? Is there any way to automatically parse a case object from a string, in Scala? Using some built in / automatically generated Scala function? For example, I have these case objects: (please note that there's a sealed parent class) abstract sealed class FlagReason case object Spam extends FlagReason case object Illegal extends FlagReason case object CopyrightViolation extends FlagReason case object Other extends FlagReason and I'm wondering if there's some automatically generated function that works like: FlagReason.fromString(value: String): FlagReason where FlagReason("Spam") would return the Spam case object. If there were, then I need not write my own -- which I've done: object FlagReason { def fromString(value: String): FlagReason = value match { case "Spam" => Spam case "Illegal" => Illegal case "CopyrightViolation" => CopyrightViolation case "Other" => Other } } Background: I'm converting my case objects to strings that I use as radio button values in a html form. I'm converting the selected value back to a case object, when I handle the submitted form. Related info: This is actually possible with Java enums, see e.g. this StackOverflow question: Lookup enum by string value ((I don't think I'm looking for Scala's Parser Combinators. I suppose that were I to use them I'd still need to define the parsing rules myself, rather than having built in "automatic" string to case object conversion)) A: As missingfaktor points out, FlagReason withName "<name>" should do what you need. But if <name> is not a valid name, it will throw an exception. So, a slightly safer way to handle this when you are not sure if the name is valid is to use Option[FlagReason]: scala> def parse(name: String) = FlagReason.values.find(_.toString == name) parse: (name: String)Option[FlagReason.Value] scala> parse("Spam") res0: Option[FlagReason.Value] = Some(Spam) scala> parse("NonExisting") res1: Option[FlagReason.Value] = None A: No, no such method is automatically generated. You will have to write your own fromString method. Note that you can write it more compactly as follows: object FlagReason { def fromString(value: String): Option[FlagReason] = { Vector(Spam, Illegal, CopyRightViolation, Other).find(_.toString == value) } } Alternatively you may consider using scala.Enumeration which does provide this facility. object FlagReason extends Enumeration { val Spam, Illegal, CopyRightViolation, Other = Value } Then you can obtain the particular enum value with FlagReason withName "<name>", or safely as an Option with Try(FlagReason withName "<name>").toOption.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Gnu C++ macro __cplusplus standard conform? The Gnu C++ compiler seems to define __cplusplus to be 1 #include <iostream> int main() { std::cout << __cplusplus << std::endl; } This prints 1 with gcc in standard c++ mode, as well as in C++0x mode, with gcc 4.3.4, and gcc 4.7.0. The C++11 FDIS says in "16.8 Predefined macro names [cpp.predefined]" that The name __cplusplus is defined to the value 201103L when compiling a C++ translation unit. (Footnote: It is intended that future versions of this standard will replace the value of this macro with a greater value. Non-conforming com- pilers should use a value with at most five decimal digits.) The old std C++03 had a similar rule. Is the GCC deliberatly setting this to 1, because it is "non-conforming"? By reading through that list I thought that I could use __cplusplus to check in a portable way if I have a C++11 enabled compiler. But with g++ this does not seem to work. I know about the ...EXPERIMENTAL... macro, but got curious why g++ is defining __cplusplus this way. My original problem was switch between different null-pointer-variants. Something like this: #if __cplusplus > 201100L # define MYNULL nullptr #else # define MYNULL NULL #endif Is there a simple and reasonably portable way to implement such a switch? A: This was fixed about a month ago (for gcc 4.7.0). The bug report makes for an interesting read: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=1773 A: If I recall correctly this has to do with Solaris 8 causing issues when __cplusplus is set as it should. The gcc team decided at the time to support the Solaris 8 platform rather than be compliant in this particular clause. But I noticed that the latest version of gcc ends the Solaris 8 support, and I guess this is a first step in the right direction. A: It is a very old g++ bug. That is, the compiler is not conforming. Apparently it can't be fixed because fixing it would break something on a crazy platform. EDIT: oh, I see from @birryree's comment that has just been fixed, in version 4.7.0. So, it was not impossible to fix after all. Heh. Cheers & hth.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530047", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "34" }
Q: Cache key length in asp.net I was investigating the MVC3 source and came across the following (in OutputCacheAttribute.cs) which is called when generating a key to use for output caching: // The key is typically too long to be useful, so we use a cryptographic hash // as the actual key (better randomization and key distribution, so small vary // values will generate dramtically different keys). using (SHA256 sha = SHA256.Create()) { return Convert.ToBase64String(sha.ComputeHash(Encoding.UTF8.GetBytes(uniqueIdBuilder.ToString()))); } The comment says that the use of a hash is required because "The key is typically too long to be useful". Can anyone shed light on this and recommend a maximum length for cache keys in asp.net? A: The length doesn't actually matter as it is converted to a hash. This applies to MVC and ASP.NET. Maximum length of cache keys in HttpRuntime.Cache object?
{ "language": "en", "url": "https://stackoverflow.com/questions/7530050", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: colorbox refreshing parent window without closing popup I am using colorbox for showing pop ups. Is this possible to reload parent window without closing pop. I mean I want to do actions/events in the pop up and the changes should be displayed at parent window. Thanks A: You can definitely play with the elements in the page from within the colorbox. You can't, however, "refresh the parent window" as you stated in the question title, because then you will also lose the colorbox (which is a part of that page). But judging from the rest of your question, you simply want to make changes in the page. If your colorbox is not in an iframe (e.g., you have not explicity set the option iframe:true) then it's pretty straightforward. Just create event handlers that are called from actions performed in the colorbox. If you are setting the colorbox to open an iframe, there's a couple things to be aware of: * *The iframe page (the contents of your colorbox) must be within the same domain *Use the parent. in the iframe's JS that references the parent page Here's an example of the colorbox code you would have in the iframe page: $(document).ready(function() { $("a.internalColorboxLink").click(function() { parent.$("body").append( parent.$("<div/>").text("MY NEW TEXT") ); }); }); In fact, this is the almost the same code as would be in the inline colorbox (that is, the js in the parent page). Simply remove the parent references. I can post more concrete examples if you update your question with exactly what you want to do.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Understanding managed beans/backing beans I am learning Java EE 6 and I am trying to grasp the overall image of it. I am reading about JSF and how adding components. I am setting/reading values from the components to a bean which has the @ManagedBean annotation. I have some trouble understanding it properly. What is Managedbeans? Is it just just objects that holds the state of the components? And they can have other methods as well? Where does the EJBs fit in? Does the managed beans invoked methods on the EJBs? A: What is Managedbeans? Is it just just objects that holds the state of the components? A JSF Managed bean is like any other Java bean except that if it managed by JSF. In other words it is a bean that is created and destroyed by JSF as needed. Hortsman Core JSF 2 book states. The JSF implementation does the following: * *Creates and discards beans as needed (hence the term “managed beans”) *Reads bean properties when displaying a web page *Sets bean properties when a form is posted And they can have other methods as well? Yes they can have as many methods as you may want.However you would (and should) ideally like to have your managed bean as lean as possible.For example it might have a search method but you should not be doing actually search inside this method but this search methods sole purpose should be to delegate the task to the business layer (which may or may not be EJB based) . I other words no heavy lifting . Where does the EJBs fit in? EJB is your Business tier , they have big biceps and do all the heavy lifting. Since EJB3 JPA was introduced and that is also part of EJB. JPA however is the persistence tier. All EJBs except for JPA run in inside an EJB container. All Java EE complaint server provide these . In a typical 3 tier architecture (these days however it is mostly more than 3 but 3 tiered is easier to explain. JSF is your Web tier , EJBs are your business tier and JPA which is also part of EJB specification but does not need EJB container is your ORM or Persistence tier. Do not worry about word container too much you will get used to it quickly and rarely you will have to worry about it. If you are using a Java EE server it's all setup for you. Does the managed beans invoked methods on the EJBs? Yes as explained above already . All the heavy lifting here. However it is not mandatory to use EJB with JSF. You could use any other framework e.g Spring or could even write simple pojos but thats an other area of discussion. A: From this link JSF - Managed Beans Managed Bean : Managed Bean is a regular Java Bean class registered with JSF. In other words, Managed Beans is a java bean managed by JSF framework. From this link Creating and Using a Backing Bean for a Web Page Backing Bean : In JSF, backing beans are JavaBeans used mainly to provide UI logic and to manage data between the web tier and the business tier of the application (similar to a data transfer object). Typically you have one backing bean per JSF page. The backing bean contains the logic and properties for the UI components used on the page. NB: For a backing bean to be available when the application starts, you register it as a managed bean with a name and scope
{ "language": "en", "url": "https://stackoverflow.com/questions/7530054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: select() function in C# im new to C# and any help/feedback would be appreciated. im trying to develop a a client-server program in c#, however i do have different clients sending information to the server side. Is there any function similar to the c language select() such that can help to get all the information from every client side in C#? here is my server side code: // Create the listening socket... m_mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, 9051); // Bind to local IP Address... m_mainSocket.Bind(ipLocal); // Start listening... m_mainSocket.Listen(10); Socket clientSock = m_mainSocket.Accept(); byte[] clientData = new byte[1024]; int receivedBytesLen = clientSock.Receive(clientData); string clientDataInString = Encoding.ASCII.GetString(clientData, 0, receivedBytesLen); string clientStr = "Client Data Received: " + clientDataInString; byte[] sendData = new byte[1024]; sendData = Encoding.ASCII.GetBytes(clientStr); clientSock.Send(sendData); clientSock.Close(); A: There are higher level constructs, but if you want to get pretty low level, you are probably looking for Socket.Accept: http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.accept.aspx A: Here is a code project with some nice diagrams and examples. The underlying "select" is handled by the .NET framework so you have to think / work at a higher level. At a high level you socket.accept create a thread to process the connection. http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.accept.aspx http://www.codeproject.com/KB/IP/dotnettcp.aspx A: You want to accept connections from more than one client, so you have to call the blocking Accept method again after acception a connection: while (true) { var clientSocket = s.Accept(); beginReceive(clientSocket); } After accepting you might want to start receiving data in an async manner: private static void beginReceive(Socket clientSocket) { byte[] buffer = new byte[1000]; clientSocket.BeginReceive( buffer, 0, 1000, SocketFlags.None, OnReceiveData, clientSocket); } And finally here is the callback method which is called by the framework on another thread when data arrives. You have to finish the async call with EndReceive: private static void OnReceiveData(IAsyncResult ar) { int bytesReceived = ((Socket) ar.AsyncState).EndReceive(ar); // process data... } Of cause you have to store your buffer somewhere else and maintain one receive buffer per client. Maybe you should write an own class for managing a connected client.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to stop ui background thread on blackberry I've addded 5 button in horizontalFieldManger. When i click the button i gets image url from server there after i get the image. I loaded the image in on verticalfiedlManager on the same screen.. My code is. Thread loadImageThread = new Thread() { public void run() { if(Imagethread) { try { final Vector url = new Vector(); HttpConnections httpConnection = new HttpConnections(path+suffix); DataInputStream _inputStream = new DataInputStream(httpConnection.StreamConnection()); getXMLObjects(_inputStream); _inputStream.close(); UiApplication.getUiApplication().invokeLater(new Runnable() { public void run() { feedListItem = ListFeedHandler.item; int Size = feedListItem.size(); for (int i = 0; i < Size; i++) { url.addElement(newsBean.getURL()); } } }); UiApplication.getUiApplication().invokeLater(new Runnable() { public void run() { loadPicture(url); } }); } catch(Exception e) { e.printStackTrace(); } } } }; loadImageThread.start(); In loadPicture(url) method. i get image and load on verticalfiledmager. When i click second button, i delete all imaged on verticafiledmanager and reload which is get from second button. Its working fine. but my problem is when i click buttons two,three, four continuously , its load one by one. I need only the images which is last pressed button. A: Something like this.. int id = -1; ... if(id != -1) { UiApplication.getUiApplication().cancelInvokeLater(id); id = -1; } id = UiApplication.getUiApplication().invokeLater(new Runnable() { public void run() { ..... id = -1; //when invokeLater task finished normally }
{ "language": "en", "url": "https://stackoverflow.com/questions/7530056", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Find by intermediary attribute in a has_many :through in Rails Possible Duplicate: Rails has_many :through Find by Extra Attributes in Join Model I have the following many to many setup in my model: class Project < ActiveRecord::Base has_many :projectcollaborations has_many :partners, :through => :projectcollaborations, :source => :partner end class Partner < ActiveRecord::Base has_many :projectcollaborations has_many :projects, :through => :projectcollaborations, :source => :project end class Projectcollaboration < ActiveRecord::Base belongs_to :project belongs_to :partner end I can access: @partner = Partner.first @partner.projects @partner.projectcollaborations.find_by_myrole('creator') .... now how can I access the @partner's all project having myrole creator in my many-to-many relationship table? A: @collaborations = @partner.projectcollaborations.includes(:projects).find_all_by_myrole('creator') @projects = @collaborations.map &:project maybe there is another, prettier, railsier way, but this is how i'd do it
{ "language": "en", "url": "https://stackoverflow.com/questions/7530059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: HTML Parsing: Clicking element with "onclick" handler does not update WebBrowser ReadyState I am looking for a way to CLICK an HTML element on a page programmatically. If the page is opened in a Browser and we need to click on a <A> element then instead of clicking we can retrieve the HREF property and Navigate to that url. The benefit of this approach is that the Document::ReadyState returns the correct status, using which we can wait until the page has fully loaded. The problem comes when the element that needs to be clicked has an onclick handler. Clicking it does not give any status in ReadyState property or DocumentCompleted event. In this case, how to wait till the document has fully loaded. A: Waiting untill the document has loaded is a difficult problem, but you want to continually check for ReadyState and Busy (don't forget that). Also, you can get href of A element, not a problem, but tell me what happens when you click on the A that doesn't trigger the DocComplete or ReadyState, can you give us the outerHTML of this? why isn't it? Is it supposed to be a link that executes a JavaScript function only? If it is following a link, the only way it wont return a DocComplete event is if it returns a NavigateError event. Let us know. Also, if the page you are waiting for has frames, you need to get a ref to them and check their .busy and .readystate as well, and if the frames are nested, the nested frames .readystate and .busy as well, so you need to write a function that recursively retreives those references. Now, regarldess of how many frames it has, first fired navigatecomplete event is always the top document, and last fired doccomplete event is always that of the top (parent) document as well. So you should check to see if its the first call and the pDisp Is WebBrowser1.object (literally thats what you type in yoru if statement) then you know its the navcomplete for top level document, then you wait for this same object in the doc complete, so save the pDisp to a global variable, and wait until a doc complete is run and that Doc Complete's pDisp is equal to the Global pDisp you've saved during the first NavComplete event (as in, the pDisp that you saved globally in the first NavComplete event that fired). So once you know that pDisp was returned in a doc complete, you know the entire document is finished loading. This will improve your currect method, however, to make it more fool proof, you need to do the frames checking as well, since even if you did all of the above, it's over 90% good but not 100% fool proof, need to do more for this. Let me know your thoughts and the clarification on my question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: New open graph settings I am using Facebook comments for my wordpress blog, so far evertyhing was working good, but recently, when the user comment on my site, their comment doesnt get posted on their profile even though they thick the option saying publish this on facebook at the comment box. Is there any recent setting or option to fix this problem? Or how can I test and see what is the cause of the problem? And, Open graph brings pretty nifty cool options and settings, do I have to change or specify any special options for the comment box used on my site?
{ "language": "en", "url": "https://stackoverflow.com/questions/7530066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Accessing smartcard keystore in an applet, through a js call I am attempting to access the smartcard keystore, by an applet, through a js call. I am searching for best pratices, and hopefully a guide, minding the security issues. What I can and cannot do in it? Just the use of doPrevileged is enough? What are the limitations that an applet has in those matters? Should use a JApplet or an Applet? I really do need some directions. I just have one request: I don't want to make use of outside libraries. Thanks Addendum: as It seems, the sun documentation explains that: Signed Applets Signed applets do not have the security restrictions that are imposed on unsigned applets and can run outside the security sandbox. Note: JavaScript code is treated like unsigned code. When a signed applet is accessed from JavaScript code in an HTML page, the applet is executed within the security sandbox. This implies that the signed applet essentially behaves likes an unsigned applet. But I have come to other applets that, although their methods are called in js, use JDialog so the user starts the action. A: Smartcard is a wide term, you will be fine even with so called cryptocard (the difference is smartcard can host applications while cryptocard provides only fixed set of cryptography functions). There is a new serie (looks it will have only two part though) about this topic here: http://rostislav-matl.blogspot.com/2011/09/using-smart-card-as-keystore-in-java.html . You'll probably find that finding not too expensive and multiplatform solution is not easy.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Timezone or Time conflict I deployed a Rails App but I'm getting the times wrong on the created_at columns. I go to rails console production and ran Time.now and I get the correct time. I logged in to MySQL and ran SELECT NOW(); and I get the correct time. But when a new record is created into the database I get that it's about 5am when it's really about 1am. Anybody experience anything similar? How did you fix it? A: The problem is that you don't have default time zone set in your application. you can do it in your environment.rb (Rails 2) or application.rb (Rails 3) file, you can set the default timezone this way: config.time_zone = 'Central Time (US & Canada)' Reference: http://databasically.com/2010/10/22/what-time-is-it-or-handling-timezones-in-rails/
{ "language": "en", "url": "https://stackoverflow.com/questions/7530073", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you create a custom collection editor form for use with the property grid? I am trying to incorporate a property grid control with a class that has a list/collection of another class as one of the properties. Lets call them class A and the list would be containing class B for reference. I was wanting to incorporate a form that had two list boxes. The list box on the left would contain a list of all of class B's in my program that are not currently in the list on the right. The list on the right would contain all of the class B's that are currently associated with class A. I want buttons in between to move items between the two lists. This would be easy to design, but I'm not sure exactly how to set up the form to be used as the collection editor. Can anyone point me in the right direction? And also, how can I go about having setting up a drop down for a property that contains a list of id's to select from if anyone could point me in the direction for accomplishing this as well. A: Okay, I was finally able to track down how to accomplish this. I was attempting to create a custom CollectionEditor.CollectionForm which was close to what I needed to do, but it wasn't quite the right direction. First of all, create a regular Windows Form which includes your GUI for editing your collection. Then just include button/buttons which return a DialogResult in the Form. Now the key to accomplishing what I was looking for is not a CollectionEditor.CollectionForm as I had thought would be the correct approach, but rather a UITypeEditor. So, I created a class that inherited from the UITypeEditor. Then you simply flesh it out as such: public class CustomCollectionModalEditor: UITypeEditor { public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { if (context ==null || context.Instance == null) return base.GetEditStyle(context); return UITypeEditorEditStyle.Modal; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { IWindowsFormsEditorService editorService; if (context == null || context.Instance == null || provider == null) return value; editorService = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); CForm CollectionEditor = new CForm(); if (editorService.ShowDialog(CollectionEditor) == System.Windows.Forms.DialogResult.OK) return CollectionEditor.Programmed; return value; //return base.EditValue(context, provider, value); } } The key parts to take note of, are the functions GetEditStyle and EditValue. The part responsible for firing-off the Form you created to edit your collection, is in the EditValue override function. CForm is the custom collection editor form I designed in this test to edit the collection. You need to fetch the IWindowsFormsEditorService associated with the IServiceProvider and simply call the .ShowDialog(formVariable) of the IWindowsFormsEditorService in order to show the form you designed to edit the collection. You can then catch the returned DialogResult value from your Form and perform any custom handling that you require. I hope this helps someone out as it took me quite a bit of digging to determine the right way to incorporate this. A: This answers Brandon's question. I too searched long and hard on how to actually replace the default propertygrid collection editor. Nathan's answer was the final solution. Brandon here is how I was able to use Nathan's solution and use my own collection editor. using Swfd = System.Windows.Forms.Design; using Scm = System.ComponentModel; using Sdd = System.Drawing.Design; public class CustomCollectionModalEditor : Sdd.UITypeEditor { public override Sdd.UITypeEditorEditStyle GetEditStyle(Scm.ITypeDescriptorContext context) { if (context == null || context.Instance == null) return base.GetEditStyle(context); return Sdd.UITypeEditorEditStyle.Modal; } public override object EditValue(Scm.ITypeDescriptorContext context, IServiceProvider provider, object value) { Swfd.IWindowsFormsEditorService editorService; if (context == null || context.Instance == null || provider == null) return value; editorService = (Swfd.IWindowsFormsEditorService)provider.GetService(typeof(Swfd.IWindowsFormsEditorService)); //CForm CollectionEditor = new CForm(); //--- Replaced the Collection from this post with mine which requires an argument that passes the collection Ccne.CustomCollection editgcp = new Ccne.CustomCollection(); // Ccne.CustomCollection is my collection editgcp = MYGCPS; // MYGCPS is the actual instance to be edited Gcp_Editor.GcpEditorMain CollectionEditor = new Gcp_Editor.GcpEditorMain(editgcp); // call my editor if (editorService.ShowDialog(CollectionEditor) == System.Windows.Forms.DialogResult.OK) { MYGCPS = CollectionEditor.ReturnValue1; // update current instance of the collection with the returned edited collection THISPG.Refresh(); // calls a method which refreshes the property grid return value; // the replaces the statment in the post >> CollectionEditor.Programmed; } //--- return value; //return base.EditValue(context, provider, value); } } //---------- The propertygrid entry private Ccne.CustomCollection gCPs; [Scm.Category("3 - Optional inputs to run gdal_translate")] [PropertyOrder(133)] [Scm.TypeConverter(typeof(Ccne.CustomCollectionConverter))] [Scm.Editor(typeof(CustomCollectionModalEditor), typeof(Sdd.UITypeEditor))] [Scm.Description("The Collection of the single or multiple Ground Control Points (Gcp)" + " entered. \n Each gcp requires a Name, pixel, line, easting, " + "northing, and optionally an elevation")] [Scm.RefreshProperties(Scm.RefreshProperties.All)] // http://stackoverflow.com/questions/3120496/updating-a-propertygrid [Scm.DisplayName("23 Collection of Gcp's")] [Scm.ReadOnly(true)] // prevents values being changed without validation provided by form public Ccne.CustomCollection GCPs { get { return gCPs; } set { gCPs = value; } } //-------- important code from CollectionEditor i.e. > Gcp_Editor.GcpEditorMain(editgcp) using Swf = System.Windows.Forms; namespace Gcp_Editor { public partial class GcpEditorMain : Swf.Form { public Ccne.CustomCollection ReturnValue1 { get; set; } ... public GcpEditorMain(Ccne.CustomCollection input1) { InitializeComponent(); formcollection = input1; } ... private void OkayBtn_Click(object sender, EventArgs e) { this.DialogResult = Swf.DialogResult.OK; ReturnValue1 = formcollection; return; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7530074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: What is the best way to compute intersection and difference of 2 sets? I have 2 lists List<Class1> and List<Class2> that are compared by same property Class1.Key and Class2.Key (string) and I want to write a function that will produce 3 lists out of them * *List<Class1> Elements that are present in both lists *List<Class1> Elements that are present only in first list *List<Class2> Elements that are present only in second list Is there a quick way to do that? A: var requirement1 = list1.Intersect(list2); var requirement2 = list1.Except(list2); var requirement3 = list2.Except(list1); For your List<string>, this will be all you need. If you were doing this for a custom class and you were looking for something other than reference comparisons, you'd want to ensure that the class properly overrided Equals and GetHashCode. Alternatively, you could provide an IEqualityComparer<YourType> to overloads of the above methods. Edit: OK, now you've indicated in the comments that it isn't a list of string, it's a List<MyObject>. In which case, override Equals/GetHashCode (if your key should uniquely identify these classes all the time and you have access to the source code) or provide an IEqualityComparer implementation (still involves Equals/GetHashCode, use this if the comparison is unique to these requires or if you do not have access to MyObject source). For example: class MyObjectComparer : IEqualityComparer<MyObject> { public bool Equals(MyObject x, MyObject y) { // implement appropriate comparison of x and y, check for nulls, etc } public int GetHashCode(MyObject obj) { // validate if necessary return obj.KeyProperty.GetHashCode(); } } If you used a custom equality comparer such as this, the call to the above methods would be list1.Intersect(list2, customComparerInstance); Edit: And now you've moved the bar yet again, this time the problem deals with two distinct classes. For this, you would consider utilizing join operations, one being an inner, the other being an outer. In the case of class Class1 { public string Foo { get; set; } } class Class2 { public string Bar { get; set; } } You could write var intersect = from item1 in list1 join item2 in list2 on item1.Foo equals item2.Bar select item1; var except1 = from item1 in list1 join item2 in list2 on item1.Foo equals item2.Bar into gj from item2 in gj.DefaultIfEmpty() where item2 == null select item1; To get the items in list2 without matching* objects in list1, simply reverse the order of the lists/items in the except1 query.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Passing a UISlider value into stringByEvaluatingJavaScriptFromString? I have a UISlider and I'm trying to pass its value into a window.scrollBy string. Basically, I'm attempting user-configurable auto-scrolling of web content. The actual scrolling is working, but I'm unable to pass a value into the JavaScript by using the normal %f and , method. [_webView stringByEvaluatingJavaScriptFromString:@"window.scrollBy(0,5);"]; I'm using the above, and I'd like the '5' to be substituted with the value of the slider. Can this be done without the need for more Java (I'm absolutely not a JavaScript programmer!) A: First you have to build your javascript code using StringWithFormat: NSString *string = [NSString stringWithFormat:@"window.scrollBy(0,%f);", slider.value]; [_webView stringByEvaluatingJavaScriptFromString:string];
{ "language": "en", "url": "https://stackoverflow.com/questions/7530086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to set a background drawable on a clicked GridView item in Android? I have a GridView with a bunch of icons and I need to select one. And by select I mean: * *I need the drawable id to store into a database (so I can access it later) *I need to draw some kind of visual cue on the grid to let the user know which icon is currently selected I found this: http://groups.google.com/group/android-developers/browse_thread/thread/f08a58167dbaa8c8 So I guess setSelection is out of the picture and I can't use it to select the icon itself nor draw the visual cue. I know the grid item position in the onItemClickListener and I can save it as a private class variable. My biggest problem is drawing that visual cue. How can I achieve that? How can I draw a visual cue on the clicked item and if the user clicks different items, to "undraw" that visual cue and redraw it in the new item? A: After tackling with this for a couple of hours I think I finally found the solution I was looking for. Although the answers are barely related, the initial edits on Ian solution helped me find this solution :) I'm not going to explain everything I did, I think it's pretty self explanatory. Just a few remarks: * *First I tried view.Invalidate() and view.postInvalidate() instead of iconAdapter.notifyDataSetChanged() but neither worked. The documentation stated that the invalidate methods only "asked" to redraw the view "when possible". *I was looking for a simpler solution than to merge two drawables. For instance, draw the icon on the ImageView background and the visual cue as the image. For some strange reason, the visual cue started to show randomly all over the other icons when the GridView was scrolled. I don't understand why, but the idea of a visual cue on top of a background image makes perfect sense to me and ImageView allows that, no need for that extra merge method. However, I couldn't make it work without it... MyActivity.java public class MyActivity extends Activity { private GridView mGridViewIcon; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mGridViewIcon = (GridView)findViewById(R.id.gridview_icon); mGridViewIcon.setAdapter(new IconAdapter(this)); mGridViewIcon.setOnItemClickListener(new GridView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { IconAdapter iconAdapter = (IconAdapter)parent.getAdapter(); iconAdapter.setSelectedItemPosition(position); iconAdapter.notifyDataSetChanged(); } }); } } IconAdapter.java public class IconAdapter extends BaseAdapter { private int mSelectedPosition; private Integer[] mThumbIds; private int mIconSize; private Context mContext; public IconAdapter(Context context) { mThumbIds = AppHelper.ICON_SET.keySet().iterator().next(); mIconSize = context.getResources().getDimensionPixelSize(R.dimen.default_icon_size); mContext = context; } @Override public int getCount() { return mThumbIds.length; } @Override public Object getItem(int position) { return mContext.getResources().getDrawable(mThumbIds[position]); } @Override public long getItemId(int position) { return mThumbIds[position]; } @Override public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if(convertView == null) { imageView = new ImageView(mContext); imageView.setLayoutParams(new GridView.LayoutParams(mIconSize, mIconSize)); } else { imageView = (ImageView)convertView; } if(mSelectedPosition == position) { imageView.setImageDrawable(mergeDrawableLayers(mThumbIds[position], R.drawable.ic_note_selected_mark)); } else { imageView.setImageResource(mThumbIds[position]); } return imageView; } public void setSelectedItemPosition(int position) { mSelectedPosition = position; } private Drawable mergeDrawableLayers(int background, int overlay) { Drawable[] drawableLayers = new Drawable[2]; drawableLayers[0] = mContext.getResources().getDrawable(background); drawableLayers[1] = mContext.getResources().getDrawable(overlay); return new LayerDrawable(drawableLayers); } } A: I believe, that if you want some kind of selection cue, you need a focusable object. However, with a focusable object (such as a Button), attaching OnItemClickListener to the GridView does not work (if i remember correctly). Rather, you must individually attach an OnClickListener to each item at getView() in the adapter. Adapter: // create a new ImageView for each item referenced by the Adapter public View getView(int position, View convertView, ViewGroup parent) { Button button; if (convertView == null) { // if it's not recycled, initialize some attributes button = new Button(mContext); // set layout params (make sure its GridView.layoutParams) // and other stuff } else { button = (Button) convertView; } button.setBackgroundResource(mThumbIds[position]); // mThumbIds hold Resource Ids button.setOnClickListener(new OnClickListener() { onClick(View v) { // store directly to database here, or send it with the activity with sharedPreferences (below) // We need an Editor object to make preference changes. // All objects are from android.context.Context SharedPreferences settings = getSharedPreferences("MY_PREFERENCE", 0); SharedPreferences.Editor editor = settings.edit(); editor.putInt("button_id", mThumbIds[position]); // Commit the edits! editor.commit(); } }); return button; } } On Activity Side, save button onClickListener: onClick(View v) { // Restore preferences SharedPreferences settings = getSharedPreferences("MY_PREFERENCE", 0); int id = settings.getInt("button_id", -1); // now safe all stuff to database } There may be details missing because a Button is focusable, but i think this should do. Also , you will achieve the selection by using a .xml defined selector resource. That, however, should be addressed in a separate question. Edit 1: Actually now that i think about it, i'm not sure if a drawable .xml (the selector) can have an ID. I'll have to implement this at home later on and try it. Edit 2: I added the sharedPreference part Edit 3: Added activity side querying of sharedPreference.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530087", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Precompiling assets with Capistrano shows error on load 'deploy/assets' I'm using rails 3.1.0 and trying to setup Capistrano to precompile assets. Capistrano v2.8.0 has "load 'deploy/assets'" in Capfile. But when I run "cap deploy" it shows the following error: cap deploy /usr/lib/ruby/1.8/capistrano/configuration/loading.rb:183:in `find_file_in_load_path': no such file to load -- deploy/assets (LoadError) from /usr/lib/ruby/1.8/capistrano/configuration/loading.rb:171:in `load_from_file' from /usr/lib/ruby/1.8/capistrano/configuration/loading.rb:89:in `load' from /usr/lib/ruby/1.8/capistrano/configuration/loading.rb:86:in `load' from /usr/lib/ruby/1.8/capistrano/configuration/loading.rb:86:in `each' from /usr/lib/ruby/1.8/capistrano/configuration/loading.rb:86:in `load' from Capfile:3:in `load' from /usr/lib/ruby/1.8/capistrano/configuration/loading.rb:172:in `load_from_file' from /usr/lib/ruby/1.8/capistrano/configuration/loading.rb:89:in `load' from /usr/lib/ruby/1.8/capistrano/configuration/loading.rb:86:in `load' from /usr/lib/ruby/1.8/capistrano/configuration/loading.rb:86:in `each' from /usr/lib/ruby/1.8/capistrano/configuration/loading.rb:86:in `load' from /usr/lib/ruby/1.8/capistrano/cli/execute.rb:64:in `load_recipes' from /usr/lib/ruby/1.8/capistrano/cli/execute.rb:64:in `each' from /usr/lib/ruby/1.8/capistrano/cli/execute.rb:64:in `load_recipes' from /usr/lib/ruby/1.8/capistrano/cli/execute.rb:30:in `execute!' from /usr/lib/ruby/1.8/capistrano/cli/execute.rb:14:in `execute' from /usr/bin/cap:4 UPDATE It magically started working after I restarted my PC (Ubuntu). A: Can you please demonstrate that the cap that you are using is indeed in the bundle? Please share your Gemfile and your Capfile, chances are that "cap" isn't in the bundle, so it's loading a previous version, be sure to run with "bundle exec" (to make sure to use the correct capistrano) A: As I encountered the same problem currently, I noticed that using RVM with a project specific .rvmrc was not reloaded after I switched branches with git checkout. The result was that the system wide capistrano version 2.6.0 was being used instead of the project specific capistrano version 2.9.0. This lead to the same error message 'no such file to load -- deploy/assets (LoadError)'. A simple cd out of the project path and again into the project path solved the problem for me. A: What worked for me for this issue was installing the latest version of capistrano (gem install capistrano).
{ "language": "en", "url": "https://stackoverflow.com/questions/7530089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is java.util.Observable thread-safe? In java's Observer pattern classes Observer and Observable, are calls made to Observable objects's notifyObservers(Object arg0), in different threads, thread-safe? Example: I have multiple threads, all Observables, that will be calling notifyObservers(...) ever so often. All these threads report to a single Observer object. Will I encounter concurrency issues, and what would be a better way to solve this? I am aware of a possible solution using event listeners. However I am unsure how to implement it and also, I would like to stick with the Observer pattern implementation, if possible. A: From the source code (I have Java 5 source, but it should be the same for Java 6 and 7) it seems like you only have synchronization on the Observable itself. From the notifyObservers(...) method (in Observable): synchronized (this) { //the observers are notified in this block, with no additional synchronization } Thus if the Observer doesn't change any shared data it should be fine. If it does - you could have multiple calls to update(Observable, Object) with different Observables - you'd need to add synchronization on that shared data yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Rails select form helper needs to save multiple attribute values of one object I have a form where I'm creating an interview for a job posting and one of the fields is a dropdown where I select the candidate (from a list of candidates created on another page) that I plan to interview. So far I'm able to save the details of the interview as well as the candidates name, but I also want to save the candidates id. I'm not sure how to go about this. Currently I have = select("interview", "interviewee_name", Candidate.order('last_name ASC').collect {|c| [c.fullname]}) Somehow I need to find a way to retrieve and save the correct value to candidate_id. Any help is appreciated :) A: = select("interview", "interviewee_name", Candidate.order('last_name ASC').collect{|c| [c.fullname, c.id]}) UPD Then (if you really need to store its name) in model add callback: class Interview < AR::Base before_save :set_candidate_name belongs_to :candidate private def set_candidate_name self.interviewee_name = self.candidate.fullname end end A: You probably need to use javascript to do this - basically put a click handler on the select element and make an ajax call to the server to retrieve the candidate name from the id. Then populate the name field in the callback. I think I have some sample code somewhere if you are using jquery ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7530096", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Bluetooth On Android: my Socket.connect() Blocks forever, and Socket.close does not unblock I have been working on a bluetooth app for android for awhile now and I just discovered this problem. When I preform mySocket.connect(); in my bluetooth service class it occasionally blocks indefinitely. I read the documentation for BluetoothSocket.close() and it says the following: Immediately close this socket, and release all associated resources. Causes blocked calls on this socket in other threads to immediately throw an IOException. However, this does not seem to work for me. Here is my code for setting a timer and then trying to connect. //code for starting timer and connecting MyRunnable runner = new MyRunnable(mySocket); Thread countThread = new Thread(runner); countThread.start(); mySocket.connect(); runner.setSocketConnected(); //code for MyRunnable private class MyRunnable implements Runnable{ private boolean didSocketConnect = false; private boolean socketConnectFailed = false; private BluetoothSocket socket; public MyRunnable(BluetoothSocket socket){ this.socket = socket; } public void run() { long start = System.currentTimeMillis(); while(ESTABLISH_TIMEOUT + start >= System.currentTimeMillis() && !didSocketConnect && !socketConnectFailed){ } if(!didSocketConnect && !socketConnectFailed){ Log.v(TAG,"Reached Timeout and socket not open. Look for #"); try { socket.close(); Log.v(TAG,"#THIS CALL SHOULD BE MADE AFTER REACHED TIMEOUT AND SOCKET NOT OPEN"); } catch (IOException e) { Log.v(TAG,"Closing the socket connection fail--", e); } }else{ Log.v(TAG, "Connected or Failed Before Timeout Thread Hit"); } } public void setSocketConnected(){ didSocketConnect = true; } public void setSocketFailed(){ socketConnectFailed= true; } } When I call close(), it also blocks indefinitely and the connect() call never throws an IOException, despite BluetoothSocket.close() documentation. What is the best way to make it work so that the connect() and close() do not block indefinitely? NOTE: I am using Android 2.2 for this project. A: BluetoothSocket.connect() - From the documentation: Attempt to connect to a remote device. This method will block until a connection is made or the connection fails. If this method returns without an exception then this socket is now connected. In order for your call to BluetoothSocket.connect() to quit blocking, it needs to make the connection. This is by design and it makes sense if you think about it, get the address of the Bluetooth device we want to connect to, call .connect(), and block until its connected. This is why you want separate threads. As far as you calling .close(), if you work out the issues with .connect(), .close() should fall into place. Please read this. It basically says you want a separate thread called "connecting" (.connect()) and "connected" (InputStream.read()). This way your UI will not be blocked. Example (from the above link). ConnectThread initiates the connection. ConnectedThread manages the connection (reads/writes data, etc...). private class ConnectThread extends Thread { private final BluetoothSocket mmSocket; private final BluetoothDevice mmDevice; public ConnectThread(BluetoothDevice device) { // Use a temporary object that is later assigned to mmSocket, // because mmSocket is final BluetoothSocket tmp = null; mmDevice = device; // Get a BluetoothSocket to connect with the given BluetoothDevice try { // MY_UUID is the app's UUID string, also used by the server code tmp = device.createRfcommSocketToServiceRecord(MY_UUID); } catch (IOException e) { } mmSocket = tmp; } public void run() { // Cancel discovery because it will slow down the connection mBluetoothAdapter.cancelDiscovery(); try { // Connect the device through the socket. This will block // until it succeeds or throws an exception mmSocket.connect(); } catch (IOException connectException) { // Unable to connect; close the socket and get out try { mmSocket.close(); } catch (IOException closeException) { } return; } // Do work to manage the connection (in a separate thread) manageConnectedSocket(mmSocket); } /** Will cancel an in-progress connection, and close the socket */ public void cancel() { try { mmSocket.close(); } catch (IOException e) { } } } private class ConnectedThread extends Thread { private final BluetoothSocket mmSocket; private final InputStream mmInStream; private final OutputStream mmOutStream; public ConnectedThread(BluetoothSocket socket) { mmSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; // Get the input and output streams, using temp objects because // member streams are final try { tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); } catch (IOException e) { } mmInStream = tmpIn; mmOutStream = tmpOut; } public void run() { byte[] buffer = new byte[1024]; // buffer store for the stream int bytes; // bytes returned from read() // Keep listening to the InputStream until an exception occurs while (true) { try { // Read from the InputStream bytes = mmInStream.read(buffer); // Send the obtained bytes to the UI Activity mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer) .sendToTarget(); } catch (IOException e) { break; } } } /* Call this from the main Activity to send data to the remote device */ public void write(byte[] bytes) { try { mmOutStream.write(bytes); } catch (IOException e) { } } /* Call this from the main Activity to shutdown the connection */ public void cancel() { try { mmSocket.close(); } catch (IOException e) { } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7530100", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Is there a way to ensure that a Silverlight ScrollViewer keeps the top item completely visible In Silverlight 4, is there a way that whenever you page down a ScrollViewer (i.e click the scroll bar in the area adjacent to the thumb) whatever item is at the top is completely visible. I still need it to scroll smoothly when the thumb is dragged or the mouse wheel is used. My client doesn't like that an item is cut in half when he pages down the list because it is cut in half both when its at the top and when its at the bottom. I suggested some sort of integral scroll, and he didn't like it. He wants it to still scroll smoothly unless paging up or down. Edits Here's the catch. The items are not the same size. So I have to detect the item that is at the top of the scroll viewer and Scroll it into view. Is there an easy way to do this? A: The first thing you need to do is dig out the vertical scroll bar from the internals of the ScrollViewer. You can do this with the help of VisualTreeHelper. There are a number of little chunks of code in various blogs the make its use even easier. I recommend this VisualTreeEnumeration (but I would wouldn't I). With that extensions class in place you can get the vertical scroll bar with: ScrolBar vertSB = someScrollViewer.Descendents() .OfType<ScrollBar>() .FirstOrDefault(sb => sb.Name = "VerticalScrollBar"); Now you can attach to is Scroll event and determine the type of scroll that occured like this: vertSB.Scroll += (s, args) => { if (args.ScrollEventType == ScrollEventType.LargeDecrement || args.ScrollEventType == ScrollEventType.LargeIncrement) { // using args.NewValue determine the correct Integral value and assign // using someScrollViewer.ScrollToVerticalOffset } };
{ "language": "en", "url": "https://stackoverflow.com/questions/7530101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to drop all of the indexes except primary keys with single query I am planning to drop all of the indexes except the primary keys. I made the primary keys myself but all other indexes was suggestion of SQL Server. After dropping all indexes which are not primary keys, planning to use SQL Server profiler tuning template for database tuning advisor and create indexes. With this way planning to not have unused indexes or performance degrading indexes. How logical is this ? Thank you. A: The easiest way is probably this: run this query which will output a list of DROP INDEX ..... statements. SELECT 'DROP INDEX ' + name + ' ON ' + OBJECT_SCHEMA_NAME(object_id) + '.' + OBJECT_NAME(object_Id) FROM sys.indexes WHERE is_primary_key = 0 AND name IS NOT NULL AND OBJECT_SCHEMA_NAME(object_id) <> 'sys' Copy those DROP statements from the results grid to a new query window, check them, maybe tweak them, and then run them to actually drop the indices. A: DECLARE @sql NVARCHAR(MAX) = N''; SELECT @sql += N'DROP INDEX ' + QUOTENAME(SCHEMA_NAME(o.[schema_id])) + '.' + QUOTENAME(o.name) + '.' + QUOTENAME(i.name) + ';' FROM sys.indexes AS i INNER JOIN sys.tables AS o ON i.[object_id] = o.[object_id] WHERE i.is_primary_key = 0 AND i.index_id <> 0 AND o.is_ms_shipped = 0; PRINT @sql; -- EXEC sp_executesql @sql;
{ "language": "en", "url": "https://stackoverflow.com/questions/7530103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: A question on semaphore value if a process terminates abnormally after decrementing the semaphore value if a process goes down after decrementing the value of semaphore from 1 to 0, as per my understanding the value of semaphore remains as 0. If the same process comes up again and tries to re-acquire the same semaphore, it will block for ever. Is there a way to reset the semaphore value to 1 after decrementing it if my process goes down abnormally? A: I assume you are using the standard semctl()/semop() API for the semaphores. There is a flag available called SEM_UNDO that will tell the kernel to reset the semaphore's value if your process terminates. You need to use this in your semop( ) calls. More information here : http://beej.us/guide/bgipc/output/html/multipage/semaphores.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7530105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tracking the Successfully uploaded File Names by 'Uploadify' Jquery plugin I am using 'Uploadify' Jquery plugin in my MVC 3.0 application to upload multiple files. Its working fine, but showing the list of files which got failed while uploading. How to track the Successfully uploaded File Names? My script looks like : <link href="@Href("~/Content/uploadify.css")" rel="stylesheet" /> <script src="@Href("~/Scripts/jquery-1.4.1.js")" type="text/javascript"></script> <script src="@Href("~/Scripts/jquery.uploadify.js")" type="text/javascript"></script> <script type="text/javascript"> $(window).load( function () { $("#fileuploader").fileUpload({ 'uploader': '/Scripts/uploader.swf', 'cancelImg': '/Images/cancel.png', 'buttonText': 'Select Image', 'script': 'Home/Upload', 'folder': '/uploads', 'fileDesc': 'Image & XML Files', 'fileExt': '*.jpg;*.jpeg;*.gif;*.png;*.xml', 'multi': true, 'auto': true }); } ); </script> My HTML code : <div id="fileuploader"></div> <div>Upload Status</div> Successful Files : <div> @TempData["SuccessfulFileList"]</div> Failed Files :<div> @TempData["FailedFileList"]</div> The Controller code goes like this: private static List<string> _successfulFileList = new List<string>(); private static List<string> _failedFileList = new List<string>(); public string Upload(HttpPostedFileBase fileData) { try { var fileName = this.Server.MapPath("~/uploads/" + System.IO.Path.GetFileName(fileData.FileName)); fileData.SaveAs(fileName); _successfulFileList.Add(fileName); } catch { var failedFileName = fileData.FileName; _failedFileList.Add(failedFileName); } TempData["SuccessfulFileList"] = _successfulFileList; TempData["FailedFileList"] = _failedFileList; return "Some Files Get uploaded"; } A: You are using a Flash component to upload your files (Uploadify). Flash components don't send cookies. Sessions are tracked by cookies. TempData uses Session. Conclusion => you cannot use TempData with a Flash client. There are some ugly workarounds. This being said using a static list in your controller to store uploaded files is very dangerous because the List<T> object is not thread safe and if you have 2 users uploading their files in parallel your application could crash. As an alternative you could store the list of the uploaded files to your datastore (database or something) and fetch it from there instead of relying on session. A: I found a quite descriptive explanation here : Link Ref : http://blog.bobcravens.com/2010/02/upload-files-with-progress-using-uploadify/
{ "language": "en", "url": "https://stackoverflow.com/questions/7530108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Qt Creator "Cannot create file (...) qtcreator.xml" (Mac) Qt Creator starts up with several error messages saying that: "Cannot create file /Users/[username]/.config/Nokia/qtcreator.xml: Permission denied" And when I exit: "Cannot create file /Users/[username]/.config/Nokia/toolChains.xml: Permission denied" The program runs fine, but I guess it won't be able to store any config. Anyone know how to fix this? A: As has been mentioned in the comments, it looks like the Qt installer adds the configuration directories with root as the owner. To fix this, run: sudo chown -R `id -un`:staff ~/.config/Nokia/ A: this command works great for me. found it in qtcenter forum find ~/.config/Nokia -print0 | sudo xargs -0 chown $USER i use this instead for version 2.6.1 Qt 5 find ~/.config/QtProject -print0 | sudo xargs -0 chown $USER
{ "language": "en", "url": "https://stackoverflow.com/questions/7530111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Android service to listen for incoming text from server I need android service which will run in background and listen for urls from server. Then that application will take data from urls and save it to hard disk. My question in first place is, is it possible for android service to listen for incoming text from server? A: What you want to do is receiving push notifications, which can contain the URL's you want: https://stackoverflow.com/search?q=[android]+push+notifications A: I think you might be looking for this http://code.google.com/android/c2dm/ http://www.vogella.de/articles/AndroidCloudToDeviceMessaging/article.html By using c2dm we can achieve your requirement.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Oracle data distribution across date index There's a situation that arises in large database tables (~50 million rows) where users need to browse date-indexed records. But users browsing the data do not necessarily know where on the timeline data occurs and where the gaps are. In past projects, I've quantized the records into 24-hour "buckets", and used that to create a bar-graph timeline, where the height of the bar indicates the number of records in that period. This allowed users to focus in on areas where data actually exists. The drawback of this solution is that the record counts must be continually updated and maintained (if data can be inserted/removed from any point on the timeline). Is there a more elegant solution to getting these aggregate record counts? For instance, by peeking at a date index and seeing how many values there are associated with that index? A: No too sure what you are asking but faced with a similar situation i would do the following: Partition the table on s_date. (is that what your "bucket" is, a partition?) Create a bitmap index on s_date. Generate statistics like this: select s_date, count(s_date) from big_table where s_date > '01-APR-11' group by s_date; Also you may want to read up on oracle's "Gathering Optimizer Statistics", it's nice to know. cheers. A: I'm not sure if this will actually work for you, but it sounds like what you're looking for are histograms. If a histogram exists for your index, you can query USER_HISTOGRAMS to get a rough idea of the distribution of values across the index. The downside of this is that it will only be accurate as of the last time statistics were gathered for your index, so if your data changes often, it may not be up-to-date.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Conflict between QTMovie / QTMovieView and custom C++ framework I'm experiencing an insane problem... A simple Cocoa application with QTMovieView, in which a specific movie file is set or an application which loads and renders QTMovie manually works fine, however if I just link my custom Objective C++ framework, the application always hangs / deadlocks indefenitely right after first [QTMovie play] or [QTMovie autoplay] call... My custom framework is pretty complex, but I can't even imagine how it can be in a conflict with QTMovie since only static initialization logic is executed, the framework works perfectly fine with its container Cocoa application and there are no exceptions or signals, even valgrind fails to detect anything. There is, however, operator new overloading, but disabling it doesn't help... Also it doesn't matter from which thread the QTMovie is being accessed from - the result is always the same... Changing compiler settings, synchronizing compiler settings with the framework settings have not effect, compiler settings by themselves do not seem to cause any problems. Also, if I initialize QTMovie OR QTMovieView, load my framework dynamically and call the [QTMovie play] or [QTMovie autoplay] method, the thread it was called from will also deadlock... Can somebody please help me understand, what can possibly cause this issue?! A: Ryan, what does make you think there is a conflict between QTMovie and QTMovieView? Have you tried to exclude QTMovieView, does QTMovie play normally without it? You should be able to hear the sound at least. If the QTMovie is the issue, which I doubt, you could use QTMovieLayer instead. Also, you said you used threads, QTMovie is a capricious thing, you always need to create it in the main thread. If you want to use it in another thread make sure you detached it successfully and attached to the new thread. In the new thread you need to call [QTMovie enterQTKitOnThread] or [QTMovie enterQTKitOnThreadDisablingThreadSafetyProtection] before you start doing anything with the movie. Also, [QTMovie exitQTKitOnThread] should be called after the movie has been detached from the thread and the thread is about to finish. A: Just from your description, it is hard to understand the exact sequence of calls that is going on. However, when I have seen freezes that match the general description of what you are doing in the past, they have usually been static initialisation problems. You mention that you only have static initialisation logic being executed, which to me makes this even more likely. The problem is that file scope statics are not guaranteed to be initialised in any order. What happens, then, is that sometimes you can get differences in the order of initialisation depending on what libraries you link in. So, if you have two objects A and B and B depends on A, you may find that most of the time the initialisers for A are called first and everything works, but then you link in a new library and suddenly B is scheduled first. Since it uses an uninitialised A, anything could happen, from accessing invalid/unmapped memory addresses to returning odd values used in if/else cases for weird program flow or strange container lookup, etc... There are methods of removing these kinds of static initialisation issues. See this article on solving the static initialisation fiasco. A: I trade QTMovieView as a screen only. For some simple apps, I also use it to handle everything like this: [myQTMovieView setMovie:((QTMovie *)[QTMovie movieWithFile:file error:&error])]; [[myQTMovieView movie] stop]; [[myQTMovieView movie] autoplay]; so, in this way, you will never to init an QTMovie.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530121", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: DataGridTemplateColumn sizing I have a WPF app with a DataGrid containing 10 DataGridTemplateColumns. When I bind a collection of objects to the data grid they all display fine in the grid. The only problem is that if I have I more rows than will fit on the screen without scroll bars, the columns only autosize to fit the values that are on the screen. If, for example, I scroll down and come to a row where the value of column 1 doesn't fit then column 1 will autosize to fit it. This is really annoying. Is there no way of making it autosize to fit all items in the collection, regardless of whether or not they are initially on screen? I've tried setting the width property of each column to Auto but that didn't do anything. Thanks in advance for any help A: The issue is being caused because the rows in the datagrid are being virtualized. So items not shown on the screen do not need to be drawn (or have their sizes calculated) until they need to be displayed. You could turn virtualization off like so: <DataGrid VirtualizingStackPanel.IsVirtualizing="False" HorizontalScrollBarVisibility="Hidden"> Note, however, that doing so can cause your datagrid to load slower if you have a lot of items due to the fact that all items will be 'drawn' even when not shown on the screen.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Server-side processing - how to refresh the table on outside event (checkbox clicked)? If there is a series of checkboxes defining some additional conditions on the data (like "Male", "Female") above a server-processed DataTables table and the user makes some selections - How to tell the table to reload the new aaData from the server? And is there a way to pass some parameters (like which checkboxes have been set) along? A: Do you need something like http://www.datatables.net/release-datatables/examples/api/regex.html ? Ignore regex specific code - this page shws you how to filter elements using external form. Jovan
{ "language": "en", "url": "https://stackoverflow.com/questions/7530131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript form error array not registering I have made a fiddle so you can test it for your yourself: http://jsfiddle.net/ProjectV1/9XQtb/ Javascript I have coded some simple validation and before the function created an array for form errors, at the end of the function there is an if statement that if any of the array == true then it prevents the event handler for the form submission. The actual problem I have is that the form itself works and so does the error array but the if statement does not work for both the confirm inputs. Try it yourself with the fiddle (I have added the result of the variable error for that input next to the input itself for ease of understanding); RECREATE PROBLEM To pass as error == false then the email must be valid, password over 6 characters, and username over 3 characters. For example purposes I have pointed the form to google. Form works for non confirm inputs If you click on the input fields of email, password, and username, without ever selecting the confirm inputs and try to submit the form it will not as expected as the error variables return true. Then fill them out so that the errors return false without ever selecting the confirm input fields and the form will submit as expected as the error variables return false. Form doesn't work for confirm inputs But if you fill out all the form fields so that either or both of the confirm inputs contain an error then the form still submits even though the errors for that input field returns false. The confirm inputs will only ever try to validate if the input it is confirming itself returns as false. Why is this happening and how can I prevent it? Has it got something to do with the fact that the confirm inputs are nested in if else statements. Javascript Code $(document).ready(function() { $('#joinForm input').blur(function() { var id = $(this).attr('id'); joinAjax (id); }); }); var errors = new Array(); errors[email] = null; errors[cemail] = null; errors[password] = null; errors[cpassword] = null; errors[username] = null; function joinAjax (id) { var val = $('#' + id).val(); if (id == 'email') { $('#emailMsg').hide(); var reg = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/; if (val == '') { errors[email] = true; $('#' + id).after('<div id="emailMsg" class="error">' + errors[email] + '</div>'); } else if (reg.test(val) == false) { errors[email] = true; $('#' + id).after('<div id="emailMsg" class="error">' + errors[email] + '</div>'); } else { errors[email] = false; $('#' + id).after('<div id="emailMsg" class="success">' + errors[email] + '</div>'); } joinAjax('#cemail'); } if (id == 'cemail') { $('#cemailMsg').hide(); var reg = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/; var email = $('#email').val(); if (reg.test(email) == true) { if (val != email) { errors[cemail] = true; $('#' + id).after('<div id="cemailMsg" class="error">' + errors[cemail] + '</div>'); } else { errors[cemail] = false; $('#' + id).after('<div id="cemailMsg" class="success">' + errors[cemail] + '</div>'); } } else { $('#cemail').val(''); } } if (id == 'password') { $('#passwordMsg').hide(); if (val == '') { errors[password] = true; $('#' + id).after('<div id="passwordMsg" class="error">' + errors[password] + '</div>'); } else if (val.length < 6) { errors[password] = true; $('#' + id).after('<div id="passwordMsg" class="error">' + errors[password] + '</div>'); } else { errors[password] = false; $('#' + id).after('<div id="passwordMsg" class="success">' + errors[password] + '</div>'); } joinAjax('#cpassword'); } if (id == 'cpassword') { $('#cpasswordMsg').hide(); var password = $('#password').val(); if (password.length >= 6) { if (val != password) { errors[cpassword] = true; $('#' + id).after('<div id="cpasswordMsg" class="error">' + errors[cpassword] + '</div>'); } else { errors[cpassword] = false; $('#' + id).after('<div id="cpasswordMsg" class="success">' + errors[cpassword] + '</div>'); } } else { $('#cpassword').val(''); } } if (id == 'username') { $('#usernameMsg').hide(); if (val == '') { errors[username] = true; $('#' + id).after('<div id="usernameMsg" class="error">' + errors[username] + '</div>'); } else if (val.length < 3) { errors[username] = true; $('#' + id).after('<div id="usernameMsg" class="error">' + errors[username] + '</div>'); } else { errors[username] = false; $('#' + id).after('<div id="usernameMsg" class="success">' + errors[username] + '</div>'); } } $('#joinForm').submit(function(event){ if ((errors[email] == true) || (errors[cemail] == true) || (errors[password] == true) || (errors[cpassword] == true) || (errors[username] == true)) { event.preventDefault(); } return true; }); Working example http://jsfiddle.net/ProjectV1/9XQtb/3/ CHANGES AFTER POINTYS ADVICE var errors = {}; errors.email = true; errors.cemail = true; errors.password = true; errors.cpassword = true; errors.username = true; function joinAjax (id) { var val = $('#' + id).val(); if (id == 'email') { $('#emailMsg').hide(); var reg = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/; if (val == '') { $('#' + id).after('<div id="emailMsg" class="error">Enter your email</div>'); } else if (reg.test(val) == false) { $('#' + id).after('<div id="emailMsg" class="error">Email invalid</div>'); } else { errors.email = false; $('#' + id).after('<div id="emailMsg" class="success">Email OK</div>'); } joinAjax('cemail'); } if (id == 'cemail') { $('#cemailMsg').hide(); var email = $('#email').val(); if (errors.email == false) { if (val != email) { $('#' + id).after('<div id="cemailMsg" class="error">Emails do not match</div>'); } else { errors.cemail = false; $('#' + id).after('<div id="cemailMsg" class="success">Success</div>'); } } else { $('#cemail').val(''); } } if (id == 'password') { $('#passwordMsg').hide(); if (val == '') { $('#' + id).after('<div id="passwordMsg" class="error">Enter a password</div>'); } else if (val.length < 6) { $('#' + id).after('<div id="passwordMsg" class="error">Minimum length of 6</div>'); } else { errors.password = false; $('#' + id).after('<div id="passwordMsg" class="success">Password OK</div>'); } joinAjax('cpassword'); } if (id == 'cpassword') { $('#cpasswordMsg').hide(); var password = $('#password').val(); if (errors.password == false) { if (val != password) { $('#' + id).after('<div id="cpasswordMsg" class="error">Passwords do not match</div>'); } else { errors.cpassword = false; $('#' + id).after('<div id="cpasswordMsg" class="success">Success</div>'); } } else { $('#cpassword').val(''); } } if (id == 'username') { $('#usernameMsg').hide(); if (val == '') { $('#' + id).after('<div id="usernameMsg" class="error">Enter a username</div>'); } else if (val.length < 3) { $('#' + id).after('<div id="usernameMsg" class="error">Minimum length is 3</div>'); } else { errors.username = false; $('#' + id).after('<div id="usernameMsg" class="success">Username available</div>'); } } $('#joinForm').submit(function(event){ if ((errors.email == true) || (errors.cemail == true) || (errors.password == true) || (errors.cpassword == true) || (errors.username == true)) { event.preventDefault(); } return true; }); } I addressed all of pointys advice, and added a few of my own changes. * *I changed the default values of errors to true and only changed them if they needed them to be false. Making it so I didn't have to change it to true on an error. *Changed values inside div to display error messages. *Rather than checking on the confirm if the original input for confirm is valid against a regex or length, I just check to see if the value of the error was false or not. Thanks every for your help, I hope people can learn from this. A: This stuff here is incorrect: errors[email] = null; errors[cemail] = null; errors[password] = null; errors[cpassword] = null; errors[username] = null; What you want instead is: errors.email = null; errors.cemail = null; errors.password = null; errors.cpassword = null; errors.username = null; Same for all the other references. The first form (the incorrect form currently in your code) would work if "email", "cemail", "password", etc. were all variables with some values to be used as keys. As it is, they're not defined at that point. The second form uses those names as property names. You could, alternatively, express the property names as strings and use brackets: errors["email"] = null; errors["cemail"] = null; errors["password"] = null; errors["cpassword"] = null; errors['username'] = null; Initializing those properties to null is not necessary anyway, really, unless your code is going to make a distinction between a missing property and a property that is present but with a null value. Later in your code, however, things get strange because you actually do define variables with those names and then continue to use them as indirect property name references. You might want to review the way object property reference syntax works in JavaScript. Oh, also, there's no need for an array anyway as you're not using numeric indexes. It should just be an object: var errors = {}; edit Looking through the jsfiddle, there are some other problems. There are recursive calls to you "joinAjax" function that don't make sense; I can't even tell what they're supposed to do. Then, when you detect errors, you set the error flag to "true" but then also use that value directly in the error message you show (below I've fixed the incorrect property references): errors.email = true; $('#' + id).after('<div id="emailMsg" class="error">' + errors.email + '</div>'); I don't know what you want to happen, but that looks kind-of weird to me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Size limit of a string passed to function as a parameter I have a function with one parameter like : function(a){/do something/} if I pass a string to the function then is there any size limit of string which I can pass? A: It's not defined in the standard ==> implementation dependant. A cool resource. Cool because Crockford is the first response, and the rest of the discussion quotes other known names in the JS world. As clarification, the limit is not going to be on the string size you can pass to the function, but just a limit on the string size that the language supports. I.e. if you have no concerns about the size of the string in one place, then passing it is fine. A: Passing by reference is always a great strategy. Passing the URI of the data resource (basically the pointer to the head of a list), dividing the data in chunks and retrieving / GET-ing the nodes in a linked list should be a good approach (look at CORS).
{ "language": "en", "url": "https://stackoverflow.com/questions/7530141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What is the best practise for a link that trigger javascript Let's say I have a label that triggers some javascript. For example: HTML: <a href="#" id="some_id">Trigger action!</a> <!-- or, with appripriate CSS : --> <span id="some_other_id">Trigger action!</span> jQuery: $("#some_id").click(function() { alert("some action") }); How do i best achieve that ? My question is what should I see in at the bottom left of the browser when I hover on the link ? ie, what the href value should be ? If the response is 'none', then the right method is with a span. Example of few methods : http://jsfiddle.net/M3qkU/5/ A: It depends on whether you're doing a web page or a web application. If you're doing a web page, try to have the link do something useful for people who don't have JavaScript enabled. That way, the JavaScript is enhancing the page rather than required for it to work at all. This is called progressive enhancement. For example: Suppose you have a page and you want it to have tabs. Put the tabs in elements in order, and give each tab's element an id value. The navigation links that take you to those tabs would have that id value in their fragment (e.g., #movies takes you to the movies element — the browser does this for you). Then when your JavaScript loads, have it turn those elements into tabs and take over the action of those links. If you're doing a web application, and the link triggers a "page change" or "tab change" sort of change in the UI, keep it as a link and make the href a fragment (e.g., #movies) that describes the "page" or "tab" that the application switches to when it happens. You could even use that information when processing the link, and you can use it when loading the page initially so your various page states become linkable. If the "link" doesn't cause a location-style change in the application, most of the time make it a button instead (you can style button elements to a very significant degree, though I wouldn't make them look like links). A: Two cases: * *if you have a fallback that works with javascript off (e.g. a login form that opens in an overlay can also be opened as a regular page), then use a <a> link which points to that page, with an onclick that triggers the overlay/javascript action. *if it's an element that has no fallback, don't use a <a> (e.g. something that triggers an inline editor) But whatever you do, don't use <a href="javascript:soemthing()"> because the user sees that as "url" of the link and it can be confusing. As for <a href="#">, I don't recommend it either (even if it's widely used) because like mentionned earlier, it doesn't point to a real location. The only benefit of using a <a> in such cases is that you get a hand cursor, but you can use cursor:pointer in CSS to have that cursor on your non-<a> elements. A: There's plenty of theories for this. Mine: * *an a tag should only be used when it's linking to content. In such cases, there should be a valid href. In situations where the linked content would be loaded on-page (modal, ajax, etc) then JS would over-ride the href and do its thing. *page-level interactions (buttons, clickable icons, etc.) should not be links, as without JavaScript, they serve no purpose. In that situation, they should use a different tag than a. Of course, I break those rules myself all the time. Technically, href="#" will cause the page to scroll to the top in most browsers. If you use this, then you have to be careful to always over-ride the href in your JS...which is easy to forget. As such, for pure javascript interaction a tags, I suggest using href="javascript:;"
{ "language": "en", "url": "https://stackoverflow.com/questions/7530143", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Android GridView empty I hope to have a little 'more than lucky and find someone who can help me ... Let me explain my idea of what I do have a list of strings on the left and right of the screen a list of icons that allow you to perform various operations on strings on the left This is about the idea that I need. I thought of various solutions and I think that is a grid that is more close to what I do, all h a problem ... Refine the list of strings, call the GridView ... and I do not print anything on screen, but the screen remains completely empty ... enter code public class TabelleActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.testo); GridView tabella = new GridView (this); tabella.setNumColumns(2); String[] cols = getResources().getStringArray(R.array.countries_array); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.main, cols); tabella.setAdapter(adapter); } Thank you for the patience A: First of all, you never add the GridView to the view displayed on screen. To do so, you must call ViewGroup.addView(View) method. For example, you can give an ID to your base layout and do something like : // get the base Layout LinearLayout mainLayout = (LinearLayout) findViewById(R.id.main_layout); // add the GridView to it mainLayout.addView(tabella); Nevertheless, after testing, I reached an IllegalStateException such as : 02-22 09:15:13.140: E/AndroidRuntime(1634): java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView Explanation is given by the official documentation of ArrayAdapter: A concrete BaseAdapter that is backed by an array of arbitrary objects. By default this class expects that the provided resource id references a single TextView. If you want to use a more complex layout, use the constructors that also takes a field id. That field id should reference a TextView in the larger layout resource. So, I need a new resource file to define the item (item.xml). It's like: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="5dp" > <TextView android:id="@+id/item_title" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout> Finally, I just have to use it in the ArrayAdapter for the GridView: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); LinearLayout mainLayout = (LinearLayout) findViewById(R.id.main_layout); GridView tabella = new GridView(this); tabella.setNumColumns(2); String cols[] = getResources().getStringArray(R.array.countries_array); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.item, R.id.item_title, cols); tabella.setAdapter(adapter); mainLayout.addView(tabella); } I got the expected behaviour, displaying the GridView. Need some adjustment to suit your needs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530148", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Testing an array of structures in mxunit What is the best way to test a function that returns an array of structres in mxunit? Right now i'm doing something like this: var actual = variables.pbj.getFunctions(); //returns [{name="getAccountNumber", value="0"},{name="getAccountName", value=""}] var found = false; //look for get account number for(var i = 1; i lte arrayLen(actual); i ++){ if(structKeyExists(actual[i],"name") && actual[i].name eq "getAccountNumber"){ found = true; break; } } if(NOT found){ fail("Struct key getAccountNumber didn't exist"); } found = false; //look for account name for(var i = 1;i lte arrayLen(actual); i ++){ if(structKeyExists(actual[i],"name") && actual[i].name eq "getAccountName"){ found = true; break; } } if(NOT found){ fail("Struct key getAccountName didn't exist"); } This feels somewhat kludgy and fragile. Anybody know of a better way? A: This is what I would do: var actual = variables.pbj.getFunctions(); //returns [{name="getAccountNumber", value="0"},{name="getAccountName", value=""}] for (thisStruct in actual) { if(NOT structKeyExists(thisStruct,"name") || thisStruct.name neq "getAccountNumber"){ fail("Struct key getAccountNumber didn't exist"); } if(NOT structKeyExists(thisStruct,"name") || thisStruct.name neq "getAccountName"){ fail("Struct key getAccountName didn't exist"); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7530151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Bad exp calc function? What is wrong with this function? When I use 31 for exp, this function becomes an infinite loop! How can I fix that? Please help and optimize this function for me if you can, thanks. public function exp_calc($exp) { $level2 = 30; // Required EXP for 2nd level $current_lvl = 0; // Current level $level = 0; // Required EXP for next level while((int)$level <= $exp) { $level += $level2; $level2 *= 0.25; $current_lvl++; } if($current_lvl >= 80) $current_lvl = 80; return array ($current_lvl, (int)$level); } A: $level2 *= 0.25; 1 2 3 30 7.5 1.125 I assume you mean *= 1.25 there, to increase the amount of experience needed for the next level exponentially :). The current function limits somewhere below 40 I think (get some calculus to calculate the limit ;)). Edit; to clearify (since I though it wasn't yet): level one requires 30 exp total now; level two requires 7.5 additional exp; total of 37.5 level three requires 1.125 exp; total of 38.625 etc. When using *= 1.25; the amount of exp needed to reach the next level actually increases: 30 -> 37.5 -> 46.875 -> 58.594 -> etc A: I'm not sure what you want the outcome to be, but the reason it becomes an infinite loop is that every iteration you make $level2 smaller (a quarter of its size) until eventually it will practically become 0. The loop won't exit until $level is as great as (or equal) to $exp, which will never happen once $level2 becomes 0. Without doing the maths I guess 31 is the threshold that can never be reached as $level2 becomes too small to increment by.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google Maps - How to make the marker a link that opens in a lightbox I have created a google maps page with custom markers and locations. I want the user to be able to click on the marker of a location and it opens a lightbox on that page. Is this possible? Thanks! A: You'll want to check out this documentation page, on Google Maps event handling: http://code.google.com/apis/maps/documentation/javascript/events.html#EventListeners ...and from that page... google.maps.event.addListener(marker, 'click', function() { map.setZoom(8); }); Note that this simply calls a map function (setZoom); it's up to you to launch any custom lightbox you might want, assuming you don't want to use a GoogleMaps-style popup of some kind.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Draw invalidated rectangle using WM_PAINT In order to draw a text over a ComboBox (or whatever else), I override WndProc() and catch 0x000F message -- which is WM_PAINT. Code is like the following: Protected Overrides Sub WndProc(ByRef m As Message) MyBase.WndProc(m) If m.Msg = &HF Then TextRenderer.DrawText(CreateGraphics, "The text over my control.", Font, _ ClientRectangle, ForeColor) End If End Sub It works very well, but there is a problem: if I drag parent window on a side of the screen (in order to hide a part of the window form), the visible part of my control is infinitely redrawn. This makes the text redrawn over itself! I suppose there is a way to draw only invalidated (hidden) part of the control. How can I do? EDIT Here is the problem in one picture: http://i.stack.imgur.com/WqGfI.png (it's a link since I can't post image for now.) UPDATE I tried using BeginPaint API, but the RECT structure included in the returned PAINTSTRUCT structure contains only zeros. If m.Msg = WM_PAINT Then Dim ps As PAINTSTRUCT = New PAINTSTRUCT BeginPaint(Handle, ps) Console.WriteLine(ps.rcPaint.right) 'painting goes here EndPaint(Handle, ps) End If Can I do something with that? I don't know how to proceed, in order to paint only invalidated area. A: A good rule of thumb is, never use Me.CreateGraphics. Try changing your code to this: <DllImport("User32.dll")> _ Public Shared Function GetWindowDC(ByVal hWnd As IntPtr) As IntPtr End Function <DllImport("user32.dll")> _ Private Shared Function ReleaseDC(ByVal hWnd As IntPtr, ByVal hDC As IntPtr) As Boolean End Function Protected Overrides Sub WndProc(ByRef m As Message) MyBase.WndProc(m) If m.Msg = &HF Then Dim dc As IntPtr = GetWindowDC(m.HWnd) Using g As Graphics = Graphics.FromHdc(dc) TextRenderer.DrawText(g, "The text over my control.", Font, _ ClientRectangle, ForeColor) End Using ReleaseDC(m.HWnd, dc) End If End Sub A: You might be attempting to paint when there has been no actual update. Part of the PAINTSTRUCT indicates whether the window should actually be erased. Here's what I've used in the past. GetUpdateRect allows you to easily see if anything has actually been updated as well as get the updated region without having to call BeginPaint. Remember, BeginPaint is only when you're not passing the message down to your base class. (I'm subclassing using the NativeWindow class in this snippet.) Dim hasUpdates As Boolean Dim updRect As RECT Dim r As Rectangle hasUpdates = GetUpdateRect(_parentControl.Handle, updRect, False) With updRect r = New Rectangle(.Left, .Top, .Right - .Left, .Bottom - .Top) End With ' Invalidate the control so that the whole thing will be redrawn since ' our custom painting routine could redraw the entire client area. If hasUpdates Then _parentControl.Invalidate(r) ' Pass the message along to be handled by the default paint event. MyBase.DefWndProc(m) ' Now draw extras over the existing control. If hasUpdates Then Me.PaintExtras(r) So what you would do is exit the routine if hasUpdates is False. As far as the graphics to use to draw, I've had success using Graphics.FromHwnd(ctrl.Handle)
{ "language": "en", "url": "https://stackoverflow.com/questions/7530166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Add shortcut to application's menu I am trying to create an application which adds a menu item to the android installed applications menu. I have been successful at creating homescreen menu but still want my shortcut to be added to the applications menu as well. Is this possible? if so, how can i accomplish this? Thanks A: Seems like you cannot add a shortcut icon to the list of application installed on your device but only to the homescreens. Thanks guys
{ "language": "en", "url": "https://stackoverflow.com/questions/7530167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }