Posts

Showing posts from February, 2011

struts2 - Regarding Struts configuration files -

where need put struts configuration files in web application? and, differences between struts.xml , struts-config.xml? struts 2 applications, 1 should use? thanks. as indicated in vinodh's link, struts.xml default name of configuration file in struts2. struts-config.xml struts1 configuration file, , should not used in struts2. your struts.xml file should @ root of class path once web app built, located in web-inf/classes. can accomplish placing in source folder. if use maven 2 standard directory layout, place in src/main/resources.

android - "realtime" search using AsyncTask? -

i writing application searches database in "realtime". i.e. user presses letters updates search results list. since search can take while, need search in background , allow new key presses re-start search. user presses 'a' (and code starts searching "a"), presses 'b' - code not wait "a" search end, start searching "ab", rather stop "a" search, , start new "ab" search. to decided search in asynctask. wise decision ? now - whenever keypress detected, test see if have asynctask running. if - signal (using boolean within asynctask) should stop. set timer re-test asynctask within 10 msec, see if terminated, , start new search. is smart method ? or there approach take ? tia first yes, asynctask way this. problem see approach timer waiting watch die. when invoke asynctask hold onto reference of it. let keep state know if it's out searching or it's has returned. when user clicks l

php - mysql fastest 2 table query -

situation: 2 tables, first (persons) storing person names , other data, , second (phones) storing phone numbers. there can multiple phone numbers per person (thats why using separate tables in first place). goal: select in end i'd have php array this: array ( '0' => array ( 'name' => 'john smith' // other values table persons... 'phones' => array('0' => '12345', '1' => '324343') // phones table ), '1' => array ( 'name' => 'adam smith' // other values table persons... 'phones' => array('0' => '645646', '1' => '304957389', '2' => '9435798') // phones table ) ); etc. phones.person_id = persons.id what fastest way this? fastest in sense of program execution time, not coding time. simple join in case i'd many dupli

c# - Connecting to a TcpListener on a different thread, same process -

i'm trying unit test comm. code on tcp in c#. i've created quick thread stands tcplistener. each time tcpclient tries connect "only 1 usage of each socket address (protocol/network address/port) permitted" exception. can not host on , connect same port in same process? [test] public void foo() { thread listenerthread = new thread(tcplistenerthread); listenerthread.start(); thread.sleep(5000); tcpclient client = new tcpclient(new ipendpoint(ipaddress.loopback, 1234)); } private void tcplistenerthread() { tcplistener listener = new tcplistener(ipaddress.any, 1234); listener.start(); tcpclient socket = listener.accepttcpclient(); streamwriter writer = new streamwriter(socket.getstream()); writer.write(file.readallbytes("../../random file.txt")); } you using wrong constructor of tcpclient - 1 binds client local address , port , end

Android application error on starting new activity -

i'm having problem in android 1.6 app. have 2 java class files,each corresponding xml layout file. when perform following: intent ii = new intent(this, patiententry.class); startactivity(ii); i application error: sorry! application xxxx has stopped unexpectedly. please try again. i have added following androidmanifest.xml file: why getting these errors , how fix it? thanks mike make sure add patiententry activity manifest file. <activity android:name=".patiententry"></activity>

why does this regex work outside of a javascript function but not inside of it? -

okay i'm kind of new regexps in general, let alone in javascript. trying work on form validation project , found site have list of useful sample regexps various things here has few email validation, i'm attempting @ moment. anyway, following example form validation on w3schools able working using example , regexp works outside of javascript function, reason when call inside function returns value of undefined. here's code: <html> <head> <title>formzz validate-jons</title> <script type="text/javascript"> pattern = new regexp("^[0-9a-za-z]+@[0-9a-za-z]+[\.]{1}[0-9a-za-z]+[\.]?[0-9a-za-z]+$"); function valid8email(field, txt) { with(field) { //at_pos = value.indexof('@'); //dot_pos = value.lastindexof('.'); if(!pattern.test(value)) //at_pos < 1 || (dot_pos - at_pos) < 2) { alert

android - Programmatically activate loudspeaker when receiving phone call -

hey..i plan add function app auto switch on loudspeaker when user received phone call.. here part of codes: case telephonymanager.call_state_offhook: //call_state_offhook; setvolumecontrolstream(audiomanager.stream_voice_call); am.setmode(audiomanager.mode_in_call); am.setspeakerphoneon(true); boolean check = am.isspeakerphoneon(); toast.maketext(speaker.this, "loudspeaker on: "+ check,toast.length_long).show(); and added permission modify_audio_settings in manifest..however..the speakerphone didnt manage turn on..can kindly give helping hand on problem..thanks in advance..by way..this app implement in android 2.1 try hold 500 ms before turning on .. so : case telephonymanager.call_state_offhook: // call_state_offhook; try { thread.sleep(500); // delay 0,5 seconds handle better turning on // loudspeaker

c# - Help files .. formats? -

