Posts

Showing posts from February, 2011

spring - Build a website: should I use a number or random unique string as ID in URLs? -

hi building internet website java , spring framework. believe question not technology or framework related. i need have links in user interface visitors can click , see records. these links have format of http://mysite.com?id=number-id-or-random-unique-string not records allowed view. id parameter in url, use database-generated number id value , not need have additional programming. or use unique random string (for example: jctdjhdduls) id value (i have program part). numbers allow curious people (with or bad intentions) guess , try other ids. unique random strings seems better in regard. however, no matter numbers or strings value id, have security check in backend code see whether visitor allowed see record. perspective, not sure real benefit of having random string id. i hope have input experienced people. design decision choose? or other better ideas? thanks , regards. you can if want to, not go through trouble randomize id. @ root, "security through

vb.net - Arrow keys don't work after programmatically setting the selected item in a listview -

i have listview things in it, , have sub refresh listview deleting in , re-populating it. however, when user selects item , list refreshes, wanted have same item select once more. accomplished doing: listview.items(4).selected = true listview.select() which selects 5th item in list view (counting 0). however, when user presses or down keys, selected item jumps top item in list, , can't find way around this. the search has come here: arrow keys don't work after programmatically setting listview.selecteditem but not understand responses, need dumbed down version or simpler solution if possible, thank you. try using focused property on item. seems may have run before. listview.items(4).focused = true you may need set same property false first item in list.

html - table data going outside borders -

briefly , got <div id="tablewrapper"> <table> <tr> <td>veryveryveryveryveryeryveryveryveryveryveryveryveryveryvery longtext</td> </tr> <table> </div> and long text going outside table,div , wrapper borders. looking this textextexttextextexttextextext(border)|(border)textextexttextextexttextextext what css rules should use displey in next line like: texttexttexttexttexttexttexttexttext(border) texttexttexttexttexttexttex have tried setting display or width. use table-layout: fixed; attribute (be sure give table width too, e.g. 100% ) on table along applying word-wrap:break-word td 's. here's jsfiddle. css: table { table-layout: fixed; width: 100% } td { word-wrap: break-word; }

PHP add new array in an Two-dimensional Arrays -

i want create new instance in $shop array , : list1 = array( "rose" , 1.25 , 15); $list2 = array("daisy", 0.75 , 25); $list3 = array("orchid", 1.15 , 7); $list4 = array("orchid1", 2.15 , 9); $shop = array( $list1 , $list2 , $list3 ); //something line bellow $shop = $shop + array(array($list4)); echo $shop[3][0]; when execute code , i'm facing error msg : notice: undefined offset: 3 in c:\xampp\htdocs\array.php on line 13 line 13 : $shop = $shop + array(array($list4)); thanks in advance ^^ if $list4 array, don't need array(array()) . simplest , fastest way do: $shop[] = $list4; //equivalent $shop[] = array("orchid1", 2.15 , 9);

java - Swing Layout issue - JTable and JTree -

Image
i having trouble in using layout in swing properly. i trying achieve screenshot1 getting screenshot2. please see source code below. what dong wrong? how can achieve want (as in screenshot1). note: when run code multiple times, alignment between table tree getting correct. looks race condition here. screenshot1 screenshot2 source code: import javax.swing.*; import javax.swing.tree.defaultmutabletreenode; import java.awt.*; import java.util.date; public class swinglayouttest { private static final int screenwidth; private static final int screenheight; static { dimension screensize = toolkit.getdefaulttoolkit().getscreensize(); screenwidth = screensize.width; screenheight = screensize.height; } public static void main(string[] args) throws exception { jframe mainwindow = new jframe(); mainwindow.setdefaultcloseoperation(jframe.exit_on_close); mainwindow.setsize(800, 600); mainwindow.set

javascript - JQuery Mobile loading style and scripts on refresh -

the way jqm loads pages getting element attribute data-role="page" via ajax, , not whole document. so, how make jquery mobile load styles , scripts page (or refresh), rather loading them in entry point (index.htm)? just put them body tag. it described in other answer: why have put script index.html in jquery mobile

php - How can I use special characters in MySQL -

this question has answer here: how can prevent sql injection in php? 28 answers quick function replace ' \' in php 3 answers how can insert special characters ♣ , é sql table? when try error below: you have error in sql syntax; check manual corresponds mysql server version right syntax use near '] ♣ us3rnamé', '123456789', ' http://blabla.com/blabla/ ', 'http://' @ line 1 the data type text . guess shouldn't matter. try addslashes in php documentation

Why won't Python return my mysql-connector cursor from a function? -

python (2.7.3) violating mysql-connector cursor in strange way when return function. first example works fine... cnx = connect() sql = "select * mytable" cursor = cnx.cursor() cursor.execute(sql) row = cursor.fetchone() however, if return cursor , attempt fetchone() (or fetchall()) outside, throws exception... def run_query(): cnx = connect() sql = "select * mytable" cursor = cnx.cursor() cursor.execute(sql) return cursor mycursor = run_query() row = mycursor.fetchone() it throws... file "/usr/lib/pymodules/python2.7/mysql/connector/cursor.py", line 533, in fetchone row = self._fetch_row() file "/usr/lib/pymodules/python2.7/mysql/connector/cursor.py", line 508, in _fetch_row (row, eof) = self.db().protocol.get_row() attributeerror: 'nonetype' object has no attribute 'protocol' this in spite of fact "print type(mycursor)" print "mysql.connector.cursor.mysqlcursor" what

modifying javascript "slideshow" image wtih css -

Image
im quite beginner in css , js, need implement working "slide show image", tried google it, , working script complete css. but got if insert shorter image : i have tried modify self, control/button disappear everytime tried change height. i think have 3 choices : delete margin-botton centering image do both of them which 1 easiest? , how? :d this complete css code : #slides { display: none } #slides .slidesjs-navigation { margin-top:5px; } a.slidesjs-next, a.slidesjs-previous, a.slidesjs-play, a.slidesjs-stop { background-image: url(../image/btns-next-prev.png); background-repeat: no-repeat; display:block; width:12px; height:18px; overflow: hidden; text-indent: -9999px; float: left; margin-right:5px; } a.slidesjs-next { margin-right:10px; background-position: -12px 0; } a:hover.slidesjs-next { background-position: -12px -18px; } a.slidesjs-previous { background-position: 0 0; } a:hover.slidesjs-previous { backgroun

java - ExecutorService is not shutting down -

i have following code executorservice es = executors.newsinglethreadexecutor(); es.submit(new runnable() { @override public void run() { while(true); } }); es.shutdownnow(); the problem executorservice doesn't shutdown after call shutdownnow. documentation says attempts stop actively executing tasks. so why es failing shutdown? i did , worked: executorservice es = executors.newsinglethreadexecutor(); es.submit(new runnable() { @override public void run() { while(!thread.currentthread().isinterrupted()); } }); es.shutdownnow(); the reason shutdownnow doesn't terminate thread. interrupts running threads.

Multidimensional array in Android from SQLite -

could please explain how can achieve same sqlite query in java? following code: static final string[] authors = new string[] { "roberto bola–o","david mitchell"}; private static final string[][] books = new string[][] { "the savage detectives", "2666" },{ "ghostwritten", "number9dream", "cloud atlas","black swan green", "the thousand autumns of jacob de zoet" } }; this code following class implement sectioned gridview: sectioned gridview

