Posts

Showing posts from March, 2012

xml - XSLT: Reuse a template within another template -

i have xslt file displays title , artist name of cd. have 3 templates, first template displays title, second template displays artist name, , third template contains hidden table. hidden table displayed using checkbox. want reuse title , artist templates in order show them table data inside third template when visible. the problem third template doesn't show on browser because don't know assign match attribute. highly appreciated. thanks. expected result: http://oi61.tinypic.com/6ibkur.jpg ![1] index.html <html> <head> <script> function loadxmldoc(filename) { if (window.activexobject) { xhttp = new activexobject("msxml2.xmlhttp"); } else { xhttp = new xmlhttprequest(); } xhttp.open("get", filename, false); try {xhttp.responsetype = "msxml-document"} catch(err) {} // helping ie11 xhttp.send(""); return xhttp.responsexml; } function displayresult() { xml = loadxmldoc("cdcatalog.xml"); xsl

connection - Raspberry pi b+ remote access or network access?, Is it possible? -

i new user raspberry pi b+, have set , can use now. bought because want learn how program want star using want use command line. know if there way connect laptop raspberry via ether net cable or usb not need external monitor, keyboard , mouse. know if possible?, there software it? thank help it possible. need bootable os on microsd card enabled ssh , use wired network (or wireless network wifi usb adapter). possible use com port console access (most need usb com adapter). when bought first rpi using usb serial cable because had microsd noob require gui installation. took me long time i'm using gui on wifi (i'm running x2go server on pi) , never connected monitor or keyboard pi. easier if have installed raspbian enabled ssh on microsd card.

c++ - Arduino Library Error, Class name hasn't been defined -

i'm trying run circular buffer class on arduino. wrote class on c++ ide, , compiled , ran fine. copy/pasted .cpp , .h files arduino project folder, next .ino file. when tried run, got ( http://i.imgur.com/yhrh7ml.png ) error. the .h file: #include <stdint.h> #include <arduino.h> #include "circbuff.cpp" #ifndef circbuff_h #define circbuff_h #define buff_length 128 /** * circular buffer class. * has preset maximum size of buff_length bytes * uses byte array of size buff_length store data. * has start flag , end flag show start , end of our virtual buffer inside of main array. * whenever write byte buffer, adds byte index of "endflag", , moves end flag along * when call readbyte(), removes first byte in our buffer (at index of "startflag"), moves start flag */ class circbuff { public: circbuff(); //constructs new circular buffer object uint16_t getlength(); //returns number of bytes inside of our circular buffer

Reading Twitter/Facebook information without Accounts via the iOS Social Framework -

is possible tweets/facebook posts using ios social framework without using facebook or twitter accounts? not possible query data without active account. can create new slrequest, set parameters valid fb access token still need associate request valid, accessible account. see example of possible request here for fb queries, can use fb sdk perform queries without active user login using access token generated facebook app, can explain more if needed.

oauth - Azure Graph API: authorize application on multiple tenants -

i trying create application browse contacts directory on exchange. have set , able request authorization app. can present modal view, enter login information, retrieve token, when try authorize app same account have created message: the client <my app id> , resource <my app uri> identify same application. if try authorize account, receive message instead: user account <an email> external identity provider <a url> not supported application <my app id> if try login on graph explorer console or on office 365 oauth sandbox , work fine second address, not first one. i confuse. feel have mess configuration option, don't understand one. regarding #1, please not pass app id of application resource querystring parameter when authenticating against tenant url. ran exact same problem. then ran webapp-multitenant-openidconnect-dotnet github , noted down sign-in url created , used following: var signinurl = string.format(

javascript - How to set different width of jquery slider -

