Posts

Showing posts from March, 2013

javascript - jquery code to check page height not seem working correctly -

i have lil piece of jqery code here: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/javascript"> hasvbar=""; hashbar=""; $(document).ready(function() { // check if body height higher window height :) if ($(document).height() > $(window).height()) { // alert("vertical scrollbar! d:"); hasvbar="y"; } // check if body width higher window width :) if ($(document).width() > $(window).width()) { //alert("horizontal scrollbar! d:<"); hashbar="n"; } }); </script> now in html page first div 200px in height, below div contains 3 paras each in different div. show hide these 3 paras javascript onclick. problem if these 3 divs in hidden state (display:none , visibility:hidden) vertical scroll bar shows up. expecting vertical scrollbar pop if c...

HelloMapView in android -

i trying write mapview application .when extend class mapactvity generate error force close application. , in log chat got run-time error classnotfoundexception. please solve problem. it's hard point out error without knowing you've done far, @ least must add library manifest: <uses-library android:name="com.google.android.maps" /> you should go window > android sdk , avd manager in eclipse , make sure device running targeting google apis (google inc.) rather android x.x

entity framework - Does LINQ to Entities expression with inner object context instance translated into sequence of SQL client-server requests? -

i have ado.net ef expression like: db.table1.select( x => new { ..., count = db.table2.count(y => y.foreignkey.id == x.id) }) does understand correctly it's translated several sql client-server requests , may refactored better performance? thank in advance! yes - expression translated (in best way can) sql query. and t-sql query, ef (or l2sql) query expression can refactored performance. why not run sql profiler in background see getting executed, , try , optimize raw t-sql first - optimize expression. or if have linqpad , optimize t-sql query , linqpad write query you. also, im not sure why have specified delegate count() expression. you can this: var query= c in db.table1 select new { c.customerid, ordercount = c.table2s.count() };

how to use Exceptions in C++ program? -