c - Generic function for comparing two integers? -

is there standard c (linux) function, or code-efficient good-performing approach, comparing 2 integers of arbitrary size? i'm looking parameters int intcmp(const void *a, const void *b, size_t size) works on integers a , b practical size size . ( memcmp() work (i think) if architecture big endian.) the implementation tend use goes (with improvements efficient integer compare function ) it's not generic , has enough of code overhead think twice before slotting in. int intcmp(const void *a, const void *b, size_t size) { #define case_size_return_a_b_cmp(_t) \ case sizeof(_t): \ return ((*(_t *)(a) > *(_t *)(b)) - (*(_t *)(a) < *(_t *)(b))) switch (size) { case_size_return_a_b_cmp(char); case_size_return_a_b_cmp(short); case_size_return_a_b_cmp(int); case_size_return_a_b_cmp(long long); } #undef case_size_return_a_b_cmp assert(0); return 0; } static inline functions have advantage of argume

android - EditText, How can control the cursor in TextWatcher? -

i have textwatcher on edittext, in method aftertextchanged, add characters edittext move cursor end of edittext continue adding text, have problems that. like this: public void aftertextchanged(editable s) { if(edittext.gettext().length()==2){ // append dot edittext edittext.append("."); // move cursor @ end position in edittext edittext.setselection(edittext.gettext().length()); } } in android 4.0v or superior, cursor stay before "." , , in 2.2v works fine, in both can't delete characters. anyone same problem ? grettings you can avoid delete problem... public class mainactivity extends activity { int count=0; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); final edittext edittext=(edittext)findviewbyid(r.id.edittext1); edittext.addtextchangedlistener(new text

php - multidimensional array, transpositional values and merged result -

i have , array $aarg these values array ( 0 => 'reviewed_entity', 1 => 'kiosk', ) array ( 0 => 'tripadvisor', 1 => 'tripadvisor2', ) array ( 0 => 'google', 1 => 'google2', ) array ( 0 => 'yahoo', 1 => 'yahoo2', ) i need make appear below. array ('kiosk' => array ( 'tripadvisor' => 'tripadvisor2','google' => 'google2','yahoo' => 'yahoo2',)); please note few things kiosk value of [1] of first array. , it's parent array' other arrays have values of [0] transpose key [1] all arrays have been merged one. thank guys have had sleepless nights trying final merge result, please share me fastest way desired results your input array doesn't seems correct. thought following.. <?php $aarg = array( array ( 0 => 'reviewed_entity', 1 => 'kiosk', ), array ( 0 => 'tripadvisor&

histogram - How to remove the over x line in pylab (python)? -

how remove on line after banana histogram can stick vertical line? import matplotlib matplotlib.use('svg') pylab import* label = ['apple','orange', 'banana'] number = [5,4,3] barwidth =0.5 bar_location= range(len(number)) bar(bar_location,number,width=barwidth) xlim(0-barwidth,len(number)) xticks([ + barwidth/2 in bar_location], label) tittle('fruits') xlabel('my_fruit') ylabel('number') savefig('fruits.svg') show() you can set range of x-axis xlim() , e.g.: xlim(0 - barwidth, len(number) - 0.5) (but make sure insert before savfig() ).

javascript - Adding filter to select multiple rows using Ctrl key in Firefox but in Chrome it's working fine -

when try select multiple rows using ctrl key border of selected td blue. i using code check whether ctrl key pressed or not: $("#unselectedtab td").click(function (event) { if (event.ctrlkey) { $(this).toggleclass("backgroundcolor"); } else { $("#unselectedtab td").removeclass("backgroundcolor"); $(this).addclass("backgroundcolor"); } }); migth be: event.browserevent.ctrlkey you should put breakpoint in firebug , see properties event has.

NHibernate with XML as a database? -

we have project, need use nhibernate perform crud operation xml or flat file (.txt) database. can use nhibernate other rdbms? short answer yes long answer it quite work because minimum implement iconnection, icommand, driver , parser translate sql xpath or whatever. it easier load xml/txt (in-memory) sqlite database in format best suited use case , query through nhibernate.

objective c - Kobold2d: KKInput touch handling using touchPhases -

i don´t understand this, trying set touch handling using default template, difference have made delegate how handle touches classs implement protocol. problem ktouchphase works ktouchphasecancelled . -(void) update:(cctime)delta { if ([input isanytouchonnode:self touchphase:kktouchphaseany]) { cclog(@"touch: beg=%d mov=%d sta=%d end=%d can=%d", [input isanytouchonnode:self touchphase:kktouchphasebegan], [input isanytouchonnode:self touchphase:kktouchphasemoved], [input isanytouchonnode:self touchphase:kktouchphasestationary], [input isanytouchonnode:self touchphase:kktouchphaseended], [input isanytouchonnode:self touchphase:kktouchphasecancelled]); } ccdirector* director = [ccdirector shareddirector]; if (director.currentplatformisios) { [self gesturerecognition]; // calls method pasted bellow if ([kkinput sharedinput].anytouchendedthisframe)

java - Is it possible to get the exact maven command from an eclipse build process? -

short version: there way at/inspect command eclipse uses build maven project, in order run command command line? long version: i'm trying set automated build/deploy process, uses maven command line. want is: run maven build kill running server delete current .war , exploded directory copy built .war file server start server the build process on developer machine tightly integrated eclipse. i've attached server (tomcat 6) can stop/start/publish etc within eclipse. however when build command line using mvn clean package (still on development machine), package built not seem build correctly (the build successful, encounters errors upon deployment). now spend time trying figure out perfect command working, figured if works within eclipse, find exact command needed. can't seem find it. is possible @ command? system info: os: windows 7 eclipse version: juno service release 2 (build id: 20130225-0426) server: tomcat 6.0.32 maven: 3.0.5 ja

c# - Asynchronously populate gridview on button click -

i populate gridview inside update panel on button click. gridview getting populated doesn't show on screen. missing? below code i'm using: public delegate void bindgrid_delegate(); protected void btnsearch_click(object sender, eventargs e) { try { // databind of controls bindgrid_delegate bd = new bindgrid_delegate(bindgrid); iasyncresult ar = bd.begininvoke(null, null); //invoking method } catch (exception ex) { scriptmanager.registerclientscriptblock(this, this.gettype(), "pageexception", "alert('" + ex.message + "');", true); } } private void bindgrid() { try { dataset resultdataset = getdata(); gvshowresult.datasource = resultdataset; gvshowresult.databind(); updatepanel2.update(); } catch (exception ex) { scriptmanager.registerclientscriptblo

datatables - jquery data table, count several rows as a single row for the dropdown to select number of entries to show -

using jquery data table , following code dropdown option values above table 70,175,350 , all. want values show 10, 25, 50, all, every single row count should equal 7 rows.so when select 10 drodown, table should show 10*7=70 rows, 25 should show 175 rows etc. var otable = $('#example').datatable({ "sdom": 't<"clear">lrtip', "otabletools": { "bsort": false, "sswfpath": "datatables-1.9.4/extras/tabletools/media/swf/copy_csv_xls_pdf.swf", "abuttons": [ { "sextends": "xls", "sfilename": "*.xls" } ] }, "aasorting" : [], "alengthmenu": [[10, 25, 50, -1], [70, 175, 350, "all"]], }); how ? i think want: "alengthmenu": [[70, 175, 3

ant contrib - ant warning : could not load antlib.xml -

i have antcontrib.jar in lib folder of ant. set ant home "c/prog files/apache-ant". but still when run build.xml, warning "could not load antlib.xml , antcontrib.prop". because of this, not able "regex" operations. i loaded antcontrib.jar in lib folder of ant. where wrong here? provide resource , classpath in taskdef correctly follows <typedef resource="net/sf/antcontrib/antlib.xml" classpath="<path ant-contrib.jar>"/>

version control - Deleting tracked file from the file system vs hg remove -

i'd know if there consequences when deleting tracked file file system (e.g. via windows explorer) in comparison when using hg remove delete file system , untrack it. in both cases, i'll commit afterwards, in first case tortoise hg marks file missing exclamation mark, second marks clean , ready removal. besides there differences? if go file system path , don't make other changes tracked files, hg give error when try commit: nothing changed (1 missing files, see 'hg status') (this special case of nothing changed .) if have changed else, hg won't complain @ point, file's status continue show missing hg status . has negative effect of cluttering (mental) workspace , making harder tell @ glance working directory's current status is. moreover, the file remains in repository , restored hg update revisions still being tracked! hg remove return error if file deleted filesystem; in case should use hg forget tell mercurial stop track

Makefile separate directories -

it takes long time read make , gcc manual. since need basic function of them, want learn them quickly. the project directory following. cwd |----source----1.cpp |----header----1.h |----object----1.o |----makefile there 3 directories , 1 makefile in current working directories, , "1.cpp" includes "1.h". want use makefile in cwd compile project such object output in object directory. this simplified version of problem have now. since relatively hard begin scratch, me write makefile simple problem? , try learn , solve own problem. or suggests parts of make , gcc need learn solve problem. thanks in advance. this enough compile source , produce object: object/1.o: source/1.cpp header/1.h $(cxx) -c source/1.cpp -iheader -o object/1.o if want build executable, maybe called "one", add rule above that: one: object/1.o $(cxx) object/1.o -o 1 object/1.o: source/1.cpp header/1.h $(cxx) -c source/1.cpp -iheader -o object/1.o

android - How many cursor we can open in sqlite database? -

i have database single table .table contains around 7000 rows , 3 columns including primary key. when use cursor operation blocking ui. you can refer these questions . link 1 link2 now due , in situation try out new thing if possible. i want clarification if possible or not . question : can use more 1 cursor read data database. for example 7 cursor , each can read 1000 rows table , meanwhile show progress dialog . so complete database operation when user not using ui . let me know can done . if provide code snippet , best. thank time . multiple cursors should not done, programming nightmare manage. if cursor locking ui should run database query within asynctask, http://www.vogella.com/articles/androidbackgroundprocessing/article.html asynctask. any tasks take long time complete, should done on separate thread such asynctask otherwise user presented anr (application not responding).

Iphone WIFI "call home" function? -

we're deploying wifi hotspot service in locations via unifi. have sign mobile number , sms includes activation link. the problem is: the iphone seems check connectivity of wlan internet. so, after sent number, , before clicked on actvation link, theres no internet connection (basically is, youre not allowed outside of internal network until activation link has been clicked). the iphone recognizes , disables wifi, because can't contact "testserver" - on 3g again, , activation link isn't reachable anymore. my question: does know ip iphone tries connect before deactivates wifi? so whitelist ip reachable without authentication, iphone wouldnt disable wifi anymore. i've tried catch via wireshark, didnt see anything. :(

java - Error while use authentication from AD server -

package mypack; import java.util.*; import javax.naming.*; import javax.naming.directory.*; public class adcheck { public static void main(string[] args) { try { hashtable env = new hashtable(); env.put(context.initial_context_factory,"com.sun.jndi.ldap.ldapctxfactory"); env.put(context.provider_url,"ldap://myad.com:385"); env.put(context.security_authentication,"digest-md5"); env.put(context.security_principal,"my_user_name"); env.put(context.security_credentials, "my_passwors"); dircontext ctx = new initialdircontext(env); ctx.close(); } catch(namingexception ne) { system.out.println("error authenticating user:"); system.out.println(ne.getmessage()); return; } system.out.println("ok, authenticating user"); } } getting error: jav

c# - Accessing Active Directory to get User's Manager in asp.net -

i making user management module of application authenticate user credentials based on domain login details. authenticating not problem, problem need particular user's manager. i using following method retrieve "manager" property of user: directoryentry de = new directoryentry(path, user, pass, authenticationtypes.secure); directorysearcher ds = new directorysearcher(); ds.searchroot = new directoryentry("ldap://xyzdomain", "username", "pwd"); ds.filter = "(|(&(objectcategory=person)(objectclass=user)(mailnickname=*domainalias*)))"; //ds.propertynamesonly = true; ds.propertiestoload.add("manager"); list<string> users = new list<string>(); string s = "undefined"; foreach (searchresult sr in ds.findall()) { directoryentry dee = sr.getdirectoryentry(); s = (string)dee.properties[""].value ?? "<undefined>"; users.add(s); } this retur

c++ - operator new(n) versus new unsigned char[n] for placement new -

i'm allocating memory later used constructing objects placement new . should using operator new(n) , or should using new unsigned char[n] ? why? factors: new[] must matched delete[] / new() delete they communicate different things. operator new(n) request memory unspecified purposes, whereas new unsigned char[n] loosely implies intent store characters there. the array form may slightly worse performance / efficiency wise - exact details depending on implementation: 5.3.4/12 new t[5] results in call of operator new x non-neagtive unspecified value representing array allocation overhead: result of new-expression offset amount value returned operator new[] .... btw - neither initialised: operator new() returns void* uninitialised memory: see 3.7.4.1/2 "there no constraints on contents of allocated storage on return allocation function", whereas 5.3.4/15 says "a new-expression creates object of type t initializes object follows: i

Block incoming calls and sms in android -

i tried block incoming calls , sms in android given numbers. after block number, when getting call blocked number, caller can here voice message number busy . but there way change voice message power off, no service, number not in service messages ? that not possible carriers responsible giving responses.

javascript - how to use Facebook share button in my web page to share or post something to facebook page? -

i added facebook share button website sharing or posting things profile timelines not sharing or posting page(like fans page in facebook).is there anyway choose post fan page? 1 can me? plz.. considering whatever "things" in website, product id 123, example. you can make users it/share using standard fb-like button. when and/or share it, comes thing liked on website. if object of yours, has proper url proper meta-tags, show nicely on fb story. guide here you can use facebook debug tool testing if sharing, meta tags working expected here. if want page object of sharing, thing can done users can page website. cannot share stories api page, page not entity. meaning not user. so, if page said, user xyz liked item abc on yourwebsite.com it won't make sense people see this. instead if userxyz liked itemabc on site, following update on fb make more sense. userxyz liked itemabc on yourwebsite.com (this have proper pictorial representation , clicka

knockout.js calling custom binding function -

i've found unusual code, don't understand how call custom binding function , how supposed work. here code: viewmodel: ko.bindinghandlers.test = function ($) { return { init: function (el, valueaccessor, bindingsaccessor, viewmodel) { }, update: function (el, valueaccessor, bindingsaccessor, viewmodel) { } } } view: <input type="text" data-bind="test: ???, value: 0, settings: { test: 'test-value' }"> your code wrong since have have closure scope need todo ko.bindinghandlers.test = (function ($) { return { init: function (el, valueaccessor, bindingsaccessor, viewmodel) { }, update: function (el, valueaccessor, bindingsaccessor, viewmodel) { } } })(jquery); edit: in markup bind test member on viewmodel like <input type="text" data-bind="test: mymember /> to access binding custom binding init: function (el, valueaccess

haskell - Construct predicates with lenses -

i want create function a -> bool using lenses of a. instance: data = { _foo :: int, _bar :: int } makelenses ''a l :: [a] l' = filter (\a -> a^.foo > 100) l the filter predicate looks bit clumpsy. ((>100).(^.foo)) not better. without lenses, use ((>100) . foo) . is there nice way create such predicates lens ? ideally allow predicates (\a -> a^.foo > 100 && a^.bar < 50) . i think ((>100).(^.foo)) best can using standard operators. if willing define new comparison operators lenses, like: import control.lens hiding ((.>)) import control.monad (liftm2) import control.monad.reader (monadreader) import data.function (on) (.==) :: (monadreader s m, eq a) => getting bool s -> -> m bool (.==) l = views l . (==) infix 4 .== (.==.) :: (monadreader s m, eq a) => getting s -> getting s -> m bool (.==.) = liftm2 (==) `on` view infix 4 .==. (.<) :: (monadreader s m, ord a) => getting

javascript - Change symbols of currency fields upon changing Currency on the Form in CRM 2011 -

some of might have faced issue in microsoft dynamics crm 2011 today when assigned task change currency lookup value dynamically match account currency in case of difference. did same calling setlookupvalue javascript function set currency value according account currency. setlookupvalue("transactioncurrencyid", "transactioncurrency", accountcurrency.id, accountcurrency.name); after doing unit test, currency lookup value changing observed currency symbols of fields defined currency datatype on form not changing destination currency in case accountcurrency . e.g. currency field changed us dollar (usd) euro (eur) fields showing usd prefix. after spending hours on web gathered useful information in chunks different sources respect problem. i have managed device 2 ways , tested both ways on ie browser microsoft dynamics crm 2011 change currency symbol of every currency field on form dynamically. using odata (simple , effective no cross-

load testing - JMeter: run a single Thread Group with dynamically generated Number of Threads (users) -

i have several thread groups in test plan, same exception of number of threads, keeps incrementing tg tg. whenever have change single thing, it's nightmare have go each , every 1 of them make same change. is there way make 1 single thread group run several times different number of threads generated dynamically, , have each sample inside on single row of summary report listener (for example)? thanks. put samplers inside transactioncontroller or simplecontroller in first thread group use modulecontroller in other thread groups referencing first one.

ServiceStack Redis CRUD -

first time using servicestack redis. looked around web , not find basic crud example. closest found this , this . wondering if i'm doing right. thanks. note : assume using using statement. took out because stackoverflow complained had 'too code'. using (var client = redismanager.getclient().gettypedclient()) public class testuser { public string username; } public ienumerable<testuser> getall() { return client.lists["users"].asqueryable(); } public void updateall(ienumerable<testuser> users) { var list = client.lists["users"]; foreach (var testuser in users) { client.setentry(testuser.username, testuser); client.store(testuser); if (!list.contains(testuser)) list.add(testuser); } client.saveasync(); } public testuser get(string username) { return client.getbyid(username); } publi

javascript - If element with ID has as class -

this question has answer here: test if element contains class? 18 answers what have is function setmenucurrentto(variable) { document.getelementbyid("game_" + variable).style.display = "block"; var elems = document.getelementsbyclassname("current_nav"); (var i=elems.length; i--;) { elems[i].style.display = "none"; elems[i].classname = 'none'; } document.getelementbyid("game_" + variable).classname="current_nav"; } } so when click tag specific element(variable) adds content , "hides" one. there bug when click twice in same button, content dissapears , don't have anymore content. so tried code: function setmenucurrentto(variable) { document.getelementbyid("game_" + variable).style.display = "block"; if (getelementbyid("game_" + variable).hasclass(&qu

Find number of decimal digits of a variable in MATLAB -

given variable x = 12.3442 i want know number of decimal digits of variable. in case result 4. how can without trial , error? here compact way: y = x.*10.^(1:20) find(y==round(y),1) assumes x number , 20 maximum number of decimal places.

java - HttpServletRequest UTF-8 Encoding -

this question has answer here: how pass unicode characters jsp/servlet request.getparameter? 4 answers i saw lot of question mine not single answer works... here's thing : want parameters request (characters accents) doesn't work. tried user request.setcharacterencoding( "utf-8" ) didn't work either. i know urldecoder.decode( request.getquerystring(), "utf-8" ) returns me rights characters request.getparametervalues() doesn't work ! have idea ? thank paul's suggestion seems best course of action, if you're going work around it, don't need urlencoder or urldecoder @ all: string item = request.getparameter("param"); byte[] bytes = item.getbytes(standardcharsets.iso_8859_1); item = new string(bytes, standardcharsets.utf_8); // java 6: // byte[] bytes = item.getbytes("iso-8859-1"); /

java - Will I receive GCM messages if Android kill my app and if I do a Force Close from the settings? -

i'm newbie android development , i'm interested in 2 things connected google cloud messaging. does android absolutely kill applications if run long time in background ios does? , if receive gcm notifications after app killed android? is there difference between force close (from settings menu) , when app killed android? , if force close receive gcm notifications? 1 - yes, if install in manifest broadcast receiver listens gcm, triggered anyway. event depends on app. common practice start intent service handles message. it's make interact activities of app. 2 - android 3.1, if user force closes app, stop notified of broadcast until user not start app again. check "launch controls on stopped applications" here more details.

javascript - Manipulating JSON data sets -

so have array myarr[] of json objects in form: { "a":"", "b":"" } are there efficient methods getting array of b: [ myarr[0].b, myarr[1].b, myarr[2].b, ... ] or have manually iterate through myarr build array of b? why not have fun prototypes , extend array obtain handy , reusable function: array.prototype.pluck = function(key) { var = this.length, plucked = []; while(i --) { plucked[i] = this[i][key] || "" } return plucked; } with one, can do: collection.pluck(keyname) to desired result. check here working demo: http://jsfiddle.net/jyrnn/1/

mysql - Wikipedia: dump article id's and it's category -

i make mysql database every wikipedia article id , it's category id (most general category). saw wikipedia gives entire dump, , few others links between categories. saw there mediawiki can't manage find right query send. but nonetheless can't find how dump big file article id's , it's category id. how should it? how data should expect? wikipedia provides dumps of of data. 1 want categorylinks.sql , contains list of category names (categories don't have ids) each article id. want page.sql , contains map article id title. to work dumps, can import them local mysql database, or use library parses dumps directly, the 1 wrote .net . but each article in several categories , there no notion of primary category or that. so, if want 1 category each article, have figure out how yourself.

php - PHPEclipse code templates incorrect indenting -

indentation behaviour incorrect using phpeclipse code templates. if code indented @ start of template insertion, indent depth ignored , tabs used if use spaces indenting. example: "function" code template, inserted when indent depth 4 spaces: function function_name( $param ) { // 4 spaces return ; // tab? } // nothing! i specified use spaces in window -> preferences -> phpeclipse -> php -> typing tab -> checked insert spaces tab and window -> preferences -> phpeclipse -> php -> formatter -> style tab -> unchecked indentation represented tab i tried use tabs, nothing: function function_name( $param ) { // 1 tab return ; // 1 tab... (*sigh*) } // nothing! i checked code template, seems correct , similar java code templates, work expected. "use code formatter" checked. , goog

regex - Awk gensub transformation -

echo "0.123e2" | gawk '{print gensub(/([0-9]+\.[0-9]+)e([0-9]+)/, "\\1 * 10 ^ \\2", "g")}' gives me "0.123 * 10 ^ 2" result expected. there way tell calculate term "12.3" ? in general: there way modify/transform matches (\\1,\\2,...)? it easier perl: perl -pe 's/(\d+\.\d+e\d+)/ sprintf("%.1f",$1) /ge' filename with test data: echo '0.123e2 xyz/$&" 0.3322e12)282 abc' | perl -pe 's/(\d+\.\d+e\d+)/ sprintf("%.1f",$1) /ge' 12.3 xyz/$&" 332200000000.0)282 abc with awk: awk '{ while ( match( $0, /[0-9]+\.[0-9]+e[0-9]+/ ) > 0 ) { num = sprintf("%.1f", substr( $0, rstart, rlength ) ) sub( /[0-9]+\.[0-9]+e[0-9]+/, num ) } print $0 }' filename

c# - Linq to SQL Query Slow -

i'm trying following sql query linq sql. select course_sections.sec_subject, course_sections.sec_course_no, course_sections.sec_no, sectionenrollments.sectionenrollment course_sections inner join (select stc_course_name, stc_section_no, count(*) sectionenrollment student_acad_cred stc_term = '2012fl' group stc_course_name, stc_section_no) sectionenrollments on course_sections.sec_subject + '-' + course_sections.sec_course_no = sectionenrollments.stc_course_name , course_sections.sec_no = sectionenrollments.stc_section_no sec_term = '2012fl' my first attempt this var query = sections in db.course_sections sections.sec_term == "2012fl" orderby sections.sec_subject, sections.sec_course_no, sections.sec_no select new { sections.sec_subject, sections.sec_course_no,

javascript - PHP Force Dynamic content into the DOM -

i'm trying come way html/text user sees on given url, though of see may produced dynamically (on page-load, example) not in dom, manually loading javascripts , putting resulting data page. my thinking this: (naively) return array of javascript files scraping <script> tags src attribute. return array of on-page hard-coded javascripts like: <script> var example = true; </script> create function decide real urls encountered in internal , external page javascripts. example, when encountering example $.ajax({ url: '/relative-js-file.js' , figure out absolute url php may access page. using php, load of javascript found on page in way resembles being loaded on actual page (the page came from). take whatever data javascript returns (plain, html, etc.), , inject new plain-text and/or html original page <body> . i realize not work lot of time, hope @ least starting point until can find better solution or create more advanced function handle u

concurrency - How to handle synchronization of frequent concurrent read/writes on a Java ArrayList -

i have java class contains arraylist of transaction info objects queried , modified different threads on frequent basis. @ basic level, structure of class looks (currently no synchronization present): class statistics { private list<traninfo> traninfolist = new arraylist<traninfo>(); // method runs - every time transaction comes in. void add(traninfo traninfo) { traninfolist.add(traninfo); } // method acts cleaner , runs occasionally. void removebasedonsomecondition() { // code determine items remove traninfolist.removeall(listofunwantedtraninfos); } // methods query stats on tran info. // these methods called frequently. stats getstatsbasedonsomecondition() { // iterate on list of tran info // objects , return stats } stats getstatsbasedonsomeothercondition() { // iterate on list of tran info // objects , return stats } } i need

python - Adding water flow arrows to Matplotlib Contour Plot -

Image
i generating groundwater elevation contour matplotlib. see below here have now; how can add water flow arrows image below? i want add arrows make this: if has ideas and/or code samples appreciated. you'll need recent (>= 1.2) version of matplotlib, streamplot this. need take negative gradient of head (a.k.a. "water table" surface aquifers) grid. as quick example generated random point observations of head: import numpy np scipy.interpolate import rbf import matplotlib.pyplot plt # make data repeatable np.random.seed(1981) # generate random wells random head (water table) observations x, y, z = np.random.random((3, 10)) # interpolate these onto regular grid xi, yi = np.mgrid[0:1:100j, 0:1:100j] func = rbf(x, y, z, function='linear') zi = func(xi, yi) # -- plot -------------------------- fig, ax = plt.subplots() # plot flowlines dy, dx = np.gradient(-zi.t) # flow goes down gradient (thus -zi) ax.streamplot(xi[:,0], yi[0,:], dx, dy, co

javascript - scroll in both directions with iScroll -

i make image slide momentum freely in direction (no snap). i came across iscroll4 , great script (works great on ios , android). js code: var myscroll; function loaded() { myscroll = new iscroll('wrapper', { hscrollbar: false, vscrollbar: false, snap:false, vscroll: true, hscroll: true }); } html code: <div id="wrapper"> <div id="scroller"> <div id="thelist"> <img id="theimg" src="https://www.google.com/images/srpr/logo4w.png" width="300px" height="200px"> </div> </div> </div> css: body,ul,li { padding:0; margin:0; border:0; } #wrapper { position:absolute; z-index:1; top:-500px; bottom:0px; left:-500px; width: 100%; height: 100%; overflow:auto; background-color: red; } #scroller { position:a

design patterns - Purpose of factory classes in Java -

i have used java quite long time, never did find out, makes factories special. can please explain me? there reason why should want implement own factory (if it's possible)? factory patterns fantastic decoupling classes. example, let's assume common interface, animal , , classes implement it. dog , cat . if not know user want generate @ run time, can not create dog pointer. won't work! what can though, port separate class, , @ run time, pass discriminator factory class. class return object. example: public animal getinstance(string discriminator) { if(discriminator.equals("dog")) { return new dog(); } // etc. } and calling class uses: string type = "dog"; animal value = factory.getinstance(type); this makes code extremely readable, separates decision logic logic performed on value , decouples classes via common interface. in all, pretty nice pattern!

javascript - jQuery Change Value Using Data Attribute -

i have multiple elements that'll have same data attributes different values, how can jquery change value? below example html. <div data-one="test" data-two="test2"></div> <div data-one="testing" data-two="hello"></div> <div data-one="yo" data-two="test3"></div> by default, value of div data-one when class active on body tag, change values data-two value. i thought storing values variable easier although divs don't have id's , they're scattered around in dom makes difficult. so far had this: if($('body').hasclass('active')) { $('div').html($(div).data('two')); } you can use html method. var has = $('body').hasclass('active'); $('div').html(function() { return has ? $(this).data('two') : $(this).data('one'); }); http://jsfiddle.net/44du5/

java - Issue when dynamically setting properties using reflection -

i have task object properties need populated data received via json web service. property names mapped json keys. using following code in attempt populate object app crashes when hits line: while(looper.hasnext()){ string key = looper.next(); string val = json.get(key).tostring(); user.getclass().getdeclaredfield(key).set(user, val); // crash } the object called user. have verified key variable match property in user object. ideas on how fix this? thanks! you should set field accessible field field = user.getclass().getdeclaredfield(key); if (field != null) { field.setaccessible(true); field.set(user, val); }

php - Replacement for deprecated function mysql_connect -

this question has answer here: mysqli or pdo - pros , cons? [closed] 13 answers so have amazon web service database set up i'm working off old tutorial application i'm planning on using with. i noticed mysql_connect deprecate when looked up. what can use alternative? how can connect amazon database? <? mysql_connect("localhost", "username", "password") or die ("can't connect database server"); mysql_select_db("videorecorderdemo") or die ("can't select database"); mysql_query("set names 'utf8'"); ?> i error: warning: mysql_connect() [function.mysql-connect]: access denied user 'username'@'192.168.1.1' (using password: yes) in /www/zxq.net/r/e/d/red5vptest/htdocs/utility/db.php on line 2 can't connect database server no matter credential

php - mysql how to show some rows of table depending on one field and depending on one field in other table? -

i have script members login , read posts catagory have in table called posts, click button , entry inserted table called postsread collecting postname, memberid, , date showing had been read them. looking query display them posts have not read. **tables** **fields** posts id, name, date, from, topic, info, cat postsread id, postname, memberid, date users id, memberid, pass, fname, lname, email sessions holding $_session['memberid'], unsure of how query between 2 tables i'm looking for. like: show posts in posts except in postsread members memberid next corresponding postname. using php version 5.3, , mysql 5.0.96. i using following display posts database: $sql=mysql_query("select * posts cat='1' order date desc"); but not differentiate between if member has clicked stating have seen them yet or not. i have looked many places , see examples close cant fit needing. don't understand how write this. have trie

OpenLayers removes/destroys new features when zooming out -

i have openlayers.layer.vector layer allow user create, modify , delete features , feature attributes. changes saved when hit "save changes" button. if user creates new feature, zooms map out ways, causes openlayers remove features layer , add in features saved geoserver db. have tried hanging onto newly created features , adding them layer on "loadend" event openlayers has destroyed geometry of new features useless. how prevent openlayers nuking new features when zooming out? i've used featuresremoved event removed features verify if "insert" state. prevent multi-insertions on multiple zoom-out gave feature intermediate state. , made insertions on loadend, changing state "insert" again. please note have 1 editing layer time. var nuevas_features = null; .... .... .... .... eventlisteners: { 'loadstart': function(evt) { nuevas_features = null; }, 'featuresremoved' : function(algunfeature) { nuev

c# - Use NativeWindow to disable screensaver -

i want disable screensaver , monitor power off. @ stage there's no windows form, youse. wan't use nativewindow. here's code sealed class observerwindow : nativewindow, idisposable { internal observerwindow() { this.createhandle(new createparams() { parent= intptr.zero }); } public void dispose() { destroyhandle(); } protected override void wndproc(ref message msg) { if (msg.msg == wm_syscommand && ((((long)msg.wparam & 0xfff0) == sc_screensave) || ((long)msg.wparam & 0xfff0) == sc_monitorpower)) { msg.msg = 0; msg.hwnd = intptr.zero; } base.wndproc(ref msg); } } the problem is, wndproc not called wm_syscommand. actualy wndproc called 4 times. @ last call there's msg.msg == wm_create. i think i'm missing create parameter. have advise? regards michael update i running code i

rotation - THREEJS: Rotating the camera while lookingAt -

i have moving camera in camera container flies arond scene on giving paths airplane; can move position x,y,z positive , negative. camera container looking @ own future path using spline curve. now want rotate camera using mouse direction still keeping general looking @ position while moving forward object. say, want turn head on body: while moving body having general looking @ direction, turning head around lets 220 degree , down. can't behind body. in code cameracontainer responsible move on pline curve , lookat moving direction. camera added child cameracontainer responsible rotation using mouse. what don't working rotation of camera. guess common problem. lets camera when moving on x-axes moves not straight, moves curve. specially in different camera positions, rotation seems different. tryiing use cameracontainer avoid problem, problem seems nothing related world coordinates. here have: // camera in container cameracontainer = new threejs.object3d(); cameracon

mongoid3 - Mongoid Identity Map setting not taking effect in Rails console -

it not appear identity_map setting getting picked config/mongoid.yml file. here's file: development: sessions: default: uri: mongodb://localhost:27017/test_development options: &defaultopts op_timeout: 60 allow_dynamic_fields: false identity_map_enabled: true preload_models: true raise_not_found_error: false when run through rails_env=development rails console map not turned on: $ rails_env=development rails c loading development environment (rails 3.2.13) [1] pry(main)> mongoid.using_identity_map? => false [2] pry(main)> mongoid.identity_map_enabled? => false even attempt manually load mongoid , file doesn't change it: [3] pry(main)> require 'mongoid' => false [4] pry(main)> mongoid.load!("./config/mongoid.yml") => {"sessions"=> {"default"=> {"uri"=>"mongodb://localhost:27017/test_development", &