iam using elastislide responsive carousel slider link i modification code, want 1 page show 2 slider different width i want slider 1 width : 100% , slider 2 width : 50% this code, confused :( index.html <head> <link rel="stylesheet" type="text/css" href="css/elastislide.css" /> <script src="js/modernizr.custom.17475.js"></script> </head> <body> <ul id="carousel"> <li><a href="#"><img width="150px" height="160px" src="images/small/1.jpg" alt="image01" /></a></li> <li><a href="#"><img width="150px" height="160px" src="images/small/2.jpg" alt="image02" /></a></li> <li><a href="#"><img width="150px" height="160px&

c++ - How to use std::mem_fn to call a method on all objects inside a vector? -

given vector such as: vector<something*> a; i want call function whoami() on every something object. want append return value ( string ) ostream objects inside vector. here's code: std::transform(a.begin(), a.end(), std::ostream_iterator<std::string>(outstream_), std::mem_fn(&something::whoami))); edit: bad, forgot reference. after adding missing & in argument mem_fn , your code works . however, why use transform here in first place? proper solution problem is for (auto s : a) outstream_ << s->whoami();

Android - Compare two list for equality irrespective of the order of items -

i need compare 2 list of objects irrespective of order example: list1 = { object1, object2, object3, object4 } list2 = { object4, object1, object2, object3 } compare(list1, list2) should return true. here simple example compare 2 lists in java, http://beginnersbook.com/2013/12/how-to-compare-two-arraylist-in-java/ how compare 2 different list object in java?

java - Dense and Sparse Run Time -

i trying make program finds shortest path in graph. example, make 100 vertices , 100 edges 100 vertices again , 500 edges , measure run time. my question how can understand whether dense or sparse? the density ratio of number of edges in graph number of edges in complete graph same vertex set. both of these graphs reasonably sparse, though first sparser. often density of graph used decide data structure use represent graph an adjacency matrix makes sense dense graphs enumerating outbound edges not common operation. edge lists make sense sparse graphs or enumerating outbound edges done frequently. it's trade-off though. adjacency graphs take more memory vertex count scales, getting list of edges between 2 vertices fast. scanning outbound edges slow. edge lists take less memory vertex count increases, looking edges between 2 vertices slower, enumerating outgoing edges fast.

ios - No valid 'aps-environment' entitlement string found for application on app store -

so have app called dripper put out month ago , update couple days ago. update added push notifications , few little tweaks. tested sandbox-apn using development profile , things worked great. switched things production-apn , pushed test-flight, again things worked perfectly. once put update on market , ran noticed wasn’t getting new push registrations on server. looked @ console logs device , found this: dec 4 17:55:15 ina-touch-it coffco[1210] : registering remote notifications dec 4 17:55:15 ina-touch-it springboard[52] : no valid 'aps-environment' entitlement string found application 'dripper': (null). notifications not delivered. dec 4 17:55:15 ina-touch-it coffco[1210] <warning>: failed register error : error domain=nscocoaerrordomain code=3000 "no valid 'aps-environment' entitlement string found application" userinfo=0x174270900 {nslocalizeddescription=no valid 'aps-environment' entitlement string found application

android - Timer not working intent error -

i'm making timer switches form 1 activity in 3 seconds. here code: new countdowntimer(3000, 1000) { imageview img = (imageview)findviewbyid(r.id.single_image); textview mtextfield = (textview)findviewbyid(r.id.textview1); public void ontick(long millisuntilfinished) { mtextfield.settext("seconds remaining: " + millisuntilfinished / 1000); img.setimageresource(resource); } public void onfinish() { intent intent = intent(this, gameactivity.class); intent.putextra("image", resource); intent.putextra("difficulty", difficulty); startactivity(intent); finish(); } }.start(); } it gets error @ initent intent = intent(this,gameactivity.class); its states following: the method intent(new countdowntimer(){}, class<gameactivity>) undefined type new countdowntimer(){} any idea why error? in case, th

How to prevent internet explorer from inserting a page break before multi page image -

i'm running ie11 on windows 8.1 , cant seem print following without inserting page break before image: <!doctype html> <html> <head> </head> <body> <p>text</p> <img src=".....\pic.gif" /> </body> </html> where pic.gif image height greater size of page trying print to. if print in in chrome, show "text" , below start printing image. ie11 insert page break thing on page 1 of printed document "text" followed ton of white space. if resize image small enough fit on 1 page doesn't insert page break, resizing image not option. - aware of page-break-before: avoid; css makes no difference - still inserts page break. is bug in ie or there other way force it? seems me problem have bitten many people in past haven't had luck finding others problem. can reproduce on many computers i'm sure not out of whack in regard. any appreciated, thanks. put <p> , <img&g

clone - copy an object without chainging the original one - java -

i'm doing tic-tac-toc game , have method returns possible moves current state. i'm trying recive object , copy it, change , enter array list. @override public arraylist<state> getallpossiblemoves(state current) { arraylist<state> moves = new arraylist<state>(); (int i=0; i<current.getstate().length; i++){ (int j=0; j<current.getstate().length; j++){ if (current.getstate(i, j) == '-'){ char[][] tmp1; tmp1 = current.getstate().clone(); tmp1[i][j] = 'o'; tictactoestate tmp2 = new tictactoestate(tmp1); tmp2.setstate(tmp1); moves.add(tmp2); //current.setstate(i, j, '-'); } } } return moves; } no matter try - change on tmp1 effects on "current". tryed clone() , copy constructor. mention class "state" abstract , "tictacticstate" extend

java - ClassCastException while using HFileOutputFormat2 -

i trying upload data file in hdfs hbase table using hfileoutputformat2 outputformat getting following exception, java.lang.exception: java.lang.classcastexception: org.apache.hadoop.hbase.client.put cannot cast org.apache.hadoop.hbase.cell @ org.apache.hadoop.mapred.localjobrunner$job.runtasks(localjobrunner.java:462) @ org.apache.hadoop.mapred.localjobrunner$job.run(localjobrunner.java:522) caused by: java.lang.classcastexception: org.apache.hadoop.hbase.client.put cannot cast org.apache.hadoop.hbase.cell @ org.apache.hadoop.hbase.mapreduce.hfileoutputformat2$1.write(hfileoutputformat2.java:148) @ org.apache.hadoop.mapred.maptask$newdirectoutputcollector.write(maptask.java:635) @ org.apache.hadoop.mapreduce.task.taskinputoutputcontextimpl.write(taskinputoutputcontextimpl.java:89) @ org.apache.hadoop.mapreduce.lib.map.wrappedmapper$context.write(wrappedmapper.java:112) @ com.xogito.ingestion.mr.hbase.cseventshbasemapper.map(cseventshbasemapper.java:90) @ com.xogito.ingestion.mr.

c++ - Why was the restriction on the comma operator being in a constant expression removed in C++11? -

recently when answering question realized comma operator allowed in constant expression in c++11 long expression surrounded () , example: int a[ (1, 2) ] ; pre c++11 forbidden use comma operator in constant expression, draft pre c++11 standard section 5.19 constant expressions says ( emphasis mine ): [...]in particular, except in sizeof expressions, functions, class objects, pointers, or references shall not used, , assignment, increment, decrement, function-call, or comma operators shall not used. why comma operator not allowed in constant expression pre c++11 , why restriction lifted? we can find answer in std-discussion group comma operator in constant-expression thread gabriel dos reis says: for c++11 proposed allow because restriction appeared arbitrary , reasons i've heard rationale ban appear unconvincing , specious me. and richard smith earlier in thread notes of uses of comma operator in constant expression in both c++

android - Will AsyncTask crash if I call it over 100 times in a loop? -

i getting list of files web service , using asynctask handle download of files. each task created in loop: for(int = 0; < arraysize; i++) { //omitted code except portion fires asynctask //download pdf downloadhandler dhpdf = new downloadhandler(cleanlink, filename, p1, downloadposters.this, "pdf"); dhpdf.startdownload(); //download png downloadhandler dhpng = new downloadhandler(cleanlink, filename, p1, downloadposters.this, "png"); dhpng.startdownload(); } the download class public class downloadhandler extends activity { private context mcontext; //file ====================== public string filename; private string remotepath; private file file; private string ext; //progress bar ============== private progressbar progressbar; private int progressstatus = 0; //private handler handler = new handler(); private textview mtextview; //progressdialog ============ progressdialog mprogress; private int mprogressdialog=0; public do

loops - Java program looping help! I need to restart the program via a y/n input -

okay made program need able restart program asking if user wants try again y/n? can't seem loop correctly. me! p.s sorry formatting. import java.util.*; import java.util.scanner; class tester {... ...} system.out.println("y/n?"); string playagain = in.nextline(); if (playagain == "y") play = true; else play = false; } } } try this: if ("y".equalsignorecase(playagain)) don't use == compare strings. compare reference values. want equals(): compares string contents.

graphics - Coreplot in swift: change starting value of axis to 1 -

i have graph , wan't x , 2 y start @ 1 not 0. ![enter image description here][1] this how setup plotspaces: //plotspace 1 var plotspace: cptxyplotspace = graph.defaultplotspace cptxyplotspace var xrange = plotspace.xrange.mutablecopy() cptmutableplotrange var yrange = plotspace.yrange.mutablecopy() cptmutableplotrange xrange.length = self.maxx yrange.length = maxpoids plotspace.xrange = xrange plotspace.yrange = yrange //plotspace2 (second y) var plotspace2: cptxyplotspace = cptxyplotspace() var xrange2 = plotspace2.xrange.mutablecopy() cptmutableplotrange var yrange2 = plotspace2.yrange.mutablecopy() cptmutableplotrange xrange2.length = self.maxx yrange2.length = maxeau plotspace2.xrange = xrange2 plotspace2.yrange = yrange2 graph.addplotspace(plotspace2) how can that? the location of plot range left end (on x-axis) or bottom end (on y-axis). give each range location of 1 (1) , adjust length max

python - Trouble calculating with large binomial coefficients -

intro. i'm trying plot hypergeometric distribution ipython. probability function of distribution contains 3 binomial coefficients. since values putting in coefficients large eg. 1e28, i've decided make own function calculate binomial coefficients use second order of stirling's approximation. as binomial coefficients big put in variable , multiply directly, decided calculate logarithms instead , added them each other. obtain final probability put result in exp function. probability of relatively "normal" size (its maximum @ 2.7e24), there should no more problems there... except there are. problem. the 'result' referred to, log of probability ended way bigger should values ranging -6.2e24 1.3e14. in comparison, log of mathematical maximum 56. another problem curve on plot jagged when zoomed in. looks fine when zoomed out. curve smooth, maximum @ mean of distribution: plot on entire domain. but when zoom in on mean of peak of probability

javascript - Is it possible to combine members of multiple types in a TypeScript annotation? -

it seems trying not possible, hope is. essentially, have 2 interfaces, , want annotate single function parameter combination of both of them. interface clientrequest { userid: number sessionkey: string } interface coords { lat: number long: number } and then, in function, want this: function(data: clientrequest&coords) { ... } so 'data' object contain of members both types. i saw referenced in (spec preview)[ https://github.com/microsoft/typescript/issues/805] , under "combining types' members", seems hasn't made in yet. if isn't possible, solution might this: interface clientrequest<t> { userid: number sessionkey: string data?: t } function(data: clientrequest<coords>) { ... } which work in case, although it's not dynamic like. able combine multiple (2+) types in annotation itself: function(data: typea&typeb&typec) { ... } i guess conventional solution defin

amazon web services - Upgrade EC2 instance (ubuntu) without losing IP -

i know can associate instance elastic ip. however, possible "reserve" or transfer on current public ip instance has can used when upgrade instance? the short answer no. way can guarantee specific ip instance via use of elastic ip. have have attached running instance, shut instance down size upgrade, re-attach elastic ip new instance.

xaml - Can I wrap the Content/text value of a RadioButton in WPF? -

i have xaml: <stackpanel orientation="horizontal"> <textblock x:name="keylwp" textwrapping="wrap" maxwidth="120">a letter or word or phrase </textblock> <stackpanel> <radiobutton x:name="rdbtncandidateval1" content="two wrongs don't make wright brothers grimm thingamabob dylan thomas jefferson airplane"> </radiobutton> ...where, long string assigned radiobutton's content, falls off edge of earth. how can wrap, if necessary, can textwrapping , maxwidth properties of textblock? or must pair textblock each radiobutton, eschewing radiobutton's content/text property? you have options, go make in radio button style template applies of them, or @ instance level quick; <radiobutton> <radiobutton.content> <textblock text="wrap content pretty pretty please" textwrapping="wrap"/> </radiobutto

Android Studio Gradle Sync add arguments -

i trying pass svn revision number our gradle based build machine. fine if use variables $svnrevision in build.gradle. , run command "gradlew.bat build -psvnrevision="1234". but android studio cannot sync , run build script, there way set customized arguments android studio sync gradle?

Find string like XXXX - XXXX - XXXX in a file using bash -

is there way find string xxxx-xxxx-xxxx (where xs numbers , letters) in file using bash? for example: have aaaaaaaa-aaa-aaa-xxxx-xxxx-xxxx string in text file , want extract xxxx-xxxx-xxxx (there 4 letters/numbers group rapresented xs). if not possible using bash, there other way this? thanks. grep -eo '\<[[:alnum:]]{4}-[[:alnum:]]{4}-[[:alnum:]]{4}\>' file -o outputs matched text use word boundary markers \< , \> prevent false matches "12345-1234-12345"

webgl - Android GL memory in heap -

when run "adb shell dumpsys meminfo " on nexus 5 running lollipop im seeing huge amount of memory getting used in private dirty pss of 'gl' app webview based app, not running webgl/opengl . after few minutes clicking around in app crash, on nexus 5 running lollipop, no log messages indicating happened. suspect oom error happening cause gl memory in heap im not sure why happening, , why other devices run app without problem. question why heap large on device , can empty heap space? the gl heap space gets 177116 , total pss 539058

xcode - Displaying the Day Of The Week From Date Picker -

i want store day of week string using datepicker in xcode using swift. import uikit class viewcontroller: uiviewcontroller { @iboutlet weak var mydatepicker: uidatepicker! @iboutlet weak var strweekday: uilabel! override func viewdidload() { super.viewdidload() // additional setup after loading view, typically nib. // set mode date mydatepicker.datepickermode = uidatepickermode.date // add target trigger update function change weekday when user changes date mydatepicker.addtarget(self, action: selector("triggerupdate:"), forcontrolevents: uicontrolevents.valuechanged) // weekday initial value self.strweekday.text = mydatepicker.date.weekdayname } override func didreceivememorywarning() { super.didreceivememorywarning() // dispose of resources can recreated. } @ibaction func triggerupdate(sender: anyobject) { self.strweekday.text = mydatepicker.date.

c# - Retrieving Fault types deep inside xml -

i connecting web-service , getting errors in form of soapexception. can contain different types of faults send down within detail property of soapexception. can contain more 1 faults. here 1 example of contained in soapexception instance detail.firstchild.outerxml. <someerrorfault xmlns=\"urn:somenamespace\" xsi:type=\"someerror\" xmlns:xsi=\"http://www.w3.org/2001/xmlschema-instance\"></someerrorfault> the innerexcpetion property null. inspect type of faults , take action on those. of-course can detail.firstchild.outerxml.contains("typeoffaultiamlookingfor") wondering if there better of retrieving information? you have understand data structure of soap fault. see link might help. http://msdn.microsoft.com/en-us/library/ms189538(v=sql.105).aspx

javascript - Why is getInitialState getting called again? -

i finding way react.js , having trouble figuring out why getinitialstate being called once more expect. trying write component shows value label , can switched edit value presenting input text, ways save or cancel edit operation. here's component: var react = require('react'); var reactproptypes = react.proptypes; var enter_key_code = 13; var textinput = react.createclass({ proptypes: { id: reactproptypes.string, classname: reactproptypes.string, placeholder: reactproptypes.string, onsave: reactproptypes.func.isrequired, initialvalue: reactproptypes.string }, getinitialstate: function() { return { value: this.props.initialvalue, isediting: false }; }, render: function() { var inputfield = (<div> <input classname={this.props.classname} id={this.props.id} placeholder={this.props.placeholder} onblur={this._save} onchange={this._onchange}

Aviary crop presets not working on iOS -

Image
i'm trying force users crop photo square aviary. described in aviary documentation here , possible disable custom crops , specify presets manually. attempting following: [afphotoeditorcustomization setcroptooloriginalenabled:no]; [afphotoeditorcustomization setcroptoolcustomenabled:no]; nsdictionary *size = [[nsdictionary alloc] initwithobjectsandkeys: @"kafcroppresetname",@"square", @"kafcroppresetwidth",@"1.0f", @"kafcroppresetheight",@"1.0f", nil]; [afphotoeditorcustomization setcroptoolpresets:[[nsarray alloc] initwithobjects:size, nil]]; but not work. results 0 cropping options: you should use below code: [afphotoeditorcustomization setcroptooloriginalenabled:no]; [afphotoeditorcustomization setcroptoolcustomenabled:no]; nsdictionary * square = @{kafcroppresetname: @"square", kafcroppresethei

oop - PHP - PDO placeholder with table.column format -

i created function preparevalue() takes array formatted $column => $value , , replaces each value ? whilst preserving copy of original array binding , executing later pdo. this works fine queries following $a = [ 'company' => 'apple' 'item' => 'ipad' ]; preparevalue($a); $sql = 'where company = ? , item = ?'; prepare($sql); execute($a); however, required write queries array value table.column type value, pdo doesnt seem being substituted placeholder. $a = [ 'companyid' => 'itemid'; ] preparevalue($a); $sql = 'where companyid = ?'; prepare($sql); execute($a); this query not work, if replace ? manually itemid following where companyid = itemid the query works fine. what best in scenario this? perhaps there way prepare table.column type values?

encryption - JavaScript ascii to utf-8 conversion problems with negatives -

i'm working on decrypting server side information have encryption working in different language , therefore know decryption should be? why don't negative numbers come out correct when positives do? run example: output format: str pos s[t] str.charat(str, pos + 1) str.charcodeat(pos + 1) decryption according gml: input: str: ��� key: 472 -------------- str: ��� pos: 0 st: 195 char: ⮫ value: -94 str: ��� pos: 1 st: 140 char: value: -18 str: ��� pos: 2 st: 136 char: value: -21 server side equivalent (js): input: str: ��� key: 472 --------------- str: ��� pos: 0 st: 195 char: � value: 65533 str: ��� pos: 1 st: 140 char: � value: 65533 str: ��� pos: 2 st: 136 char: value: nan how information gets input: data passed server.js -> client.js header taken , put through switch statment, rest of datapacket parsed using: var parser = require('binary-parser').parser; login: new parser().skip(1) .string("command", stringoptions)

10 ,most frequent words in a string Python -

i need display 10 frequent words in text file, frequent least number of times has been used. can't use dictionary or counter function. far have this: import urllib cnt = 0 i=0 txtfile = urllib.urlopen("http://textfiles.com/etext/fiction/alice30.txt") uniques = [] line in txtfile: words = line.split() word in words: if word not in uniques: uniques.append(word) word in words: while i<len(uniques): i+=1 if word in uniques: cnt += 1 print cnt now think should every word in array 'uniques' , see how many times repeated in file , add array counts instance of each word. stuck. don't know how proceed. any appreciated. thank you you're on right track. note algorithm quite slow because each unique word, iterates on of words. faster approach without hashing involve building trie . # following assumes have alice30.txt on disk. # start splitting file lowercase words. words = open('

lucene - Ravendb retrieve all documents in collection for reporting -

i need retrieve documents collection dump excel file. using seems work var lucenequery = session.advanced.lucenequery<test.reduceresult>("test/bytestdata"); var enumerator = session.advanced.stream(lucenequery); var obj = new list<test.reduceresult>(); while (enumerator.movenext()) { obj.add(enumerator.current.document); } this gives me results in index. instead of index want retrieve documents in collection (as index not contain information stored in document). how can done? change query be: var lucenequery = session.advanced.lucenequery<test.reduceresult>("raven/documentsbyentityname") .whereequals("tag", "customers"); this give customers.

python - Matplotlib axes autoscale does not work with after twinx() -

i have found can not axes autoscale work on 1st axes after creating second axes using twinx. expected? import numpy np import matplotlib.pyplot plt x = np.arange(0, 10, 0.1) y1 = 0.05 * x**2 y2 = -1 *y1 fig, axl = plt.subplots() # make left axes axr = axl.twinx() # make left axes axl.plot(x, y1, 'g-') # plot on left axl.grid() axl.autoscale(enable=true, axis=u'both', tight=false) plt.show() # stuff later plot on axr when run above code autoscales in y-direction correctly on left axes (0 5) changes x-axis scale +/- 0.06 instead of correct 0 10. however, once axr no longer blank , plotted on axr behaves expect. this example first came across issue in more complicated pyqt4 gui allows user create multiple subplots & left/right combinations. since user 1 manually controlling plot creation order possible above situation present itself. is there way autoscale work blank twinx right axes. or xlimit going have manually set? fyi, using python 3.4 part of

c++ - Is it possible to distinguish a `const` variable from a non-`const` one and from a `const&` reference? -

suppose wanted make own reference ("smart pointer") type guaranteed refer immutable data, rather merely immutably-viewed data. in other words, data can't mutated anyone , opposed not through particular reference. not easy, because c++ considers const things subcase of mutable-access things, , & references implicitly convert const & , likewise * const * . let's call type: template<typename t> class immref { ... }; one straightforward thing can declare: template<typename t> struct imm { const t value; }; and allow creating immref s out of imm s, or other immref s. here variable declared const , it's not possible make mutable references it, , in fact immutable. (unless internally uses mutable , since there's nothing can that, let's ignore it.) that works, greater flexibility, wider applicability, , compatibility other code doesn't know our imm type, better if create immref s any const -declared variable. it

java - READ COMMITTED lock wait timeout exceeded -

i have 1 question regarding transaction isolation level , locking in mysql. i have 1 query keeps getting lock timeout error: java.sql.sqlexception: lock wait timeout exceeded; try restarting transaction the queries try delete records specific date_id. btw, date_id indexed well. of times, there no records match, i.e. delete nothing. after investigation, found may caused culprit long-running query, range select on same table. however, confused me both transaction run @ isolation level of "read committed". have no clue why lock needed , why timeout (especially consider there no matching record delete) thank in advance! the transaction isolation "read committed" contract: database promises read committed data , keep not-yet-committed data out of transaction. lock timeout error runtime-error: database tries update data cannot find moment (see "innodb_lock_wait_timeout" mentioned here in mysql reference manual). if there no data delete, d

java - NullPointerException at createBitmap(). Using an Adapter to inflate a Bitmap into a ListView's rows -

i'm getting nullpointerexception @ createbitmap. on research, i've come across people suggesting it's because of low memory. i'd find out if there's in code changed make work. reference, i'll post xml file of row give idea of how should fit in. here's function gives error (i'm trying make image circular, function): public bitmap getcroppedbitmap(bitmap bitmap, view view) { bitmap output; try { view.builddrawingcache(true); output = bitmap.createbitmap(bitmap.getwidth(), bitmap.getheight(), //error here bitmap.config.argb_8888); }finally { view.setdrawingcacheenabled(false); } final rect rect = new rect(0, 0, bitmap.getwidth(), bitmap.getheight()); canvas canvas = new canvas(output); final paint paint = new paint(); paint.setantialias(true); int halfwidth = bitmap.getwidth()/2; int halfheight = bitmap.getheight()/2; canvas.drawcircle(halfwidth, halfheight, mat

file watcher - Continuously reading java WatchEvents -

i'm trying synchronize 2 folders , sub directories between client , server. have modified version of this class i've posted below. in client class, create watchdir object , call processevents() method in infinite loop. method returns mytuple object (a struct containing event type , path object) if event registered , null if not. problem seems work first event happen in directory (i.e. if add file watched folder, watchdir object.processevents() returns 1 tuple entry_create event , never returns tuple other file additions/deletions/modifications happen after). i'd processevents continuously called (hence infinite while) returning tuple each time event occurs. help! my modified watchdir: import static java.nio.file.standardwatcheventkinds.*; import static java.nio.file.linkoption.*; import java.nio.file.attribute.*; import java.io.*; import java.util.*; import java.util.concurrent.timeunit; public class watchdir { private final watchservice watcher; private f

java - Failing to produce unicode strings dynamically -

in ui of application using unicode strings ranging "\u0900" "\u0959" unicode equivalent of devanagari characters. trying generate these unicode strings dynamically set on buttons of ui. code: for(int i=900; i<=959 ; i++){ string buttontext = "\\"+"u"+integer.tostring(i); this.add(new createbutton(buttontext)); //createbutton extends jbutton. } it fails horribly, strings displayed , \u900 \u959 instead of devanagari characters themsleves. how solve issue? you can't create unicode escape sequence ( "\u...." recognized compiler). instead, loop through character values , create string string#valueof : for (char = 0x900; <= 0x959; i++) { string buttontext = string.valueof(i); // ... } note i'm prefixing numbers 0x , means numbers hexadecimal . because unicode escape sequences composed of 4 hexadecimal digits : unicodeescape: \ unicodemarker hexdigit hexdigit hexdigit

Unable to choose appropriate method using Java Generics -

this program doesn't wanted. prints "sad" twice, whereas hoping print "happy" , "sad". public class woof { public static class arf<t> { t yap; public arf(t yap) { this.yap = yap; } public string woof() { /* * should select doyapstuff() based on whether t * happens integer, or else. */ return doyapstuff(yap); } /* special case implementation of doyapstuff() t integer */ public string doyapstuff(integer x) { return "happy"; } /* default implementation of doyapstuff() t else */ public string doyapstuff(t x) { return "sad"; } } public static void main(string[] args) { integer = 5; arf<integer> arf1 = new arf<integer>(i); system.out.println(arf1.woof()); // should print "happy"