hey , trying inherit exception class , make new class called nonexistingexception: wrote following code in h file: class nonexistingexception : public exception { public: virtual const char* what() const throw() {return "exception: not find item";} }; in code before sending function writing try{ func(); // func function inside class } catch(nonexistingexception& e) { cout<<e.what()<<endl; } catch (exception& e) { cout<<e.what()<<endl; } inside func throwing exception nothing catches it. in advance help. i this: // derive std::runtime_error rather std::exception // runtime_error's constructor can take string parameter // standard's compliant version of std::exception can not // (though compiler provide non standard constructor). // class nonexistingvehicleexception : public std::runtime_error { public: nonexistingvehicleexception() :std::runtime_error("exception: not...

sql server 2008: sp_RENAME table disappeared -

i renamed table sp_rename (sql server 2008) sp_rename 'dbname.scname.oldtblname' 'dbname.scname.newtblnam' the resulting message (it in black color - warning or successful message) "caution: changing part of object name break scripts , stored procedures." so after command table 45 million records disappeared , don't have backup. new table. :) guys have idea bringing table back? :) p.s. yeah, smile not ":(", because when seriousness of problem goes threshold, ":(" becomes ":)". what say? ssms not refresh object explorer automatically there use dbname select object_id('scname.newtblnam') sp_rename says you can change name of object or data type in current database only. names of system data types , system objects cannot changed. you specified dbname it's possible have object [dbname.scname.newtblnam] in dbo schema (or similar) and did backup first? best practice befor...

C++ single template specialisation with multiple template parameters -

hallo! i specialise 1 of 2 template types. e.g. template <typename a, typename b> class x should have special implementation single function x<float, sometype>::somefunc() . sample code: main.h: #include <iostream> template <typename f, typename i> class b { public: void somefunc() { std::cout << "normal" << std::endl; }; void somefuncnotspecial() { std::cout << "normal" << std::endl; }; }; template <typename i> void b<float, i>::somefunc(); main.cpp: #include <iostream> #include "main.h" using namespace std; template <typename i> void b<float, i>::somefunc() { cout << "special" << endl; } int main(int argc, char *argv[]) { b<int, int> b1; b1.somefunc(); b1.somefuncnotspecial(); b<float, int> b2; b2.somefunc(); b2.somefuncnotspecial(); } compilation fail...

javascript - get rid of centered play button from youtube video -

i'm using google youtube chromless api create custom play controls yotube vids on site. using chromless player doesn't seem rid of play icon sits on video @ start. cant hide other controls using this: swfobject.embedswf("http://www.youtube.com/apiplayer?&enablejsapi=1&playerapiid=player1", id, "545", "300", "8", null, null, params, atts); googled death can't find answer. any ideas?

php - serialize is causing a mess when it comes to gather information? -

since learning on how use serialize, facing hiccup after used below code jquery post jquery.post("d_in.php",jquery("#myform").serialize(), function(data){ alert("data loaded: " + data); and let's have 2 inputs names small$item_id, each input name follows items itself, whenever try echo $_post['small'.$item_id] both in 1 let's 1 small102-s , 3 small1055-a when print result follows : 13 even when comes more items how can split number? update #1: i tried using explode("&", $_post['small'.$item_id] getting null, seems data sent without & sent without split. update#2: here whats in d_in.php foreach ($cart->get_contents() $item) { $item_id = $item['id']; $item_name = $item['name']; $item_price = $item['price']; $item_qty = $item['qty']; $item_ids = explode("-",$item_id); for($i = ...

c++ - Segmentation fault while trying to print size of a vector inside a structure -

this piece of code gives me error struct state{ int time_taken; vector<int>time_live; string loc_name; vector<int>loc; }; for(int u=0;u<(a[start].loc.size());u++) { l=a[start].loc[1]; if(a[l].time_taken < min_time) { min_time=a[l].time_taken; finish = l; } } this gives segmentational fault . firstly, if a[start] out of range may problem, may or may not seg fault, depending on a is. secondly, in loop have a[start].loc[1] , out of range if a[start].loc empty. did mean loc[u] ?

Cursors in SQL Server 2005 database -

i working cursors , executed in t-sql , database use microsoft sql server 2005. my query after execute cursor, output shown in message area. when deallocate cursor using deallocate <cursor name> gets deallocated. again execute cursor. in message area this: "command(s) completed " and not getting output of cursor. resolve, copied cursor code , opened new query area , pasted there. works perfect first time. when rerun cursor, same message displayed in message area. how re-execute same cursor code in same window rather creating new sql window? without seeing code hard wrong, know cursors code of last resort , can done less code , faster performance using method. see link ideas of better ways handle task: http://wiki.lessthandot.com/index.php/cursors_and_how_to_avoid_them

parsing - How to combine Regexp and keywords in Scala parser combinators -

i've seen 2 approaches building parsers in scala. the first extends regexparsers , define won lexical patterns. issue see don't understand how deals keyword ambiguities. example, if keyword match same pattern idents, processes keywords idents. to counter that, i've seen posts this one show how use standardtokenparsers specify keywords. then, don't understand how specify regexp patterns! yes, standardtokenparsers comes "ident" doesn't come other ones need (complex floating point number representations, specific string literal patterns , rules escaping, etc). how both ability specify keywords , ability specify token patterns regular expressions? i've written regexparsers -derived parsers, this: val name: parser[string] = "[a-z_a-z][a-z_a-z0-9]*".r val kwif: parser[string] = "if\\b".r val kwfor: parser[string] = "for\\b".r val kwwhile: parser[string] = "while\\b".r val reserved: pars...

sql - MySQL: Last 10 entries per user? -

i have table storing transactional data users. find users rating take average score of last 10 entries user. there way sql? i need able work out single user given id. , list of users ordered score. currently i'm working out outside mysql , storing in col each user can order_by that. # returns average transactions. select user_id, avg(score) transactions user_id = 1 # returns scores last 10 transactions. select user_id, score transactions user_id = 1 order_by date desc limit 10 use: select x.user_id, avg(x.score) (select t.user_id, t.score transactions t t.user_id = ? order t.date limit 10) x group x.user_id

javascript - How do you limit options selected in a html select box? -

i'm using select tag in form i'm making allows multiple selections, want make maximum amount of selections upto 10. possible using javascript or jquery? thanks in advance! here full code use...gotta love google ajax api playground :-) edit 1: note: lets choose 5 because didn't feel copy/pasting 10 options :-) <!-- copyright (c) 2009 google inc. free copy , use sample. license can found here: http://code.google.com/apis/ajaxsearch/faq/#license --> <!doctype html public "-//w3c//dtd xhtml 1.0 strict//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title>sample select maximum jquery</title> <script src="http://www.google.com/jsapi?key=abqiaaaa1xbmidxx_btcy2_fkph06rragtyh6uml8madna0ykuwnna8vnxqeertaucfkyrr6owbo...

.net - Entity Framework 4, defining relationship -

when defining relationship in entity framework 4 in 1-to-many relationship using poco classes why relationship have defined @ child level. example have order has many products. relationship in mapping file product like:- relationship(e => e.order) .fromproperty(m => m.product) .hasconstraint((e, m) => e.id == m.id); in n-hibernate defined in mapping file @ parent level (order in case). having relationship defined @ parent offers more flexibility , reuse. is there way @ parent level instead in ef4. in ef4 ctp2 have inverse properties. mentioned in ado.net team blog post . public parentconfiguration() { property(p => p.id).isidentity(); property(p => p.firstname).isrequired(); property(p => p.lastname).isrequired(); //register inverse relationship(p => p.children).fromproperty(c => c.parents); } what means parent.children = children work...

sql server - SQL - Joining tables where one of the columns is a list -

i'm tryin join 2 tables. problem i'm having 1 of columns i'm trying join on list. so possible join 2 tables using "in" rather "=". along lines of select id tablea inner join tableb on tableb.misc in tablea.misc tableb.misctitle = 'help me please' tableb.misc = 1 tablea.misc = 1,2,3 thanks in advance no want not possible without major workaround. not store items want join in list! in fact comma delimited list should never stored in database. acceptable if note type information never need used in query clasue or join. if stuck horrible design, have parse out list temp table or table variable , join through that.

how to totally delete eclipse and start over (os x)? -

i've having problems eclipse set-up, , i'm thinking of deleting , starting again scratch. if delete workspace directory, , eclipse.app applications folder, everything, or there hidden files somewhere have worry about? i'm on os x. delete eclipse folder. enough. won't need delete workspace can create new one.

mobile - Unzip files and/or streams in rhomobile -

how decompress compressed file in rhomobile application? saw zlib extension unavailable in rhodes, because needs ruby port. ruby uses "zlib.c" or "zlib.h" source files , not portable zlib. when running rhodes application, in line source: require 'zlib' it raises error: no such file load -- zlib anyone has idea? thanks in advance? see documentation on adding libaries rhodes app: http://wiki.rhomobile.com/index.php/rhodesextensions#adding_libraries_to_your_rhodes_application i don't know if zlib work or not (actually curious find out). if have more questions suggest rhomobile google group.

Creating a new variable from a conditional operation on 3 old variables in R -

i have dataset in r, contains results of rapid diagnostic test. test has visible line if working (control line) , visible line each of 2 parasite species detects, if present in patient sample. the dataset contains logical column each test line, follows: (database called rdtbase) control pf pv 1. true true false 2. true false true 3. false false false 4. true true true 5. true false false i add new column contains single result each rapid test. results designated according different logical conditions met 3 lines. example above new column this: control pf pv result 1. true true false pf 2. true false true pv 3. false false false invalid 4. true true true mixed 5. true false false negative i able create new column, takes lot of coding , think there has simpler (and shorter) way this. here current (long) method: r.pf <- rdtbase[which(control == "true" & pf == "true" & pv == "fal...

My app frequently throws android.view.WindowLeaked exception -- -

my app throws exception below: e/windowmanager( 6282): android.view.windowleaked: activity com.myactivity has leaked window com.android.internal.policy.impl.phonewindow$decorview@4479b710 added here the app shows progress dialog when main activity starts , starts task. when task done, dismiss progress dialog. my code below. can me? public class myactivity extends activity { private static int id_dialog_progress = 2001; public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.my_activity); showdialog(id_dialog_progress); new mytask().execute(null, null, null); } @override protected dialog oncreatedialog(int id) { if (id == id_dialog_progress) { progressdialog loadingdialog = new progressdialog(this); loadingdialog.settitle(""); loadingdialog.setmessage(""); loadingdialog.setindeterminate(true); loadingdialog.setcancelable(f...

.net - WPF Is it legal to invoke another event from within an event-invocation-method -

the following code part of answer have received solve probem have posted in so. works fine, i'm curious if allowed manually invoke event within invocation-method eventargs of original event: protected override void onmouseleftbuttonup( mousebuttoneventargs e ) { base.onmouseleftbuttondown( e ); } i have seen pattern never used because feared lead sideeffects or problems in future versions of wpf. has insight tell me if such redirected event-invocations save? i careful doing this. if event data contains stuff relevant original event other event handler can confused data. when comes events external devices mouse. maybe example posted ok, don't know. can see problem doing other way around, raising mouse down when mouse - mouse down handler (potentially, have no idea if this) query input device actual status of mouse , wouldn't match. or perhaps operation on mouse works when pressed etc. so in summary: may work, not rely on unless 100% sure ...

htmlunit cookie/refer question -

testing out java htmlunit lib. trying figure out if there's way set/delete cookie file (cookiejar) used webclient object.. i've searched multiple docs, htmlunit api no luck, i'm assuming i'm missing something. also, there way see headers (request/respnse/referer) being xfered between client/server during testing... thanks tom you can use webclient.getcookiemanager() , , can subclass httpwebconnection as: webclient.setwebconnection(new httpwebconnection(webclient) { public webresponse getresponse(webrequestsettings settings) throws ioexception { system.out.println(settings.geturl()); return super.getresponse(settings); } });

java - How to use reverse engineering in my eclipse -

i using mysql workbench , eclipse 8.6. , making hibernate-spring program. possible use reverse engineering feature in eclipse mysql workbench in dao , hbm files can generate derby. how can mysql workbench. url of using reverse engineering in eclipse. http://www.myeclipseide.com/documentation/quickstarts/hibernateandspring/ i'm not sure myeclipe, in eclipse 3.6 can install "hibernate tools" eclipse. steps - create schema , tables using mysql workbench - in eclipse, create new database connection (database perspective --> data source explorer view --> database connections, right-click, new). specify mysql driver, username password, database etc - make sure eclipse connected database, , can mysql ping - in eclipse, create new "jpa" project. - right-click on jpa project, , go "jpa tools" --> generate entities tables. - in wizard, need change mechanism auto-assigning id's entities being written database

Python: Why does my function not display what's being returned in the interpreter? -

in python interactive interpreter: i importing module contains class. these methods of class (some of them): def do_api_call(self, params): return self.__apicall(params) def __apicall(self, params): return urllib2.urlopen(self.endpoint, params).read() when import class , use method do_api_call(), doesn't output when finishes running. def do_api_call(self, params): print(self.__apicall(params)) def __apicall(self, params): return urllib2.urlopen(self.endpoint, params).read() i create instance of class , run method: myapi = myapiclass() myapi.do_api_call(params={'param': 'value'}) when second version (note print function) however, outputs html of page being called. why doesn't first version output anything? it's working (ie, it's getting page , not raising errors). your first version returns value see output. second version prints value. if you, consider storing return value ...

web applications - Prism: Bundle not working -

i trying new , decided try out webapps on prism. started out dev center on mozilla on creating first bundle. worked first time, once added other files construct entire bundle, prism not recognize parameters more. when tried removing of other files except webapp.ini, doesn't work anymore... here webapp.ini [parameters] id=prismtest@educdesign.lu name=prismtest uri=http://192.168.1.120/ status=no location=no sidebar=no navigation=no i downloaded prism , reinstalled on imac. still, standard form when no .webapp file selected. well, won't believe it... error somewhere else. when started compressing entire structure, selected folder , hit compress. put folder @ archive's root, structure compromised. did not notice until found earliest prism try , noted difference while uncompressing compare. because had folder, continued compressing folder, though had 1 item (webapp.ini). error me thinking not take folder archive. /me gets nominated internet fail awards ...

sql server 2005 - Pivot sql query -

i've sql server 2005 table competitor (id, title, cdate, price) want format query view in gridview this: alt text http://i46.tinypic.com/2cmxg76.jpg please me writing sql query. sql 2005 supports pivot - books online doc http://msdn.microsoft.com/en-us/library/ms177410(sql.90).aspx the main shortcoming i've found pivot stuff must specify column names, although can use query beforehand , inject values varchar variable , execute that.

mysql: how can i remove the street number from a streetaddress column? -

i have column named streetaddress contains <street number> <street name> for example: 15 rue gontier-patin 4968 hillcrest circle how can remove numbers beginning of row purely in sql? how - trim off , including first space in strings start number update mytable set addresscol=substring(addresscol, locate(' ', addresscol)+1) addresscol regexp '^[0-9]';

c# - Trace all handled exception -

i trying understand why deployed application not working properly. have pinned down problem particular update routine. sadly, routine embedded nothing try-catch. bool requireupdate = false; try { requireupdate = !client.isuptodate(); } catch{ } i need way exception without having recompile , deploy. is there way modify app.config file can trace handled exceptions log file, regardless of how have been handled? unfortunately there nothing can done handled exceptions, are handled (even if badly, in case). the best way them rewrite/recompile/deploy.

linux - How do I pass an environment variable to a Netbeans Makefile on Ubuntu? -

i'm using netbeans on linux (ubuntu 9.04) build c project. how pass in environment variable that's it's visible makefile? if normal export myvar="xyz" , run make command line works fine of course. but netbeans doesn't seems use .bashrc environment, if click "build" in netbeans, make fails. interestingly, problem doesn't seem occur on macosx - i've added variable ~/.macosx/environment.plist , , value is visible netbeans. i found this post suggested modifying ~/netbeans-6.8/etc/netbeans.conf . i've tried this, adding -j-dmyvar=xyz end of netbeans_default_options , ie: netbeans_default_options="-j-client -j-xverify:none -j-xss2m -j-xms32m -j-xx:permsize=32m -j-xx:maxpermsize=200m -j-dapple.laf.usescreenmenubar=true -j-dsun.java2d.noddraw=true -j-dmyvar=xyz" but didn't seem work. edit: this answer possibly not valid unity-based flavours of ubuntu. the issue nothing netbeans - it's rela...

actionscript 3 - How do I return different type from overridden method? -

i'm extending as3 class rectangle class called bin. want override rectangle clone() method method returns bin object, not rectangle object. if try override clone method specify bin return type, #1023: incompatible override error. here's bin class: package { import flash.geom.rectangle; public class bin extends rectangle { public function bin(x:number = 0, y:number = 0, width:number = 0, height:number = 0) { super(x, y, width, height); } override public function clone():rectangle { return new bin(x, y, width, height); } } } this class works, when use clone() method create new bin instance, type errors when try use bin methods on new instance. how override clone() , send actual bin instance? technically, can't change signature when override method. in case, though, not huge problem. have cast resulting object type bin after calling clone method.

syntax - JAVA: if without curly brackets, and relation to continue -

i have following java code fragment while (condition1){ switch (someinteger){ case 1: if(condition2) continue; // other stuff here break; // other cases here } } all fine. when generate class file , decompile using free tool (jd-gui), following code. while (condition1){ switch (someinteger){ case 1: if(!condition2); // other stuff here break; // other cases here } } so changes if(condition2) continue; if(!condition2); not find info on other if statement (without braces). can explain logic here? in advance. edit: did more tests , decompiler not work correctly. here code before: public void strip(inputstreamreader f1, outputstreamwriter f2) throws ioexception{ int commenton=0, quoteon=0; int b1; while ((b1 = f1.read()) != -1){ switch ((char) b1){ case '\\': if (commenton==0){ ...

ServicesSearch an error comes in java as symbol not defined in netbeans -

package com.intel.bluetooth.javadoc.servicessearch; import java.io.ioexception; import java.io.outputstream; import javax.microedition.io.connector; import javax.obex.*; //import java.util.vector; public class obexputclient { public static void main(string[] args) throws ioexception, interruptedexception { string serverurl = null; // = "btgoep://0019639c4007:6"; if ((args != null) && (args.length > 0)) { serverurl = args[0]; } if (serverurl == null) { string[] searchargs = null; // connect obexputserver examples // searchargs = new string[] { "11111111111111111111111111111123" }; **servicessearch**.main(searchargs); if (servicessearch.servicefound.size() == 0) { system.out.println("obex service not found"); return; } // select first service found serverurl = (string)servicessearch.servicefound.elementat(0); } system....

javascript - How to check 2 date fields and compare to see which date is ahead, behind or the same -

i'm working 2 dates posted me in textbox strings in format 03/02/2010. 1 current completion date , second final completion date. need compare these 2 dates check if final completion date ends being ahead, behind or same current completion date. is there way can using javascript or jquery? thanks help. var passeddate1 = new date('03/02/2010'); var passeddate2 = new date('03/01/2010'); if (passeddate1 > passeddate2) { alert ('date1 greated date 2'); } else if (passeddate1 < passeddate2) { alert ('date1 less date 2'); } else { alert ('they equal'); }

Is it possible to set the Windows language bar to english or back to the default from a c# application -

i have c# application needs set windows language bar english or @ least default setting. know can set inputlanguage of own application need set input language windows in general. can done manually using language bar, need way programmatically. there way this? i haven't done since windows xp in it's childhood, may want check if language support still based on same principles. win32, need imported c#. first, read on msdn pages keyboard input: http://msdn.microsoft.com/en-us/library/ms645530%28vs.85%29.aspx getkeyboardlayoutlist tells layout installed loadkeyboardlayout loads new input locale identifer. activatekeyboardlayout sets current language

sql - Details of impact for indexes, primary keys, unique keys -

i think know enought theory, have little experience optimizing db in real world. know points of view, thoughts or experiences. let's imagine scenario like: table key: c1, c2, c3, c4 index: c7, c3, c2 table b key: c1, c2, c3, c4 index: c1, c5 all non-clustered. tables have 40+ fields. feeded daily night , have updates during day. table a, if more queries benefit key index, index impact negatively? because insert/delete has update 2 indexes instead of 1. table b, has field @ index, not present in key. could query using c1, c5 benefit key?: key: c1, c2, c3, c4, c5 so index droped. what impact order of fields has? key: c1, c2, c3 key: c3, c1, c2 a typical scenario me process_date, client_number, operation. , feeds bunch of data each day (process_date). if more queries benefit key index, index impact negatively? because insert/delete has update 2 indexes instead of 1. a non-clustered index has negative impact on insert/update/delete perform...

java - File Processing -

i'm writing game in user can create own level , remove them also. trouble want files saved names level1, level2, level3 etc without asking user name of level. while saving game level5 name might possible previous level name exists. there way avoid such problems. mean before saving name should save should known previously... thanx... you can make use of methods provided java.io.file api, such file#exists() . returns boolean . if true , can either append file, or create 1 different filename (maybe counter suffix?). can append existing file using constructor of fileoutputstream taking 2nd boolean argument set true . can stick using constructor without checking if file exists, create new 1 if file doesn't exist , append if file exists.

.net - Where the MSI file is copied after the installation? -

i have replace because of bug blocks software uninstallation, windows can't find msi file if use file search utility, think msi stored somewhere add or remove programs utility can use it. does not go %windir%\installer\ though think files may renamed. not sure name mapping from... this directory gets big move external drive. cause uninstalls or updates fail missing msi error, can fixed putting directory back

android - Clear listview content? -

i have little problem listview. how clear listview content, knowing has custom adapter? edit : custom adapter class extends baseadapter, looks : import android.app.activity; import android.content.context; import android.view.layoutinflater; import android.view.view; import android.view.viewgroup; import android.widget.baseadapter; import android.widget.textview; public class myadapter extends baseadapter { private activity activity; private string[] data; private static layoutinflater inflater=null; public myadapter(activity _a, string[] _str) { activity = _a; data = _str; inflater = (layoutinflater)activity.getsystemservice(context.layout_inflater_service); } public static class viewholder{ public textview text; } @override public int getcount() { return data.length; } @override public object getitem(int position) { return position; } @override public long get...

spring mvc - DataSource not injected to @Resource annotated field with alwaysUseJndiLookup setting -

i've read @resource annotation article ( http://www.infoq.com/articles/spring-2.5-part-1 ) , wish use on tomcat 6.0.26 , spring 3.0.3 but not work -- field ds in users class not initialized , i've got nullpointerexception when try made query. file src/org/example/db/users.java package org.example.db; import javax.sql.datasource; import javax.annotation.resource; @repository public class users { @resource private datasource ds; ... } file web-inf/spring-servlet.xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:context="http://www.springframework.org/schema/context" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spri...

ruby on rails - Change starting id number -

i have 'account' model in rails corresponding 'accounts' table in database. if wipe database , start over, 'account_id' field start @ 1 , count there. change starting number, that, when first account created in fresh database, 'account_id' is, say, 1000. there way in rails, or need specialized database-dependent sql code? for sake of illustration, here simplified version of 'accounts' table: create_table "accounts", :force => true |t| t.string "email", :null => false t.string "crypted_password", :null => false t.string "name", :null => false t.boolean "email_verified", :default => false end you'll need specialized database-dependent sql functionality. if you're using mysql, can add following code migration after create_table code: execute("alter table tbl auto_increment = 1000")

How to auto save and auto load all properties in winforms C#? -

how auto save properties winforms when closed , auto load properties winforms when load ? c# using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.text; using system.windows.forms; using system.io; namespace scontrol { public partial class form1 : form { public form1() { initializecomponent(); } private void button1_click(object sender, eventargs e) { (int = 0; < controls.count; i++) { system.xml.serialization.xmlserializer x = new system.xml.serialization.xmlserializer(typeof(controls[i])); stream stream = file.open("test.xml", filemode.create); x.serialize(stream, controls[i]); } } } } your question little unclear, but if require saving/loading of form layout have at windows forms user settings in c# if require saving/...

java - Is there a way for NetBeans to automatically create brackets in a separate line? -

when create new class instance, this: /* * change template, choose tools | templates * , open template in editor. */ package helloworld; /** * * @author sergio */ public class wordmanipulations{ } i hate when brackets placed way. there way make create things this: /* * change template, choose tools | templates * , open template in editor. */ package helloworld; /** * * @author sergio */ public class wordmanipulations { } simply follow these steps: navigate tools -> options -> editor navigate editor -> formatting select following language: java category: braces in "class declaration, method declaration, etc." braces placement: new line

java - @Override Snafu -

i've create project/class file in eclipse helios using jdk1.6. had let eclipse generate code implementation class of interface. public interface foo { void bar(); } public class fooimpl implements foo { @override public void bar() { } } so far good. reason, i've imported project in eclipse has jdk 1.5 , see error message the method bar() of type fooimpl must override superclass method quick fix remove '@override' annotation . after googling, got know there override_snauf - 6.0 java compiler updated allow @override on interface method implementations. @override checking override syntax in compile stage, applied interface same reason guess.

c# - generating string from exited characters -

i have character array shown below : char[] pwdchararray = "abcdefghijklmnopqrstuvwxyzabcdefg" + "hijklmnopqrstuvwxyz0123456789`~!@#$%^&*()-_=+[]{}\\|;:'\",<" + ".>/?".tochararray(); and char array, want generate string of minimum length 7 , characters in string should above char array. how operation? generate 7 random numbers between 0 , yourarray.length -1. pick corresponding char in array , put in final string. here code stringbuilder: stringbuilder sb = new stringbuilder(); random random = new randdom(); for(int i=0; i<7; i++) { sb.append(pwdchararray[random.nextint(0, pwdchararray.length -1)]); } return sb.tostring();

wpf - Treeview MVVM ObservableCollection Updates -

i have treeview binds lots of nested observablecollections. each level of treeview shows aggregated sum of hours in child items. example: department 1, 10hrs ├ team 10, 5hrs │ ├ mark, 3hrs │ └ anthony, 2hrs └ team 11, 5hrs ├ jason, 2hrs ├ gary, 2hrs └ hadley, 1hrs department 2, 4hrs ├ team 20, 3hrs │ ├ tabitha, 0.5hrs │ ├ linsey, 0.5hrs │ └ guy, 2hrs └ team 11, 1hr └ "hadley, 1hr" when modify individual.hours in viewmodel class want update hours values in both team , departments too. i'm using notificationproperties hours properties, , observablecollections teams in departments , individuals in teams . thanks, mark each department's hours depends on aggregate of team's hours. each team's hours depends on aggregate of individual's hours. thus, each team should listen changes of individual's hours property. when detected, should raise onpropertychanged own hours pro...

delphi - FtpOpenFile returns nil instead of file handle when uploading -

i'm transferring file using ftp in delphi. i able connect ftp account ok when try , upload file ftpopenfile function returns nil instead of handle file uploaded. hintfile := ftpopenfile(hintconnect,pchar(tgtfn),generic_write,ftp_transfer_type_binary,0); if log ftp site using ftp client application , same credentials can upload file without problem. any suggestions appreciated. try last error, documentation says all: "returns handle if successful, or null otherwise. retrieve specific error message, call getlasterror." http://msdn.microsoft.com/en-us/library/aa384166(vs.85).aspx

entity framework 4 - How preserve Entityframework SSDL changes? -

how can preserve ssdl changes? each time open entity framework model designer overrides , remove casacade delete attribute added ssdl manually many many relations. using entity framework 4.0 , model first approach. you can't. that's "feature" of designer. but designer recognize , support cascades if they're in database. they?

Where's the syntax error in this (f)lex snippet? -

i'm having great time doing lexer using flex. problem is, code editor doesn't color syntax of file, , seems rule has error in it. since i'm not sure how use single quotes , double quotes inside intervals, thought i'd share snippet you: [^\\\'\n]+ { wchar_t* string; utf8_decode(yytext, &string); yyextra->append(string); free(string); } flex tells me there's 'unrecognized rule' on utf8_decode line. if remove whole rule, things fine again. can tell i'm doing wrong here? the action must begin on same line pattern. use [^\\\'\n]+ { wchar_t* string; utf8_decode(yytext, &string); yyextra->append(string); free(string); }

Is there an alternative to JXTA for Java P2P frameworks? -

my team having trouble project using jxta. is there framework p2p networks java? release 2.7 has been improved in terms of testing. and, practical jxta ii book has been made available reading on scribd. have try again.

sql - selecting latest rows per distinct foreign key value -

excuse title, couldn't come short , point... i've got table 'updates' 3 columns, text, typeid, created - text text field, typeid foreign key 'type' table , created timestamp. user entering update , select 'type' corresponds too. there's corresponding 'type' table columns 'id' , 'name'. i'm trying end result set many rows in 'type' table , latest value updates.text particular row in types. if i've got 3 types, 3 rows returned, 1 row each type , recent updates.text value type in question. any ideas? thanks, john. select u.text, u.typeid, u.created, t.name ( select typeid, max(created) maxcreated updates group typeid ) mu inner join updates u on mu.typeid = u.typeid , mu.maxcreated = u.created left outer join type t on u.typeid = t.typeid

Best practices for moving data using triggers in SQL Server 2000 -

i have troubles trying move data sql server 2000 (sp4) oracle10g, link ready , working, issue how move detailed data, case following: table master table b detail both relationed work trigger (for insert) so query needs query both create robust query, when trigger fired on first insert of master passed normal, in next step user insert 1 or more details in table b, trigger fired time record increment, problem need send example : 1 master - 1 detail = 2 rows (works normal) 1 master - 2 details = 4 rows (trouble) in second case work around detail in each select each insert duplicates data, said if detail have 2 details normal 2 selects 1 row each one, in second select rows doubled (query first detail inserted) how can move 1 row per insert using triggers on table b? most of time boils down coding error, , blogged here: http://www.brentozar.com/archive/2009/01/triggers-need-to-handle-multiple-records/ however, i'm concerned what's going happen rollback...

How to hide columns in an ASP.NET GridView with auto-generated columns? -

gridview1.columns.count 0 sqldatasource1.databind(); but grid ok i can do for (int = 0; < gridview1.headerrow.cells.count;i++) i rename request headers here but gridview1.columns[i].visible = false; i can't use because of gridview1.columns.count 0. so how can hide them ? try putting e.row.cells[0].visible = false; inside rowcreated event of grid. protected void bla_rowcreated(object sender, gridviewroweventargs e) { e.row.cells[0].visible = false; // hides first column } this way auto-hides whole column. you don't have access generated columns through grid.columns[i] in gridview's databound event.

Syntax error on closing brace after opening a php tag -

i'm getting trouble function looks pretty this: <?php function my_function() { if(!empty($variable)) { //do stuff } else { ?>show message<?php } } ?> the problem i'm getting parse error: parse error: syntax error, unexpected ‘}’ in /www/bla/bla/bla.php on line 8 i know fact i'm not missing or have '}' brace because code works fine on local server , i've run validator make sure syntax correct, however, when port code online server, error. i believe has php installation not supporting closing , reopening of php tags between condition i'm not sure how go fixing it. i know echo 'message'; instead, not place script uses kind of syntax display messages, fixing here mean i'd error on line, , another. thanks. as stands piece of code runs fine on php 5.2.14. when pasted in code sure pasted line as-is?: ?>show message<?php the thing can think of code on server using short...

computer vision - An iPhone library for shape recognition via the camera -

i hope falls within "programming question" category. im lightheaded googling (and reading every post in here on subject) on subject "computer vision", im getting more confused enlightened. i have 6 abstract shapes printed on piece of paper , have camera on iphone identify these shapes (from different angles, lightning etc.). i have used opencv while back(java) , looked @ other libraries out there. caveat seems either rely on jail broken iphone or experimental , hard use end using days learning libraries figure out didn't work. i have thought of taking +1000 images of shapes , training haar filter. again if there out there bit easier work appreciate advise, suggestion of people bit of experience. thank suggestion or pieces of advise might have:) have @ at opencv's surf feature extraction (they have demo uses detect objects). surf features salient image features invariant rotation , scale. many algorithms detect objects extracting such fea...

.net - T4MVC problems with MVC 2 under VS2010: cannot convert from 'method group' to 'System.Web.Mvc.ActionResult' -

just added t4mvc templates project, built , tried use cool new features introduces. i tried update redirecttoaction("notfound", "error"); to redirecttoaction(mvc.error.notfound); i following error @ build: argument 1: cannot convert 'method group' 'system.web.mvc.actionresult' also, in views, when try this: <%= url.action(mvc.home.index) %> i messages say: argument type 'method group' not assignable parameter type 'system.web.mvc.actionresult' not sure begin troubleshooting this. you need call action method. e.g. mvc.error.notfound(). see doc more examples.

c++ - setRawHeader doesn't follow elements in the web view -

i want test rendering of configured vhost before hostname set. exemple : view webpage "othernameofmysite" located @ mysite.com if dns entry "othernameofmysite" doesn't exist (but apache vhost set). my code : webvhost = new qwebview(); qnetworkrequest * request = new qnetworkrequest(qurl("http://mysite.com")); request->setrawheader("host","othernameofmysite"); webvhost->load(*request); the header set main page, if there element in html page image, download of image not use header configured. in case can't view render of possible vhost. how can tell webview use header elements of web page ? thanks. you should reimplement qnetworkaccessmanager class, particularly, createrequest function can manually set header requests. create instance of reimplemented class , set in webvhost->page()->setnetworkaccessmanager(your_reimplemented_class) . so, you'll want.

A few questions regarding Pythons 'import' feature -

i downloaded beautiful soup , i've decided i'll make small library (is call them in python?) return results of movie given , imdb movie search. my question is, how import thing work? for example, downloaded beautifulsoup , is, .py file. file have in same folder python application (my project use library)? for ubuntu, can search packages command apt-cache search beautifulsoup this should yield python-beautifulsoup - error-tolerant html parser python so easiest way install beautifulsoup ubuntu run sudo apt-get install python-beautifulsoup once this, can put import beautifulsoup in of scripts , python installation find module.

Are there any issues with using static keyword in a plain php function? -

for example: <?php function get_current_user_id(){ static $id; if(!$id){ $id = 5; echo "id set."; } return $id; } $id = get_current_user_id(); $id2 = get_current_user_id(); $id3 = get_current_user_id(); echo "ids: ".$id." ".$id2." ".$id3; ?> //output: id set.ids: 5 5 5 http://codepad.org/jg2fr5ky thus presumably repeated calls user id simple return of id still in memory. don't know if idiomatic use of php functions, though. it's kinda singleton, except not oo, , i've never heard of or seen other people using it, i'm wondering if there downsides using statics in manner, or if there gotchas should aware of more complex use cases of statics in functions. so, problems might encounter type of usage of statics? i don't think there wrong approach -- actually, use myself quite often, " very short-lifetime caching mecanism ...

asp.net - Is connection string name LocalSqlServer mandatory? -

how configure connection string asp.net membership provider? have write hand or tool available in visual studio can specify connection string algorithm used store password? i read 1 article , specifies connection string :- <configuration> <connectionstrings> <remove name=”localsqlserver”/> <add name="localsqlserver" connectionstring="data source=localhost;initial catalog=appservicesdb;integrated security=true" providername="system.data.sqlclient"/> </connectionstrings> </configuration> this localsqlserver name doesn't sound intuitive. how change this? thanks in advance :) it's referenced either <membership> configuration section <membership defaultprovider="sqlmembershipprovider" > <providers> <clear/> <add name="mysqlmembershipprovider" connectionstringname="localsqlserver" ...

java - Serial Number of a X.509 Certificate -

i programming certification authority in java uni class, don't know what's best option serial number of certificate. simple static counter 0 verybignumber some huge bigint random number is there reason choosing 1 on other... or none of them?? thanks, i recommend use random number, keep list of issued serial numbers in database. allow 2 things. you never reissue same serial number. you can tell certificate's serial number if remotely valid. of course #1 requires check against known list on generation , generate new random number if collision occurs, , #2 isn't of in terms of security or validation interesting prospect never-the-less.

c++ - Why does calling std::stringstream's good() through a pointer lead to crashes? -

i having problems stringstream object. class has input stream member. checking if obj->istream , after thatn if obj->istream->good(). the stream exists call good() crashes. in visual studio 2005. clue? how reset istream? if (soap->is) { if (soap->is->good()) return soap->is->read(s, (std::streamsize)n).gcount(); return 0; } that code gsoap framework std::istringstream in_stream; in_stream.str("a buffer"); soap->is = &in_stream; the in_stream goes out of scope, belongs local stack, ->is->good() called outside function when in_stream no longer exists. this indicates is member not point stringstream . might initialized garbage value when enclosing object instantiated. if testing pointer being zero, make sure it's set 0 in constructor (and reset 0 if ever detach stream).

.Net ORM bulk deletion via predicate -

is there orm allow me following? db.delete<myentity>(x => ***some predicate***); we use nhibernate , don't believe possible it. subsonic able this. http://subsonicproject.com/docs/linq_deletes

debugging - Java is reporting errors running the A+ Learning System. Any ideas how to fix them? -

i work local school district part time. run piece of software called a+ learning system. uses java runtime environment does. on 1 of our computers, isn't running; opening command prompt , typing out: java -jar als.jar gives following error messages. c:\als30\alsclient>java -jar als.jar > c:\alsdebuginfo.txt exception in thread "main" java.lang.noclassdeffounderror: javax/media/controllerlistener @ java.lang.classloader.defineclass1(native method) @ java.lang.classloader.defineclasscond(unknown source) @ java.lang.classloader.defineclass(unknown source) @ java.security.secureclassloader.defineclass(unknown source) @ java.net.urlclassloader.defineclass(unknown source) @ java.net.urlclassloader.access$000(unknown source) @ java.net.urlclassloader$1.run(unknown source) @ java.security.accesscontroller.doprivileged(native method) @ java.net.urlclassloader.findclass(unknown source) @ java.lang.classload...

Weird string expansion with powershell -

i'm using string expansion feature build filenames, , don't quite understand what's going on. consider: $basename = "base" [int]$count = 1 $ext = ".ext" $filename = "$basename$count$ext" #filename evaluates "base1.ext" -- expected #now weird part -- watch underscore: $filename = "$basename_$count$ext" #filename evaluates "1.ext" -- basename got dropped, gives? just adding underscore seems throw off powershell's groove! it's weird syntax rule, understand rule. can me out? actually seeing here trouble in figuring out when 1 variable stops , next 1 starts. it's trying $basename_. the fix enclose variables in curly braces: $basename = "base" [int]$count = 1 $ext = ".ext" $filename = "$basename$count$ext" #filename evaluates "base1.ext" -- expected #now wierd part -- watch underscore: $filename = "$basename_$count$ext" ...

java - When should we use a PreparedStatement instead of a Statement? -

i know advantages of using preparedstatement , are query rewritten , compiled database server protection against sql injection but want know when use instead of statement ? query rewritten , compiled database server if don't use prepared statement, database server have parse, , compute execution plan statement each time run it. if find you'll run same statement multiple times (with different parameters) worth preparing statement once , reusing prepared statement. if querying database adhoc there little benefit this. protected against sql injection this advantage want hence reason use preparedstatement everytime. consequence of having parameterize query make running lot safer. time can think of not useful if allowing adhoc database queries; might use statement object if prototyping application , quicker you, or if query contains no parameters.

unit testing - Compile error when trying to mock a generic method with Moq -

i have method i'd mock: public interface iservicebus { void subscribe<t>(isubscribeto<t> subscriber) t : class; } for sake of example, t can called sometype . now, i'd mock this, so: var mockservicebus = new mock<iservicebus>(); mockservicebus.setup(x => x.subscribe(it.isany<isubscribeto<sometype>>)); however, when try this, compile error: error 65 type arguments method 'servicebus.iservicebus.subscribe(messaging.isubscribeto)' cannot inferred usage. try specifying type arguments explicitly. i'm not sure how work around error. ideas? or behavior not possible mock moq? try (adding parentheses since it.isany<tvalue> method): mockservicebus.setup(x => x.subscribe(it.isany<isubscribeto<sometype>>()));

c - _beginthread vs CreateThread -

what difference between createthread , beginthread apis in windows? 1 preferrable thread creation? _beginthread() , _beginthreadex() required earlier versions of microsoft crt initialize thread-local state. strtok() function example. that's been fixed, state gets dynamically initialized, @ least since vs2005. using createthread() no longer causes problems.

objective c - Guide about subclassing -

i'd create subclass of uialertview implement own defaut behaviors when users click on dialog's buttons. it awesome if guide me through or point me guide subclassing? thanks! there not subclassing in objective c. the standard syntax looks this. @interface nsobjectsubclassedobject : nsobject { } two things mention: multi-inheritance not supported , there's method "subclass" objects called categories .

email - PHP IMAP library - Retrieving a limited list of messages from a mailbox -

i'm using php's built in imap functions build bare-bones webmail client (will used accessing gmail accounts). i've hit road block in mailbox list views, displaying paginated list of messages in mailbox sorted date (ascending or descending). my initial implementation retrieved messages mailbox imap_headers() , sorted array based on date, returned segment of array corresponded current page of list user wanted view. worked ok mailboxes small number of messages performance decreased size of mailbox grew (for mailbox ~600 messages, execution time on average around 10 seconds). , of users of client, 600 messages small number mailbox, between 5 , 10 thousand messages in inbox. so second stab @ problem instead of retrieving headers messages in mailbox, got total number of messages imap_num_msg() , using number constructed loop, loop counter used message number. , each iteration call imap_headerinfo() message number. this works better, under impression message number corre...

Error handling in C++ -

how make cin statement accepts integers? i don't think can force std::cin refuse accept non-integral input in cases. can write: std::string s; std::cin >> s; since string doesn't care format of input. however, if want test whether reading integer succeeded can use fail() method: int i; std::cin >> i; if (std::cin.fail()) { std::cerr << "input not integer!\n"; } alternatively, can test cin object itself, equivalent. int i; if (std::cin >> i) { // use input } else { std::cerr << "input not integer!\n"; }

installation - Winrar sfx deletes files too early -

i'm trying build sfx (self extracting archive) using winrar. i'm using vs2008 build setup.exe , myapp.msi. if setup.exe executed checking launches myapp.msi i'm using sfx options make extraction quiet , make extract temp folder: ;der folgende kommentar enthält sfx-skriptbefehle setup=setup.exe tempmode silent=2 overwrite=1 it seems winrar deletes msi right after setup.exe launched. setup.exe can't find msi , crashes. there way fix this? // edit: i solved problem (a while ago) calling myapp.msi instead of setup.exe: ;der folgende kommentar enthält sfx-skriptbefehle setup=myapp.msi tempmode silent=2 overwrite=1 the msi not exit until installation finished. 7-zip provides tools creating sfx installers, give try :)

python - SqlAlchemy add new Field to class and create corresponding column in table -

i want add field existing mapped class, how update sql table automatically. sqlalchemy provide method update database new column, if field added class. sqlalchemy doesn't support automatic updates of schema, there third party sqlalchemy migrate tool automate migrations. though "database schema versioning workflow" chapter see how works.

.net - How can I prevent strange characters when pulling the atom feed from a wordpress 3.0 blog -

i have atom feed on wordpress blog here: http://blogs.legalview.info/auto-accidents/feed/atom when download text of file , display on site, strange charactes accented 'a' here: recent studies showing car accident -related fatalities have declined 10% since 2008. reason i using following code in c# web application download feed: webclient client = new webclient(); client.headers.add(@"accept-language: en-us,en accept-charset: utf-8"); string xml_text = client.downloadstring(_atom_url); and xml_text.contains("Â") returns true, if download feed in browser no such  exists. i'm pretty sure character set issue, can't figure out why. examining client.responseheaders , can see in fact downloading text in utf-8, , response on .net site utf-8 well, can't figure out why weirdness appears i ...fatalities when force browser interpret feed iso-8859-1 instead of utf-...

iphone - How do I push a new controller via UIButton, nested in a UIScrollView? -

i have views part of tabbar. each view has navigationcontroller. in 1 of views have embeded xib component. scrolling view uibuttons inside it. i want slide in view, inside navigationcontroller when person taps button. can taps, etc. but, can't figure out how find controlling navigationcontroller of page push new view into. nothing seems work have tried. is possible? thanks you need pass reference navigation controller "down" view hierarchy. or pass object has reference navigation controller "down". or app delegate if has reference navigation controller.

machine learning - Number of hidden layers in a neural network model -

would able explain me or point me resources of why (or situations where) more 1 hidden layer necessary or useful in neural network? that's more similar way brain works (which might not computational advantage, lot of people researching nn gain insight way mind works, rather solve real world problems. its easier achieve kinds of invariance using more layers. example, image classifier works regardless of in image object found, or object's size. see bouvrie, j. , l. rosasco, , t. poggio. "on invariance in hierarchical models". advances in neural information processing systems (nips) 22, 2009.