i found interesting discussion regarding file formats , future direction may take. @ crossroad our new .net project in need decide on best format our file documentation. here discussion mentioned above; the future direction of file formats our current line of thinking build html file local user. possible compile html (graphics , pages) 1 file can shipped, opposed many individual files? tidiest solution. chm obvious choice seems on out. any thoughts? .hlp files way out, .chm still around, , think while. apps either have own propitiatory ones(vs, flash, etc) or use .pdf or .chm. saying, pdf unsuitable, should use .chm. from reading article, talking .hlp files, .chm files supported desktop operating systems, including vista/7. i wouldn't use mhtml, because default browser ie , lot of people don't it. another other option put of html/image etc files in zip. write custom browser(probably webbrowser control) , read html/image files zip.

Perl Archive::Tar -

i want archive txt files file::find, delete source files , remove empty directories. i'm having difficulties renaming files '$tar->rename( );' because i'd to strip them full path names , use parent directory/*.txt, whatever try code renames 1 file. don't know appropriate place execute 'unlink' function. thanks. use strict; use warnings; use archive::tar; use file::find; use file::basename; $dir = "e:/"; @files = (); find(\&archive, $dir); sub archive { /\.txt$/ or return; $fd = $file::find::dir; $fn = $file::find::name; $folder = basename($fd); $file = $_; push @files, $fn; $tar = archive::tar->new(); $tar->add_files(@files); $tar->rename( $fn, $folder."\\".$file ); $tar->write($fd.'.tar'); unlink $fn; finddepth(sub{rmdir},'.'); } you using file::find interface incorrectly. archive sub gets called once on every file f

c# - best way to display multi-columned data in grid format in winforms? -

what best way display multi-columned data in grid format using c# winforms? is listview or datagridview? datagridview best bet simple grid display. however, if needing nested (collapsible/expandable) display child rows, etc. datagridview not that. the listview way windows explorer displays objects, properties, files, etc.

java - Maven module as dependency on a Web Application -

ich have tree modules projec, server,client , core. core module should imported jar dependency in other modules. on eclipse see no warnings, if i'm starting application i'm getting following error : caused by: org.springframework.beans.factory.cannotloadbeanclassexception: error loading class [at.ac.tuwien.inso.verteilte.service.helloserviceimpl] bean name 'helloserviceimpl' defined in servletcontext resource [/web-inf/appcontext.xml]: problem class file or dependent class; nested exception java.lang.noclassdeffounderror: at/ac/tuwien/inso/verteilte/services/ihelloservice caused by: java.lang.classnotfoundexception: at.ac.tuwien.inso.verteilte.services.ihelloservice this interface imported on helloserviceimpl. helloserviceimpl created on beans following : <jaxws:endpoint id="helloservice" implementorclass="at.ac.tuwien.inso.verteilte.service.helloserviceimpl"> i have removed namespaces because of link protection of stackoverflow :

Problems with jquery and a special selector -

friends, have problem, want access element jquery li, unfortunately these li elements have ids follows: <li id='abc-2\textbox'>...</li> <li id='xop-2\listbox'>...</li> i tried item following expressions, none work. $('#abc-2\textbox') $('#abc-2\\textbox') $('#abc-2//\textbox') $('#abc-2\\\textbox') i guess problem \ character, me? $('#abc-2\\\\textbox') (use 4 slashes)

extjs - how to define jsonstore for dynamic series in charts? -

i want add in series dynamically chart. instance, have grid of unknown number of products. when clicked on particular row, sales statistics of product added chart. therefore, there may multiple lines on chart. the question is, how define fields of jsonstore yfield of series not know beforehand? i stumbled across same problem. searched official forum bit, , seems official way: you define new store fields, , use bindstore method: http://docs.sencha.com/ext-js/4-0/#!/api/ext.chart.chart-method-bindstore don't forget define appropriate series (setseries-method) , reload store redraw chart.

How to add a vertical scroll bar to a dojo select? -

i’m dynamically populating dojo select widget, list seems abnormally long. how can add vertical scroll bar it? size attribute doesn’t work here. if you're using dijit.form.select there's attribute called maxheight controls height of dropdown.

c++ - WinApi control doesn't show on the main window -

hello have following win32 program, , have edittext control doesn't show on screen. there meant 2 edittext controls drawn on main window, 1 shows, why this? full code #include <windows.h> #include <iostream> #include "resource.h" using namespace std; const int buffermax = 512; char server_ip[buffermax]; int port; const char windclassname[] = "windowclass"; lresult callback wndproc(hwnd hwnd,uint msg,wparam wparam,lparam lparam); int_ptr callback aboutdialog(hwnd hwnd,uint msg,wparam wparam,lparam lparam); int_ptr callback connectwin(hwnd hwnd,uint msg,wparam wparam,lparam lparam); int winapi winmain(hinstance hinstance,hinstance hprevinstance,lpstr lpcmdline,int ncmdshow){ wndclassex parent_window; hwnd hwnd; msg msg; parent_window.cbsize = sizeof(wndclassex); parent_window.style = 0; parent_window.lpfnwndproc = wndproc; parent_window.cbclsextra = 0; parent_window.cbwndextra = 0; parent_window.hinst

swing - Java JTable TableCellRenderer With ImageIcon Column -

i have table custom table model has 2 columns. column 0 imageicon class, , column 1 string class. public class<?> getcolumnclass(int col) { if (col == 0) { return imageicon.class; } else { return string.class; } } when define new tablecellrenderer class added columns can style cells, overwrites imageicon class , sets string. public class customtablecellrenderer extends defaulttablecellrenderer { public component gettablecellrenderercomponent (jtable table, object obj, boolean isselected, boolean hasfocus, int row, int column) { component cell = super.gettablecellrenderercomponent(table, obj, isselected, hasfocus, row, column); if(isselected) cell.setbackground(color.blue); return cell; } } any ideas on how fix this? my mistake, sort of hidden: when define new tablecellrenderer class added columns can style cells, overwrites imageicon class , sets string. so problem that, when define tab

java - Screen display size -

hi i'm writing graphics program , i've been searching way physical size of screen being used. can size of screen in pixels , logical resolution. can't seem find anywhere physical dimensions in specs monitor (eg 19"- 376 x 301 mm). question, information stored anywhere in os when loads driver particular screen being used? program i'm writing needs work on mac , windows. thanks! nt i don't think it's possible java. can try write jni code if feature absolutely essential in program. otherwise, ask user monitor size. edit looks swt can give dpi, , can calculate monitor size it: http://www.java2s.com/code/javaapi/org.eclipse.swt.graphics/devicegetdpi.htm but, you'd have use swt :) not bad choice if want develop good-looking programs mac.

flex - TLF 2.0 in Flash CS5 -

i trying figure out how can implement new text layout framework 2.0 in flash cs5. there flex , flashbuilder4 examples, nothing relating flash cs5. how update flash cs5 support tlf2. i particularly interested in creating new list/bullets features example code flash great. here source: http://sourceforge.net/adobe/tlf/home/ thank in advance, , happy holidays. try replacing new .swc current 1 (save current 1 incase new .swc messes install). textlayout.swc adobe flash cs5 located here: / adobe flash cs5 / common / configuration / actionscript 3.0 / libs / 11.0 / textlayout.swc you must restart flash cs5 changes take effect. update it doesn't work. well, doesn't work the text tool in ide can target new .swc of .as classes. however, approach less ui-friendly you'll have code without text tool. we'll have wait adobe update flash cs5 include new tlf 2.0 support in ide.

javascript - How to remove a class from a page inside onclick html attribute? -

so how can remove class html elements on page? i need to inside onclick html element. so: <div onclick="remove class 'someclass' elements on page"></div> here raw javascript solution (removes some_class class elements in document): onclick=" (var = 0, elements = document.getelementsbytagname('*'); < elements.length; i++) { var attr = elements[i].getattribute('class'), newattr = attr.replace(/\bsome_class\b/i, ''); if(newattr != attr) elements[i].setattribute('class', attr); } "

javascript - how to make a text in one line in php -

in js code must 1 line when add text db make 2 lines , not work like function(varone,asdasdasd adasd); i want it function(varone,asdasdasdadasd); how can make php smarty useed {strip} , {ldelim} , not worked used tirm not worked too you try $data = str_replace("\r\n", "", $data); if html, try function nl2br()

html - Radio Button and an Input field -

i wanna set form users can choose set of radio buttons , if dont choice can use last radio button have text field can enter custom text. i have seen on few sites. wondering , how implemented i made example, wanted? http://www.jsfiddle.net/t7ge7/ var temp = ''; function disabletxt() { var field = document.getelementbyid("other"); if(field.value != '') { temp = field.value; } field.style.display = "none"; field.value = ''; } function enabletxt() { document.getelementbyid("other").style.display = "inline"; document.getelementbyid("other").value = temp; }

spring - Is it possible to read static text dynamically from property files in velocity template? -

greetings have java ee application (spring framework) uses vm templates contains static texts like: <span> hello world </span> to like: <span> <fmt:message key="hi.message" /> </span> and wondering if it's possible read texts property file(en/fr) depending on user locale in jsp, use 1 template locales , text dynamic note: velocity not view technology used in app, using it's templates in sending emails only. spring mvc comes (very) useful velocimacros (see spring mvc documentation ). 1 of them #springmessagetext. in hello.vm file: <span>#springmessagetext("hi.message", "hello default!")</span> this macro read message message sources, depending on current locale (using built-in resourcebundlemessagesource spring). messages_fr_fr.properties hi.message=bonjour messages_en_gb.propertie hi.message=hello if no bundle available current locale, default message "hello defa

What is a simple to implement jQuery slider with multiple pictures? -

i'm searching slider has multiple images. 3 images on row, , when slides shows 3 images. anyone know 1 easy implement , styleable? thanks! jcarousel, as mentioned , excellent. if want light-weight implementation prefer jcarousel lite 2kb , yet still fully-featured.

winforms - ArgumentOutOfRange Exception in c# -

i'm trying access column name of selected row in datagridview control in windows form, i'm getting argumenoutofrange exception of following code: messagebox.show(datagridview1.selectedcolumns[datagridview1.currentcell.columnindex].tostring()); producing: argumentoutofrangeexception unhandled index out of range. must non-negative , less size of collection. parameter name: index could please tell me how can overcome error? the datagridview.selectedcolumns collection separate collection datagridview.columns , can have different set (a subset) of columns. for example if have 5 column view, , third , fourth selected, datagridview.selectedcolumns.count == 2 datagridview.columns.count == 5 and of using fourth column (index of 3) code becomes datagridview.selectedcolumns[3] which blows (rightly) indexoutofbounds. to sum up, in case, should using columns property, , not selectedcolumns.

jQuery - Cycle alternate <li>'s? -

Image
on site developing i'm trying cycle through load of <li> 's, @ alternating times. example: to start off i'd showing first 2 <li> items. item 1 fade out. item 3 fade in, in place of item 1. item 2 fade out. item 4 fade in, in place of item 2. html: <ul> <li>item 1</li> <li>item 2</li> <li>item 3</li> <li>item 4</li> </ul> any idea how can achieve effect? thanks! you (could simplified further): $("#items li").slice(2).hide(); var index = false; setinterval(function() { $("#items li").eq(index).fadeout(function() { $("#items li").eq(2).insertafter(this).fadein(); $(this).appendto("#items"); index = !index; }); }, 3000); this gives <ul> , id make faster work work: <ul id="items"> , you can test out here . before ask, yes i'm blatantly abusing weak typing treat index b

ASP.Net Cookie Problems -

i have cookie when user loges in: httpcookie cookie = new httpcookie("username"); cookie.expires = datetime.now.adddays(1.0); cookie.value = txtusername.text; response.cookies.add(cookie); and reads out in login-page when user visit again: if (response.cookies["username"] != null) txtusername.text = response.cookies["username"].value; but when log in, , after log out directly, cookie deleted. has neither exp-date nor value saved. whot wrong? if (response.cookies["username"] != null) txtusername.text = response.cookies["username"].value should if (request.cookies["username"] != null) txtusername.text = request.cookies["username"].value

Using MYSQL replication to speed up Schema changes and table optermise -

i hear many people use master - slave arrangements improve time taken when changing schemas using replication setup new temporary master, stopping relocation , swapping roles before starting again. have found example (below) found on stack overflow. setup slave stop replication. make alter on slave let slave catch master swap master , slave, slave becomes production server changed structure , minimum downtime this well, however, dont understand step 4 isn't clear me. i wonder if please explain procedure clearer. let slave catch master let slave catch master meaning slave 0 seconds behind master. this mean if replication stopped @ point (for alter table), register last replication time. when replication resume, compare current write on master last replication time on slave. however, procedures seems flaw . cannot alter slave and expecting schema in updated slave same master . in events column type changed, column droppe

java - how to get the object from a redirected view? -

im using spring mvc, java , annotations. @requestmapping(value = "/submittask", method = requestmethod.post) public modelandview submittask(httpsession session, httpservletrequest request) { map<string, object> map = new hashmap<string, object>(); modelandview model = new modelandview(new redirectview("home.html")); map.put("email", request.getparameter("email")); map.put("task",request.getparameter("task")); map.put("error", request.getparameter("error")); model.addobject("map", map); return model; } @requestmapping("/home") public modelandview home(httpsession session, httpservletrequest request) { modelandview model = new modelandview("home"); model.addobject("map", request.getparameter("map")); return model; } i don't seem value of "map" via "req

animation - jquery shine effect, animate without hover as a trigger -

i using amazing jquery shine time addy osmani. works fine since did copied , pasted :d but need shine effect automatically animate periodically image loads without having hovered first, how can achieve ? honest have 0 knowledge when comes jquery , or javascript here's code: <script type="text/javascript"> $(document).ready(function(){ /*your shinetime welcome image*/ var default_image = 'images/large/default.jpg'; var default_caption = 'welcome shinetime'; /*load default image*/ loadphoto(default_image, default_caption); function loadphoto($url, $caption){ /*image pre-loader*/ showpreloader(); var img = new image(); jquery(img).load( function(){ jquery(img).hide(); hidepreloader(); }).attr({ "src": $url }); $('#largephoto').css('background-image','url("' + $url + '")'); $('#larg

How to open the application on an iPad from a webpage? -

we need start application on ipad when user clicks on button in web page. please let know code snippets link added in web page open application on ipad. planning create web page using asp.net technology. this might you're looking for: http://applookup.com/2010/09/iphone-apps-with-special-url-shortcuts/ updates : link above dead. , cdm9002 suggested, love of dogs, here information (credits goes ios developer tips ) first of all, need use method uiapplication:openurl: launch application webpage. example, can launch apple mail in way: [[uiapplication sharedapplication] openurl:[nsurl urlwithstring:@"mailto://info@iphonedevelopertips.com"]]; to launch own application, there 2 things do: register custom url schemes , handle url launch in application. to register custom url schemes, edit info.plist. below custom scheme 'myapp' registered. cfbundleurltypes cfbundleurlschemes myapp cfbundleurlname com.yourcompany.myapp now,

How do you handle adding something like Devise authentication in BDD stories? -

if have set of bdd scenarios like: user should able register user should able login user should able reset password etc., write first scenario, write code make pass, , refactor. but if use devise, which, once correctly installed , configured, gives these features @ once, best practice that? because, if write first test , configure devise test passes, other tests write should automatically pass without having failed before. or having tests fail first not strictly necessary in bdd workflow, , should happy tests pass? with bdd, should focus on value you're providing users or stakeholders. logging in isn't valuable, i'd give them log in for first. then scenarios become easy, either: given fred logged in when fred buys book... or given fred on home page when fred buys book... logging in has no value, , apologise being 1 of people who's used bdd example in previous years. don't log in unless need to, , don't code first. i'd writ

c# 4.0 - Can we split the Filepath from the last folder in C#? -

for example have file isample.cs in path "d:\test_source\cv\source code\army.data\proceduresall\isample.cs" here wanna file-path "proceduresall\isample.cs" before don't wanna path.here using folder browser choosing folder. please me regarding this. you mean this? string path = @"d:\test_source\cv\source code\army.data\proceduresall\isample.cs"; //isample.cs path.getfilename(path); //d:\test_source\cv\source code\army.data\proceduresall path.getdirectoryname(path); //proceduresall path.getdirectoryname(path).split(path.directoryseparatorchar).last(); use path.combine("proceduresall", "isample.cs") proceduresall\isample.cs (using above these strings).

regex - Regular expression doesn't match if a character participated in a previous match -

i have regex: (?:\s)\++(?:\s) which supposed catch pluses in query string this: ?busca=tenis+nike+categoria:"tenis+e+squash"&pagina=4&operador=or it should have been 4 matches, there 3: s+n e+c s+e it missing last one: e+s and seems happen because "e" character has participated in previous match (s+e), because "e" character right in middle of 2 pluses (teni s+e+s quash). if test regex following input, matches last "+": ?busca=tenis+nike+categoria:"tenis_e+squash"&pagina=4&operador=or (changed "s+e" "s_e" in order not cause "e" character participate in match). would please shed light on that? thanks in advance! you correct: fourth match doesn't happen because surrounding character has participated in previous match. solution use lookaround (if regex implementation supports - javascript doesn't support lookbehind, example). try (?<!\s)\++(

c - How to cast program argument *char as int correctly? -

i'm on mac os x 10.6.5 using xcode 3.2.1 64-bit build c command line tool build configuration of 10.6 | debug | x86_64. want pass positive integer argument, i'm casting index 1 of argv int. seems work, except seems program getting ascii value instead of reading whole char array , converting int value. when enter 'progname 10', tells me i've entered 49, when enter 'progname 1'. how can c read entire char array int value? google showed me (int)*charpointer, doesn't work. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> int main(int argc, char **argv) { char *programname = getprogramname(argv[0]); // gets name of executable if (argc < 2) { showusage(programname); return 0; } int thenumber = (int)*argv[1]; printf("entered [%d]", thenumber); // entering 10 or 1 outputs [49], entering 9 outputs [57] if (thenumber % 2 != 0 || thenumber <

c# - DataView rowfilter with 2 levels of parents -

how can create dataview rowfilter 2 levels of parent relations? within 1 level, can like: "parent(nameoftherelation).id_something = " + 17 however, 2 levels don't know do? can shed light on can try next? define expression column on parent table... datatable dtgrandparent, dtparent, dtchild; datacolumn datacolumn = new datacolumn("somefield"); datacolumn.expression = "parent(nameofparenttograndparentrelation).somefield"; dtparent.columns.add(datacolumn); dataview dv = new dataview(dtchild); dv.rowfilter = "parent(nameofchildtoparentrelation).somefield";

android - Getting Out of memory error when reading images from SDcard -

i developing simple application imageview, when imageview clicked application should open device image gallery. achieve using following code intent imageintent=new intent(intent.action_pick); imageintent.settype("image/*"); startactivityforresult(imageintent,5); and activityresult super.onactivityresult(requestcode, resultcode, data); if(requestcode == 5) { cursor cursor; uri uri=data.getdata(); if(uri!=null) { cursor=getcontentresolver().query(uri, new string[]{ android.provider.mediastore.images.imagecolumns.data }, null, null, null); cursor.movetofirst(); string imageid=cursor.getstring(0); personimage.setimageuri(uri); log.i("imageid", ""+imageid); cursor.close(); } } the selected image displayed in imageview. problem when doing second time getting following exception. 12-01 19:31:52.

.net - asp.net application, sql server & web services -

i have no experience on connecting web apps sql server on different machine through web services. are there standard web services supposed used? also, why wouldn't possible connect sql server on "normal" way? edit: basically, i'm working on new web application needs database. client came saying have server it's accessible web services. hope helps. thanks edit 2: - have better understanding ot f now. mark answers answers system allows 1 : ) the client came saying have server it's accessible web services. this me means have web services setup application need connect , call in order access database. in case "standard" web services ones client provides. if client says going need use web services, well, that's way going have @ data.

php - Converting a number with comma as decimal point to float -

i have list of prices comma decimal point , dot thousand separator. some examples: 12,30 116,10 1.563,14 these come in format third party. want convert them floats , add them together. what best way this? number_format doesn't seem work format, , str_replace seems overkill, have more once on each number. is there better way? thanks. using str_replace() remove dots not overkill. $string_number = '1.512.523,55'; // note: don't have use floatval() here, it's prove it's legitimate float value. $number = floatval(str_replace(',', '.', str_replace('.', '', $string_number))); // @ point, $number "natural" float. print $number; this least cpu-intensive way can this, , odds if use fancy function it, under hood.

How to set number of dropped down items in WinForms combobox? -

do know if it's possible change amount of items displayed in combobox after it's been dropped down? (something row count) shows 8 items default, , have huge screens , lot of items in list, nice show larger combobox. the property you're looking maxdropdownitems .

vim colorschemes not changing background color -

i try apply various color schemes in vim have seen on net. whatever scheme choose, background remains white, though screenshots of applied scheme shows background should colored. in schemes, of background change color, space right of lines containing text still remains white. i'm using vim 7.2 on mac. have started messing non-gui applications, should pretty out of box.. does overall settings terminal window have it? when running macvim, looks ok. when starting vim terminal things looks strange.. i have in .vimrc , solved problem me using while using putty. set t_co=256 set background=dark colorscheme mustang highlight normal ctermbg=none highlight nontext ctermbg=none it's important load colorscheme before ctermbg settings in .vimrc because need override same ones set colorscheme. means can't switch colorscheme while vim running , expect work.

c# - Crystal report to send report directly to default printer -

i'm trying send report direct default printer , running ok code: doc.load(server.mappath("~\\reports\\crystalreport\\documentcrv.rpt")); doc.setdatasource(dsreport); doc.printtoprinter(1, true, 0, 0); the problem works when i'm running webapplication on dev machine (so, i'm assuming it's getting default printer server, not user's printer) there no way directly print users printer web server, unless possibly on same internal network / directory. management nightmare. your best bet pop open viewer , print dialog. i did use active x control enumerate end users printers , automatically print it. however, ie , poorly maintained.

iphone - Adding a custom subview on UIScrollView activates subview's viewDidLoad but a blank view appears instead of the subview -

if change color of uiscrollview , add buttons around or whatever, it's active. nevertheless, can't see of added subview (who's viewdidload got called , nslogged ). relevant code: linetime *controller = [viewcontrollers objectatindex:page]; if ((nsnull *)controller == [nsnull null]) { controller = [[linetime alloc] initwithpagenumber:page]; [viewcontrollers replaceobjectatindex:page withobject:controller]; [controller release]; } // add controller's view scroll view if (controller.view.superview == nil) { //nslog(@"i'm ok"); nslog(@"%d page", page); cgrect frame = scrollview.frame; frame.origin.x = frame.size.width * page; frame.origin.y = 0; controller.view.frame = frame; [self.scrollview addsubview:controller.view]; controller.resultarray = timesarray; controller.alternatesarray = alternatesarray; } basiclly taken apple's example code , merging app's code failed. , ideas?

rpmbuild - my RPM package requires 2 already installed shared libraries -

i'm looking making rpm packages. i created first rpm package rpmbuild. package simple. has copy several config files , 1 executable. i cannot install .rpm because 2 shared librairies used executable required. these librairies installed not linked .rpm package because build them 1 of projects. there located in /usr/myproject/lib directory. i tried put symbolic links /lib , /usr/lib, tried run "ldconfig" update .conf file contains /usr/myproject/lib directory, , tried update ld_library_path env variable without success. i know can ignore dependencies using -nodeps command line option i'd in next step create own yum repository yum not allow install package if dependencies not fulfilled. i prefer keep automatic dependency feature of rpmbuild enabled. thanks in advance. package these 2 libraries in rpm, can install both rpms in 1 rpm -i call.

Delphi function to convert Result of WrapText to TStringList -

i use function insert carriage returns on string nicely formatted emailing: m := wraptext(m, #13#10, ['.',' ',#9,'-'], 60); the problem email client has 1023 character limit when processing strings. if original length of m greater 1023, gets truncated (note: email client has events handle situation, think easier approach feed strings less limit). i looking " wraptexttostringlist " function this: var mstringlist: tstringlist; begin mstringlist := wraptexttostringlist(m, #13#10, ['.',' ',#9,'-'], 60); so passed 220 character body of email message. results string list approximately 4 entries. i think boils down creating function parses string @ #13#10 string list. anyone got one? tstringlist has built-in method parse string @ #13#10 string list. mystringlist := tstringlist.create; mystringlist.text := mystring; this populate list parsing string , creating new entry in list whenever finds r

regex - JavaScript: "Dynamic" back reference RegExp replacement -

i want make replacements this: var txt = "some text containing $_variable1 , $_variable2 inside of well."; var rx = /(\$_[a-z]+)/g var $_variable1 = "a cat"; var $_variable2 = "a hotdog"; var replaced_txt = txt.replace(rx, $1); i want replaced_txt equal "...containing cat , hotdog ins...", way achieve i've found far this: var replaced_txt = txt.replace(rx, function($1){return eval($1)}); and have feeling not elegant solution, no? preferably i'd avoid eval() i'm grateful ideas on this! /c you can this: var values = { '$_variable1': 'a cat', '$_variable2': 'a hotdog' }; var replaced_txt = txt.replace(rx, function(_, varname) { return values[varname] ? values[varname] : '<unknown variable: ' + varname + '>'; });

model view controller - positioning edit-form Popup for telerik mvc grid -

can tell me if there way position edit-form popup mvc grid align center of screen? thanks guys valid answers. know can position custom popup window not built in edit mode windows. however manipulated position jquery on client side on_edit api of telerik grid. var popup = $("#" + e.currenttarget.id + "popup"); popup.css({ "left": ($(window).width()/2 - $(popup).width()/2) + "px", "top": ($(window).height()/2 - $(popup).height()/2) + "px" }); e.currenttarget.id gives gridname.

hash - Comparing Data Graphs Using C# GetHashCode() -

i have graph of data i'm pulling oauth source using several rest calls , storing relationally in database. data structure ends having 5-10 tables several one-to-many relationships. i'd periodically go re-retrieve information see if updates necessary in database. since i'm going doing many users , data not change often, goal minimize load on database unnecessarily. strategy query data oauth provider hash results , compare last hash generated same dataset. if hashes don't match, start transaction in database, blow away data user, re-write data, , close transaction. saves me time of reading in data database , doing compare work see what's changed, rows added, deleted changed etc. so question: if glue data in memory big string , use c# gethascode(), reliable mechanism check if data has changed? or, there better techniques skinning cat? thanks yes, that's reliable mechanism detect changes. not know probabilty of collisions in gethashcode() m

c# - Why can I compare sbyte to all the other numeric types *except* ulong? -

you can >, <, ==, etc. comparisons between sbyte , byte, int, uint, short, ushort, long, double, , float. not ulong. my brain exploding. can explain why sbyte can compared uint not ulong? public bool sbyte_ulong_compare(sbyte x, ulong y) { return x < y; // compiler error cs0019 } also, using unchecked doesn't make things work better. brain melting. another edit. works: public bool sbyte_ulong_compare(sbyte x, ulong y) { // // returns x < y // if (x < 0) return true; if (y > 127) return true; return ((long)x < (long)y); } dthorpe , jon's answers close not quite correct. the correct reasoning follows. the specification states: for operation of form x op y, op comparison operator, overload resolution applied select specific operator implementation. ok, operator implementations overload resolution has work with? are: bool operator <(int x, int y); bool ope

PHP SESSIONS problem -

my php sessions when logged in not display links when type following url in browser example.com display links when type www.example.com how can fix problem if possible? this because sessions 1 or other. do, allow users on either www.example.com or example.com . set add code .htaccess # non-www redirect rewritecond %{http_host} !^example\.com$ rewriterule (.*) http://example.com/$1 [r=301,l] this redirect people example.com if try , onto www.example.com if have .co.uk domain may help # non-www redirect rewritecond %{http_host} !^example\.co\.uk$ rewriterule (.*) http://example.co.uk/$1 [r=301,l] there way via sessions on sub-domains. see this more info hope helps!

filepath - Is it possible to get the full path to an Android application asset file as a string? -

i'm trying use third party library in android app allows me load file using string represents path file. i've placed file in app's assets folder thinking use assetmanager path string. however, returns relative path file. i'm wondering if there's way full path file library can load file. just guess - resources.getresourcename() trick?

Android XML rounded clipped corners -

i've setup linearlayout following drawable background: <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <corners android:radius="10dp" /> <solid android:color="#ccffffff"/> </shape> the problem i'm having within linearlayout have linearlayout element sits @ bottom of it's parent. since doesn't have rounded corners corners extend past parents bottom left , right corners. the drawable background on child linearlayout looks this: <?xml version="1.0" encoding="utf-8"?> <bitmap xmlns:android="http://schemas.android.com/apk/res/android" android:src="@drawable/pedometer_stats_background" android:tilemode="repeat" /> the issue looks this: http://kttns.org/hn2zm on device non-clipping more apparent. what best method accomplish clipping?

silverlight - Approach to loading forms and busy indicator -

i "slowly" moving silverlight asp.net , have question how deal situation code needs executed after web service calls have completed. example, when user clicks on row in data grid dialog box shown allows editing of record. contains numerous combo boxes, check boxes etc. need first load data each of combo boxes, , when finished loading, need set bound entity. since new async thing, thinking have kind of counter keep track on how many calls have been dispatched, , finish reduce them one, until zero, @ point raise event load has finished, , proceed ever dependent on this. seems clunky way of doing it. sure many have faced issue, how do this. if helps, use prism mvvm approach , ria services dtos. what you've described pretty way go. there may more elegant things can locks , mutexes, counter work. has bonus can see how many operations still "in progress" @ 1 time. you dispatch events sequentially defeat whole purpose of asynchronous operations. if a

c# - WCF client Multi Event Problem -

my problem events wcf client. hand client object classes. , in classes created events. if created in different classes same event it's fires many times. want event fires in class call wcf. how can solve problem? remove each event after complete? sry english ;) thanks.... hi don't understand question quite well, i'll try answer way did. when reference wcf service, know proxy classes generated in client project. proxy classes share same data member's interface on server-side, not behavior. instance, properties accessible client, not events, methods , on. maybe can write trying accomplish , may help? update ok, think understand. that's solution remove each event shouldn't fire before execute addnumber method. solution keep track of calling classes. example public static arraylist eventobjects = new arraylist(); //declare global array list accessible classes eventobjects.add(this); //before calling addnumber method _client.addnumber += ne

sql - Search all columns in Informix table for a value -

i new informix, remember doing sql server. want query columns in given table specified value. everything googled references doing in sql server. ideas? there isn't built-in way it. you'd have do: select * table column1 = <your-value> union select * table column2 = <your-value> union ... automatic query generation is there programmatic way generate mass union-select statements? of target tables have numerous columns. what's weapon of choice? database name, table name, , value? weapon of choice sqlcmd, program available iiug software archive , not microsoft's johnny-come-lately creation of same name. dbname=stores table=customers value=raymond sqlcmd -d'\n' -d $dbname -e \ "select 'select * $table ', c.colname, '::varchar(64) = ''$value''', 'union' informix.syscolumns c join informix.systables t on t.tabid = c.tabid t.tabname = '

javascript - What is the best way to include script references in ASP.NET MVC views? -

as know, asp.net mvc stores view markup in views directory, hierarchically incompatible url routes used in asp.net mvc web application. on opposite end, in asp.net web forms (and in asp.net mvc, too), urls can , have nested "directories", or rather path separators, , combined fact web applications not hosted in root path of url rather in sub-directory i.e. "/stuff/here/myactualapp", necessary use script path relative root of application rather relative root of url. meanwhile, however, visual studio script intellisense dictates urls map relatively file being edited. further, i've run lot of problems using runat="server" virtualize root path support "~/", such head tag needing runat="server", , introduces kinds of other constraints. finally, 1 more thing: if minified flavor of script jquery referenced in addition intellisense-ready flavor, visual studio balk on it. have use escaped code keep vs balking. so i've been usin

Linq deferred execution -

i wrote simple program, here's looks like, details hidden: using system; using system.collections.generic; using system.linq; using system.text; using system.io; namespace routeaccounts { class program { static void main(string[] args) { //draw lines source file var lines = file.readalllines("accounts.txt").select(p => p.split('\t')); //convert lines accounts var accounts = lines.select(p => new account(p[0], p[1], p[2], p[3])); //submit accounts router var results = accounts.select(p => routeaccount(p)); //write results list target file writeresults("results.txt", results); } private static void writeresults(string filename, ienumerable<result> results) { ... disk write call ... } private static result routeaccount(account account) { ... ser

c# - Conversion failed when converting varchar value xxxx to int using an enum with NHibernate -

i have enum property want store , retrieve database string. nhibernate able store enum string throws following conversion exception upon retrieval: nhibernate.adoexception: not execute query --> system.data.sqlclient.sqlexception: conversion failed when converting varchar value 'pending' data type int. based on post mapping enumerations nhibernate jeremy miller created following class: public class workflowaction { public virtual actionstatus status { get; set; } } which uses enum: public enum requeststate { pending, approved, rejected } which uses class transform string public class actionstatusenumstring : nhibernate.type.enumstringtype { public actionstatusenumstring() : base(typeof(actionstatus), 50) { } } and setup property in mapping file this: <property type="infrastructure.enum.actionstatusenumstring, infrastructure" name="status" column ="status" /> as said works great

Freeing the memory of structure in C -

i have following sturcture creating linked list, how can free allocated memeory? typedef struct linked_list { struct linkedl_ist *number; pointer house; } list; typedef list *list; typedef void pointer i have following list list l1; l1 = some_function(pointer); these l1 constructed using variables. linked list data structure mentioned. how can free memory allocated l1 ? [edit] l1 holds memory of 8 byte. l1 doesn't need freed. it's on stack. return function you're in , automatically go away. way free l1 points same way free rest of elements of list: walk list (using ->number ) , free each element go. list node = l1; list next; while (node != null) { next = node->number; free(node); node = next; }

sql server 2005 - SQL Keyword search algorithm: This SQL does a sequential search, how to do an indexed search? -

we have 3 tables hold our products , keywords: product {int id, string name, ...} productkeyword {int productid, int keywordid} keyword {int id, string keyword} this sql code returns relevant products least relevant products having keywords users search criteria. searchwordtable table of search words. @keywordcount count of search words. returns products having 1 or more keywords, ordered quantity of keywords found each product. select productid, productname, count(*) * 1 / @keywordcount percentrelevant (select keyword, productid, productname product join productkeyword on ... join keyword on ... join searchwordtable on searchwordtable.keyword '%' + keyword.keyword + '%') k -- join aweful group productid, productname order percentrelevant desc -- relevant first the problem sequential search comparing every keyword have. it's not bad, searches can take minute million records. how re

vba - How to create object of .net library using 64 bit excel 2010 -

i'm getting error 429: activex component can't create object, when referencing visual studio 2008 c# library 64 bit excel 2010. note: create object method works fine on 32 bit excel 2010. i using below call create object: set commonlib = createobject("autolib.common") does has idea this. two possibilities spring mind: 1) have checked build configuration of c# library - set build x86 (i.e. 32 bit)? if so, try changing 'any configuration' or 'x64'. 2) library excel 64-bit expects be? have seen problems people have hard coded paths (e.g. c:\program files(x86)) or registry keys, don't behave hoped when switching 64-bit!

JQuery Not Working on Custom User Control in ASP.Net -

i have custom user control has on text box, , couple of compare validator controls. using jquery apply mask text box date format. mask using http://digitalbush.com/projects/masked-input-plugin/ , applying shown on website. when move code on .net page works fine. however, when move code ascx , apply control page, mask isn't being applied. have applied jquery ascx, , have tried moving aspx no avail. simple doing can't sake of me work out why not working. does know how solve this? it issue id of element in html. controls in user controls have parent namespace attached id's generated html. can post javascript?