Posts

Showing posts from March, 2013

c++ - Does the keyword "shared" prevent race conditions? -

i'm unclear "shared" in openmp. see spec states shared "declares 1 or more list items shared tasks..." seems unclear me. for example, if have following code: #pragma omp parallel shared(num1) for(i=0; i<m; i++) { for(j=0; j < n; j++) { if(myfunc(i,j) < 0) { num1 += 256*u(i,j); } } } will stop race conditions num1 , give accurate result @ end of loop? if not, do? will stop race conditions? no, won't : it programmer's responsibility ensure multiple threads access shared variables (such via critical sections) shared section make same variable visible multiple threads. you can use critical sections or atomic access syncronization, in this case you'd better use reduction clause: #pragma omp parallel reduction(+:num1)

Problems with CamelCase and underscore Rails 3 -

i have 2 models has many through association between them below: tipodocumento < activerecord::base has_many :dependencias has_many :tiporequisitos, :through => :dependencias ... end tiporequisito < activerecord::base has_many :dependencias has_many :tipodocumentos, :through => :dependencias ... end dependencia < activerecord::base belongs_to: tipodocumento belongs_to: tiporequisito ... end the id's attributes join model dependencia tipodocumento_id , tiporequisito_id. now, when try in rails console: x = tipodocumento.find(1) x.tiporequisitos i error: activerecord::statementinvalid: sqlite3::sqlexception: no such column: dependencia.tipo_documento_id: select "tipo_requisitos".* "tipo_requisitos" inner join "dependencia" on "tipo_requisitos"."id" = "dependencia"."tiporequisito_id" "dependencia"."tipo_documento_id" = 1 also i

django - mysql server doesn't run anymore -

i installed mysql on os x mountain lion , worked fine while. i run using command: /usr/local/mysql/bin/mysql -uroot then, installed django , when execute command above, get: error 2002 (hy000): can't connect local mysql server through socket '/tmp/mysql.sock' (2) anyone have precise solution this? it's happening becaouse mysql hasn't been started, have manually. so, go system preferences > mysql , press button: start server. done, works!

javascript - Using jQuery to search through element attribute values -

i'm trying make filter on screen, hiding doesn't meet requirements. this i've come far. im not sure doing wrong jquery : jquery('#searchbox').on('keyup change', function() { var search = $('#searchbox').val(); //for each h4 $('h4').each(function(){ var h4id = $(this).attr('id'); if ($(h4id).contains(search)) $(this).show(); else $(this).hide }); html : <input type="search" name="search" id="searchbox"/> <h4 id="adminstrator">administrator</h4> <h4 id="john,smith">john smith</h4> <h4 id="jane,smith">jane smith</h4> (i'm using jquery 1.9.1) (so, if start typing smith, "administrator" h4 should disappear. .contains not give text content of selector. search elements inside selector. try approach .. can lot more optimized

javascript - video.js currentTime() incorrect until timeupdate event fires -

i've noticed small inconsistency i'm hoping verify either quirk of html5, or specific video.js . it seems if call video.js' currenttime() function whilst providing new time, further calls currenttime() (to current time) not return correct time (it return previous time), until timeupdate event fires. after timeupdate event, currenttime() return correct time. for example, assuming video hasn't started playing yet, video.js has loaded, along video meta etc: videoplayer.addevent('timeupdate', function() { console.log('event callback: ' + player.currenttime); }); console.log('original time: ' + player.currenttime); player.currenttime(100); console.log('new time: ' + player.currenttime); the output expecting like: original time: 0 new time: 100 event callback: 100 however i've receiving is: original time: 0 new time: 0 event callback: 100 any insight fantastic! edit: can reproduce in chrome , s

Perl Archive::Zip creates unnecessary folders -

assuming have following array of file names wish zip my @files = ("c:\windows\perl\test1.txt", "c:\windows\perl\test2.txt", "c:\windows\perl\test3.txt"); if $obj = archive::zip->new(); foreach (@files) { $obj->addfile($_); } $obj->writetofilenamed("zippedfolders.zip"); when open zippedfolders.zip see contains subfolders, namely windows , perl , latter contains test1 , test2 , , test3 . reason, folders getting zipped up. how can make files zipped , not have click windows perl folders access zipped files? as have see, if use addfile add disk file archive, archive::zip adds archive member same path file had originally. if want stored different can pass second parameter used name , path of archive member created. for purposes suggest use core file::basename module remove path filename , pass basename second parameter. the code below demonstrates. something else need aware of can't use single ba

ssrs 2008 - Error: Subreport could not be shown. Sub Report works in Preview - but not when deployed -

i have main report runs multiple sub-reports. 1 of sub reports runs fine in preview, when deploy report , run browser, get: error: subreport not shown. i've done research , still not sure issue is. i've tried in different browsers, data sources both main report , sub report use same shared data sources. , main report , parameters seem pass fine (since works in preview, assuming). the error doesn't tell me - has else had issue? or ideas how debug? many thanks! issue resolved. needed deploy subreport well, not build.

massive memory leak in ios UIWebView -

looking mem leaks elsewhere in our system, created 20 mb web page meta refresh tag. idea move lot data through our datapath code confirm mem stability. <html> <meta http-equiv="refresh" content="1"> <body> <div style="border: 1px solid red"> content loading </div><!-- 20mb worth of comments --> </body> </html> what found uiwebview displaying meta refresh page leaks memory very, fast. app memory hits 300mb in 2 minutes , gets shot on low mem warning, when our code not in play. i have stopped refresh loading , tried dealloc webview. i have tried loadurl:"about:blank", loadhtml:"", javascript document close. i tried writing recursive removefromsuperview , removefromparentviewcontroller, reading private scrollview in webview memory problem, memory never freed. can't seem find reliable way close, dealloc webview when done it. we have lived slow rate of webview leaking q

osx - Objective c: How to know the progress of formatting USB drive in using NSTask -

i use nstask execute format usb drive ntfs fat32. works well, know progress when starts format. here code: nstask *task = [nstask new]; [task setlaunchpath:@"/usr/bin/env"]; [task setarguments:[nsarray arraywithobjects:@"diskutil", @"erasevolume", @"ms-dos" ,name ,path,nil]]; nspipe *pipe = [nspipe pipe]; [task setstandardoutput:pipe]; [task launch]; [task waituntilexit]; how add progress keep track of formatting.(like percentage done...) !! the task wrap nstask needs first providing progress updates. there, can watch stderr , stdout. if there updates them, can interpret , post notification main thread. use notification make gui updates.

Non-PCL dependencies w/ MvvmCross -

our application has several dependencies not available pcl libraries (e.g. restsharp, websocket4net, reactive extensions), available each platform plan target. what's best approach handling scenario in mvvmcross? simplest? there various ways approach this. if problem large, can abandon pcl approach, , use multiple platforms specific class libraries. these libraries can reference mvvmcross pcls , platform specific versions of restsharp, etc. discussions on pro's , con's of see - what advantage of using portable class libraries instead of using "add link"? in general, take file-linking approach if i've got include large legacy library (e.g. 1 customer had large business logic library talked 3 separate wcf services...) some of libraries mention may have pcl ports and/or alternatives - e.g. reactive extensions has official pcl port - see http://blogs.msdn.com/b/rxteam/archive/2013/02/06/rx-2-1-is-here.aspx for simple rest calls, we've

function - Recursive numeric triangle in python -

i'm trying create triangle following: 1 2 3 4 5 6 2 3 4 5 6 3 4 5 6 4 5 6 5 6 6 without using while, in, lists, etc. "if-else" cases , recursive functions. i've learned how asterisk triangle. def triangle(i, t=0): if == 0: return ' ' else: print '*' * return triangle( - 1, t + 1 ) triangle(6) it has same idea want apply exercise, don't know how code changing term term , print them right one. here solution. note there neither range nor join , implies for or list in [1]: def tri(size, row = 0, col = 0): ...: if row < size: ...: num = row + col + 1 ...: if num == size + 1: ...: print '\n', ...: tri(size, row + 1, 0) ...: if num <= size: ...: print num, '', ...: tri(size, row, col + 1) ...: in [2]: tri(6) 1 2 3 4 5 6 2 3 4 5 6 3 4 5 6 4 5 6 5 6 6 if range

Unit tests of a C# App crashes when the execution reaches C++ layer -

we have windows store app structured like, mainapp(c#, windows store) --> servicelayer(c# class library) --> maincode(c++, windows runtime component). there no problem while running application in debug mode. when try run unit test project refers mainapp, crashes when reaches c++ layer. , intermittent too. accessviolation, other times argumentexception or no exception @ all. interestingly, unit test works when directly call servicelayer instead of going through mainapp. what missing?

windows - blue screen error: DRIVER_RETURNED_HOLDING_CANCEL_LOCK -

i write driver in windows 7. , use pedding irp send event application driver. key code like: pirp peddingirp; ... void ptdrivercancelirp(in pdevice_object deviceobject, in pirp irp ) { unreferenced_parameter(deviceobject); kdprint(( "[wenz] user message cancel irp....\n" )); if ( irp == peddingirp) peddingirp = null; irp->iostatus.status = status_cancelled; irp->iostatus.information = 0; iocompleterequest(irp,io_no_increment); } ... ntstatus devicecontrol( pdevice_object deviceobject, pirp irp ) { ... switch ( irpsp->parameters.deviceiocontrol.iocontrolcode ) { ... case ioctl_notify_state: irp->iostatus.information = 0; irp->iostatus.status = status_pending; iomarkirppending(irp); peddingirp = irp; iosetcancelroutine(irp, ptdrivercancelirp); return status_pending; ... } ... } it works when event notify application. when uninstall driver, bl

php - Bringing over Page Information in Wordpress -

so, i've created pretty nice landing pages client, , think they're pretty done. client, not tech-savvy person on planet, theyve asked make pages editable them (so don't have dig through code). my landing pages simple, structed this [content] testimonial [content] testimonial [content] testimonial so, want do, create 6 pages - 3 testimonials, , 3 content - , have information pulled separate page in php pageid. for example, first content section - have seperate page called "content top" information on it, can edited client. want take information, use little php, , display on content section of main landing page. if unclear, please let me know - know way this. overall, need take information 1 page, , put page. thanks

php - htaccess rewrite on localhost -

i have problem .htaccess file, problem have site on localhost , path is: localhost/site/sitename/html/login.php?ref=company , after uploading server be: www.site-name.com/login.php?ref=asdas what needd rewrite ref looks (in both cases): path_to_site/company/login.php company $_get['ref'] ex. have url: localhost/site/sitename/html/login.php?ref=cola and want have this: localhost/site/sitename/html/cola/login.php how it? try if works you: rewritecond %{http_host} ^(.*)/$login.php$ rewriterule ^(.*)$ http://www.site-name.com$1 [r=301,l] i hope understood want correctly. check if have enabled , configured on server correctly. @ http://httpd.apache.org/docs/current/mod/mod_rewrite.html more information if youre using apache.

python - Extract small Arial text from screenshot -

i need automate extract of info flash app. idea take screenshot , text there, using pytesser isn't working (it returns nothing, don't know if it's because i'm doing wrong or because it's small). the text black arial size 8 text in white background, no noise, , text pretty simple (mostly things "9:32" or "cristiano ronaldo"). how face problem in simple way , using python? just in case it's needed, i'm using windows xp , python 2.7 thank in advance.

C# winform change selected tabcontrol image -

i have winform application written in c#. had imagelist in winform , have tabcontrol , each of tab assign image icon tab changing imageindex. however have 1 image each tab , want them change image selected tab (like highlighted image active one). have idea add images imagelist (both active , inactive images) , change imageindex of selected tab. not sure how in practical. here current codes can come with: inside selectedindexchange event, have function: foreach (tabpage tab in tabcontrol1) { if (tab.index == tabcontrol1.selectedindex) { <---how index? tab.imageindex = tab.index + tabcontrol1.tabcount; } else { tab.imageindex = tab.index; } } i came solution for (int i=0; i<tabcontrol1.tabpages.count; i++) { if (tabcontrol1.tabpages[i] == tabcontrol1.selectedtab) { tabcontrol1.tabpages[i].imageindex = + tabcontrol1.tabpages.count; } else {

symfony - Unable to extract translation id for form label with JMS Translation Bundle -

i'm using jms translation bundle extract translations. works, when try extract translation messages form form builder recieve following message: [jms\translationbundle\exception\runtimeexception] unable extract translation id form label non-string values, got "phpparser_node_expr_methodcall" in /srv/local.project.com/app/../src/project/mybundlebundle/form/type/emailtype .php on line 30. please refactor code pass string, or add "/** @ignore */". the code use followed: public function __construct($translator) { //translation service passed controller $this->trans = $translator; } public function buildform(formbuilderinterface $builder, array $options) { $builder->add('email', 'repeated', array( 'type' => 'email', 'first_name' => 'email', 'second_name' => 'email-repeat',

shell - not found error when insert #!/bin/sh -

i started learning linux shell scripting, when writing script got error, ./my_script: 4: read: illegal option -n ./my_script: 5: ./my_script: [[: not found i found out because #!/bin/sh line, can still run script without line won't execute codes such /n #!/bin/sh # shell installer gurb customizer. naveen gamage. os=$(lsb_release -si) arch=$(uname -m | sed 's/x86_//;s/i[3-6]86/32/') ver=$(lsb_release -sr) grabninstall() { sudo add-apt-repository ppa:danielrichter2007/grub-customizer sudo apt-get update sudo apt-get install grub-customizer } echo "installer grub customizer\n" echo "gurb customizer" echo "a tool editing , configuring boot menu (grub2/burg).\n" read -p "do want install grub customizer $os ${ver} [$arch] ? (y/n) " -n 1 if [[ $reply =~ ^[yy]$ ]] echo "the installer downloading , installing grub customizer!"; echo "this action may require password.\n"; grabnins

c# - Easy way to create MessageBox with "custom button" -

this question has answer here: custom button captions in .net messagebox? 8 answers i've winform application, , trying make ergonomic possible, respect lot microsoft guidelines. we have "deletion confirmation" implement, , according guidelines , found accross web, more adequate buttons be: delete , cancel ( http://msdn.microsoft.com/en-us/library/windows/desktop/aa511268.aspx#commitbuttons ) but since use messageboxbuttons specify buttons have display, can't see how can except implementing ourself confirmation dialog. i don't find logical microsoft encourage in 1 side use of "action" text on button, , other side doesn't give tools compliant, think i'm missing something? please note don't need more results possibility currently, delete option same ok me, want have differents texts. so: there way specify butt

Twitter4j: java.lang.IllegalStateException: Access token already available -

i using twitter4j creating twitter client jsp , servets. when requesting access token getting following exception. java.lang.illegalstateexception: access token available. then searched on stackoverflow. got post twitter4j access token available where in solution has written i setting access token hard coded configuration builder. but haven't mentioned how has fixed it.i not hardcoding accesstoken here code stringbuffer callbackurl = request.getrequesturl(); system.out.println("callbackurl is" + callbackurl); int index = callbackurl.lastindexof("/"); callbackurl.replace(index, callbackurl.length(), "").append("/callback"); configurationbuilder cb = new configurationbuilder(); cb.setdebugenabled(true) .setoauthconsumerkey(getservletcontext().getinitparameter("consumerkey")) .setoauthconsumersecret(getservletcontext().getinitparameter("consumersecret")); twitterfactory tf = new twitterfac

Reading database table into a .NET object of different structure -

Image
i have inflation rates stored in database following structure: when reading above data, need initialize business objects different structure dynamically , fill them database data. if database above, need create 2 objects: "uk inflation forecast" , "germany inflation forecast". in case, both objects have 6 properties: countryname (as string) , 5 inflation values (as double). how can create object classes without knowing number of properties needed , how fill these data? i create class of following structur: public class inflationclass { public inflationclass() { inflationvalues = new dictionary<int, double>(); } public string country { get; set; } public dictionary<int, double> inflationvalues { get; private set; } } and load data so int sampleyear = 2016; double samplevalue = 123456789.01; var inflation = new inflationclass(); if(!inflation.inflationvalues.containskey(sampleyear )) { inflati

android - Google market support null device -

i have publish app in google maret ,but show support 0 device.my manifest file : android:targetsdkversion="15"/> i use android 4.1 compile ,thanks answer. make sure define android:minsdkversion applicable application. if application should show in version/density devices remove compatible-screen , support-screen code menifest file

Redis: How to delete all keys older than 3 months -

i want flush out keys older 3 months. these keys not set expire date. or if not possible, can delete maybe oldest 1000 keys? are now using expire? if so, loop through keys if no ttl set add one. python example: for key in redis.keys('*'): if redis.ttl(key) == -1: redis.expire(key, 60 * 60 * 24 * 7) # clear them out in week

c# - xml serializing a list of base class -

consider below class structure [xmlinclude(typeof(derivedclass))] public class baseclass { public string mem1; public string mem2; } public class derivedclass : list<baseclass> { public string mem3; public string mem4; } class program { static void main(string[] args) { derivedclass obj = new derivedclass(); obj.mem3 = "test3"; obj.mem4 = "test4"; baseclass base11 = new baseclass(); base11.mem1 = "test1"; base11.mem2 = "test2"; obj.add(base11); xelement .parse(xmlserializerutil.getxmlfromobject(obj)) .save(@"c:\new_settings1.xml"); } } the code getxmlfromobject given below public static string getxmlfromobject(object instance) { string retval = string.empty; if (instance != null) { xmlserializer xmlserializer = new xmlserializer(instance.gettype()); using (mem

sorting - Primefaces datatable sort order -

i using primefaces' datatable component display list of classes 'student' : class student { string firstname string lastname .... } i populate list form native query. datatable component follows : <p:datatable id="studentlist" var="student" rowindexvar="rowindex" value="#{studentbean.studentlist}" rowkey="#{student.firstname}" widgetvar="slist" sortby="#{student.firstname}" sortorder="ascending"> and have button refresh data in table. problem is, when refresh data, sorting order lost. how can retain sorting order? the problem sorting applied when click sorting icon. work around can call methods in datatable component to, first know last "sorted column" , can use primefaces datatable sorting feature. force datatable sorting whenever want: /** * code first find current order , apply sorting process data. * i

android - Running the same app on several devices simultaneously -

i want run 1 app on 2 phones, , display these apps show onto same tablet. possible? so example show phone #1 shows in bottom left corner of tablet screen , show phone #2 shows in bottom right corner. all related answers appreciated! what want mirroring both phones screens, know can pc, not sure tablets. can read more here but experience, mirroring not working good- in of solution have root devices first, , it's bit slow , not smooth. i recommend put 2 phones next each other , make video tablet.

java - Different JSON array response -

i have problems parsing 2 different json responses. 1: json response restful api: { "gear": [ { "idgear": "1", "name": "nosilec za kolesa", "year": "2005", "price": "777.0" }, { "idgear": "2", "name": "stresni nosilci", "year": "1983", "price": "40.0" } ] } 2: response testing client. added values list , used gson.tojson testing output. [ { "idgear": "1", "name": "lala", "year": 2000, "price": 15.0 }, { "idgear": "2", "name": "lala2", "year": 2000, "price": 125.0 } ] they both valid, second 1 deserialize object this: type listtype = new typetoken<list<gear>>() {}.gettype()

Youtube javascript API and Android application in webview -

i use youtube javascript api autoplay youtube video in android application. (version 2.2 , later) in application load html in webview. use same code in ios application. ios work. when load video, video playing automatically. with android when load html, code loadded, video start launch it's never read. when desable autoplay , user click on video, work ! , have enable : android:hardwareaccelerated="true" <!doctype html> <html> <body> <div id="player"></div> <script> var tag = document.createelement('script'); tag.src = "https://www.youtube.com/iframe_api"; var firstscripttag = document.getelementsbytagname('script')[0]; firstscripttag.parentnode.insertbefore(tag, firstscripttag); var player; function onyoutubeiframeapiready() { player = new yt.player('player', { height: '150', width: '300',

r - Save heatmap.2 in variable and plot again -

i use heatmap.2 gplots make heatmap: library(gplots) # fake data m = matrix(c(0,1,2,3), nrow=2, ncol=2) # make heatmap hm = heatmap.2(m) when 'heatmap.2' directly plot can output device. how can make plot again variable 'hm'? toy example, in real life have function generates , returns heatmap plot later. there several alternatives, although none of them particularly elegant. depends on if variables used function available in plotting environment. heatmap.2 doesn't return proper "heatmap" object, although contains necessary information plotting graphics again. see str(hm) inspect object. if variables available in environment, re-evaluate original plotting call: library(gplots) # fake data (adjusted bit) set.seed(1) m = matrix(rnorm(100), nrow=10, ncol=10) # make heatmap hm = heatmap.2(m, col=rainbow(4)) # below fails if variables not available in global environment eval(hm$call) i assume won't case though, mentioned calling plo

javascript - element.next() not working in IE8 -

i have 1 function in below few lines: if(ele.next()) { if(ele.next().classname == 'errmark') ele.next().remove(); } now working fine browsers except 1 i.e. ie8 , getting error below: webpage error details user agent: mozilla/4.0 (compatible; msie 8.0; windows nt 6.1; wow64; trident/4.0; slcc2; .net clr 2.0.50727; .net clr 3.5.30729; .net clr 3.0.30729; media center pc 6.0; cmdtdf; bri/1) timestamp: xxx message: object doesn't support property or method line: 166 char: 5 code: 0 uri: xxxxxxxxxxxxxxxx somebody please me.. thanks.. i assume using jquery ( ele.next() jquery syntax); ele.next() give jquery object/element, not have .classname property. .classname property available in native javascript dom object, can access e.g. this: ele.next()[0] you have 2 options here: 1 use javascript mixed jquery (not recommended): if (ele.next()[0].classname === 'errmark') ele.next().remove();

jquery - Adding a horizontal line in table using javascript -

i want draw horizontal thick line separating rows in report based on 1 column values. i.e., if previous , current value same want draw horizontal line. wrote jquery coding working fine in mozilla not in ie . mistake did make? var = 1; $(".calbody tr td:nth-child(8) a").each(function() { var foo = "<hr width=2000% ;'>"; if (a === 1) { $(this).parents("tr:first").before(foo); } if (a != 1) { var b = $(this).text(); if (a != b) { $(this).parents("tr:first").before(foo); } } = $(this).text(); }); try this var foo = "<hr width='2000%'>";

node.js - Node JS Emit method - set output headers to Zlib -

i trying compress output node js application. able compress text string on server side. header sent says html/plain text so browser not able decompress i using node v0.6.18 my code follows: var http = require('http'), url = require('url'), fs = require('fs'), amqp = require('amqp'), redis = require('redis'), zlib = require('zlib'), sys = require(process.binding('natives').util ? 'util' : 'sys'); var exchangename= 'conferencetest'; send404 = function(res) { res.writehead(404); res.write('404'); res.end(); }; server = http.createserver(function(req, res) { var path = url.parse(req.url).pathname; switch (path) { case '/': fs.readfile(__dirname + "/index.html", function(err, data) { if (err) { return send404(res); } else { res.writehead(200

jquery - How to add alt to the image src tag in javascript execCommand methode? -

'insert_img': { "text": "inserimage", "icon":"icon icon-picture", "tooltip": "insertimage", "commandname":null, "custom": function(){ var imgsrc = prompt('enter image location', ''); if (imgsrc != null) { document.execcommand('insertimage', false, imgsrc); } } }, i have code this, want give alt image, how can achieve this? when take source wan see <img src="smiley.gif" alt="smiley face"> this, possible? please me. it seems can't execcommand directly documentation of commands an other one . you can still in jquery, after adding image (seems bit hackish, know, don't think can better) : $('img[src="smiley.gif"]').attr('alt','smiley face');

java - Setting default LAF's JTextField dimensions -

is possible override laf's default dimensions of jtextfield uidefaults? maybe padding, or insets, not raw dimension. dimension accounts things number of characters field supposed show, , font.

java-spring-mvc Form values not getting printed on POST -

i new spring mvc created project using springtemplateproject , used hibernate in that. i created form , on post values getting inserted in database problem not able display values on post. here code. //controller package com.projects.data; import java.util.locale; import org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.controller; import org.springframework.ui.model; import org.springframework.ui.modelmap; import org.springframework.validation.bindingresult; import org.springframework.web.bind.annotation.modelattribute; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.requestmethod; import com.projects.data.*; @controller public class homecontroller { private static final logger logger = loggerfactory.getlogger(homecontroller.class); @autowired serviceimpl service; @requestmapping(value = "/", m

How to hide the outer parents in Jquery -

below code, goal when user click <a> in 'child_2', want hide $(this) class="parent". how can achieve this? <div class="parent"> <div class="child_1"> </div> <div class="child_2"> <div> <ul> <li><a href="#">click me</a></li> <li></li> <li></li> <li></li> </ul> </div> </div> <div class="child_3"> </div> </div> use closest $(this).closest('.parent').hide(); for each element in set, first element matches selector testing element , traversing through ancestors in dom tree.

c++ - Can't delete temporary object -

i'm resizing , array of objects. made temp object when don't delete valgrind shows memory leaks , error. deleting causes segfault. wondering valgrind complaining about... void obj::resize() { obj *temp = new obj[size * 2]; //<-- line 92 (int = 0; < size; i++) temp[i] = objarray[i]; delete [] objarray; objarray = temp; size *= 2; //delete temp; //<-- causes segfault //delete [] temp; // segfaults, tried them both in case :\ } here's valgrind report: ==9292== heap summary: ==9292== in use @ exit: 21,484 bytes in 799 blocks ==9292== total heap usage: 3,528 allocs, 2,729 frees, 91,789 bytes allocated ==9292== ==9292== 21,484 (2,644 direct, 18,840 indirect) bytes in 1 blocks lost in loss record 4 of 4 ==9292== @ 0x4008409: operator new[](unsigned int) (vg_replace_malloc.c:357) ==9292== 0x804ac7e: myclass::resize() (file.cpp:92) ==9292== 0x804ac34: myclass::add(int, int) (file.cpp:82) ==9292== 0x804aae6: getline(std::

Google Drive SDK for iOS: issue with queries -

i've run issue gtlquerydrive. callbacks queryforchildrenlistwithfolderid:@"root" & queryforfileslist methods return 0 items. nslog(@"files count: %d", files.items.count) gives me 0. https://github.com/googledrive/dredit/tree/master/objectivec - i'm using example play drive apis, removed search restriction - query.q = @"mimetype = 'text/plain'"; files. make sure specify kgtlauthscopedrive. made mistake of using kgtlauthscopedrivefile sample app; restricts scope files created app, while kgtlauthscopedrive gives app access user's files. also, 'root' query, add @"'root' in parents , trashed=false" youer query.q. example mine looks this: gtlquerydrive *query; if ([self isroot]) { query = [gtlquerydrive queryforchildrenlistwithfolderid:@"root"]; query.q = @"'root' in parents , trashed=false"; } else { query = [gtlquerydrive queryforchildrenlis

java - How to instantiate a generic class -

i thought understood how use .class , class<> guess not. below super(approvalworkstation.class not being mapped constructor. how can sure i'm passing class reference base workstationrequest can instantiate it? public class approvalworkstation extends workstation { public approvalworkstation(workstationentity entity) { super(entity); } } public class workstationrequest extends com.production.socket.request.workstationrequest { public workstationrequest() { super(approvalworkstation.class); //unable map constructor } } this base workstationrequest that's extended above public class workstationrequest { private class<workstation> workstationclass; public void workstationrequest(class<workstation> workstationclass) { this.workstationclass = workstationclass; } update i'm sorry confusion, constructor has class<workstation> , not workstation had. in order able pass both

java - Is int[] an object? -

this question has answer here: is array object in java 8 answers had look, , can't seem find question same this. question int[] in java. when create int[] , use syntax: int[] x = new int[5]; the methods part of int[] make me think it's object , doesn't follow java naming convention classes, what's confusing me. array of primitive type, can used primitive. is int[] (or primitive array guess) object, or primitive? an array in java subclass of object , therefore it's object type - if contains primitive types. can check this: int[] x = new int[5]; if (x instanceof object) system.out.println("it's object!");

Servlet-handling login cookies -

imagine user in java servlet program signs personal information. if wants re-use can log in username , password submitted before. want know how going check cookies stored in browser in order see if specific username followed specific password. wondering if cookies stored in same row added or stored randomly. i know can check them writing this: for(int = 0; i< cookies.length; i++) { cookie thiscookie = cookies[i]; if (thiscookie.getname().equals("usn")) //... but there seems problem,as there number of usernames , passwords stored in browser linking between 2 of them specific.

c++ - Lookup Combo that supports remote data - load data only after user wants to -

i'm building vcl c++ builder application. see if knows of component can load data in lookup upon drop down after user has typed few letters limit rows queried? preferably after pressing tab, or enter. what best behaviour similar linux command line has, might wishful thinking. way work drop down combo list after user presses tab if there multiple options available, , fill in additional text till point characters not same anymore, if user presses tab again, drop down list. the next best if drop down allow drop down if user has typed few letters, pressing specific button opens dataset parameter of typed text far, drops down combo. does component exist? you can check out tms software . i'm not sure if has you, components quite flexible. , can send feature request them - consider next update. if lucky might add next release.

c# - datagridview pans on clicking a cell -

i have winforms application has datagridview control. now, when click on cell in datagridview control, view shifts/pans datagridview control, such cell selected more or less in centre of screen. there way disable this? users find irritating. the data gridview needed show colour codes (i.e. no text) , tooltips each cell. have tried datagridview1.enabled = false; this solves problem, however, can no longer view tooltip text. there other work-around? possible prevent user clicking on cell in first place prevent this?

jquery animate - Circular page transitions -

i experimenting animations , page transitions, trying create page 3 circular images function navigation buttons. when click 1 of them, want circle expand fill entire page, , thereby become background. i've put little mock-up of similar you're describing started. solution requires jquery , jquery ui, , creates animation blow circular div element fill whole page. html: <div class="circle"> <div>red contents go here!</div> </div> <div class="circle"> <div>green contents go here!</div> </div> <div class="circle"> <div>blue contents go here!</div> </div> css: .circle { display: inline-block; position: absolute; left: 50%; top: 50%; height: 50px; width: 50px; margin: -25px 0 0 -25px; cursor: pointer; border-radius: 25px; z-index: 0; } .circle:nth-child(1) { background: red; margin-left: -80px; } .circle:nth-child(2) { back

javascript - How to get reference to current textbox in a table which contains 50 textboxes? -

Image
basically have table 50 rows , each row has 2 td. 1 input , next 1 has label , dynamic. refer image dilemma user enters number in textbox(how know 1 if dont want loop through of them?) , on enter key event call javascript function checks if valid , adds corresponding message next tds label. how know reference of input without looping through textboxes call function on each textbox input's enter function? the following works, based upon (limited available information), though requires handle validation yourself, obviously: function yourdefinedfunction(){ // need handle validating yourself, somehow. return false; } /* binds 'keypress' 'tr' elements, 'listens' see if take place on/in 'td' element */ $('tbody tr').on('keypress', 'td', function(e){ /* 'this' 'td' element, 'e.target' element within 'td' received event var cell = this, target = e

c# - Memory Leak from use of DispatcherTimer -

so i'm not greatest @ analyzing memory leaks can tell have located one. i using timer check if connected , when comment out timer memory leak goes away. the timer code simple, this: private system.windows.threading.dispatchertimer embdattachtimer = new system.windows.threading.dispatchertimer(); embdattachtimer.tick += new eventhandler(attachtimer_elapsed); embdattachtimer.interval = new timespan(0, 0, 0, 0, 500); embdattachtimer.start(); the code eventhandler "attachtimer_elapsed" follows: void attachtimer_elapsed(object sender, eventargs e) { battached = isunitattached(); // simple check of usb connection updatecnctstattext(); // calls ui elements update them "connected" or "not connected" } the code isunitattached() makes call library driven function checks msp430 processor on other end of usb line. bool isunitattached { bsuccess = usbi_msp430.connect(); if (!bsuccess) { console.writeline("unable connect.&

c# - MVC routing with "optional" routes -

i'm bit baffled how mvc figuring out routing details. let me see if can explain right. so ... given have default route ... routes.maproute( "default", "{controller}/{action}/{id}", new { controller = "cms", action = "getpage", id = urlparameter.optional } ); and app content management system want create nice urls site structure i'll map wildcard url lets me determine if need render 404 based on what's in database ... routes.maproute( "cms", "{*path}", new { controller = "cms", action = "getpage", path = string.empty } ); herein lies problem. mvc match default route because technically no params required assuming "getpage" on "cms" controller requires no params, not want. what i'm trying "given 2 or 3 url parts, controller , action match optional id parameter other urls including ones can't match route fall down in cms r

java - how to change font direction inside styles.xml -

i have language changhing buttons , want set font direction in styles.xml each language . <!-- application theme. --> <style name="apptheme" parent="appbasetheme"> <!-- customizations not specific particular api-level can go here. --> </style> how ? this set direction of text in styles.xml, has done in every button android:textdirection=""

select - Percentages in MySQL - Between two columns in the same table -

i have mysql table looks this: name | pass | fail | pass percent | fail percent abdy | 20 | 5 | | bob | 10 | 5 | | cantona | 40 | 10 | | dave | 30 | 20 | | i trying percentages: like : passpercent = (pass/pass+fail)*100 can fill table single mysql code both columns?? the table hopefully: name | pass | fail | pass percent | fail percent abdy | 20 | 5 | 80 | 20 bob | 10 | 5 | 66 | 33 cantona | 40 | 10 | 80 | 20 dave | 30 | 20 | 60 | 40 that's absolutely possible. to fill second table: update mytable set pass_pct=(pass/pass+fail)*100,fail_pct=(fail/pass+fail)*100 granted, generate during selection of first table (if don't want store results), like: select name,pass,fail,(pass/pass+fail)*100 pass_pct,(fail/pass+fail)*100 fail_pct mytable

java - Outputting List<int[]> does not work -

this question has answer here: what's simplest way print java array? 23 answers i'm trying figure out why code isn't outputting coin change permutations list list of int arrays. it's outputting hex value (or whatever i@64578ceb is). any thoughts? call: system.out.println("permutations list: " + dan.makechange(27)); code: public class person { int[] denominations, coinvalues; list<int[]> resultslist; public person() { denominations = new int[]{25, 10, 5, 1}; resultslist = new arraylist<int[]>(); } public list<int[]> makechange(int change) { return resultslist= changemaker(change, new int[] {0,0,0,0}); } public list<int[]> changemaker(int change, int[] toadd) { if (change == 0) { resultslist.add(toadd); return resultslist; } (int = 0; < denominatio

c# - How to get rid of the view state caching for ASP.NET page -

i make dynamic table in code behind file using code such: <table border="0" cellpadding="4" cellspacing="0"> <asp:placeholder id="placeholder1" enableviewstate="false" runat="server"></asp:placeholder> </table> and here's how build in page_load(): system.web.ui.htmlcontrols.htmlgenericcontrol trcontainer0 = new system.web.ui.htmlcontrols.htmlgenericcontrol("tr"); system.web.ui.htmlcontrols.htmlgenericcontrol tdcontainer00 = new system.web.ui.htmlcontrols.htmlgenericcontrol("td"); //time variable datetime dtdatetime0 = datetime.now(); //time (must localized) textbox tbxattime = new textbox(); tbxattime.enableviewstate = false; tbxattime.id = "mytime1"; tbxattime.text = dtdatetime0.toshorttimestring(); tdcontainer00.controls.add(tbxattime); trcontainer0.controls.add(tdcontainer00); placeholder1.controls.add(trcontainer0); this loads tbxattime text box corr

git - Find the commit that changed file permissions -

what combination of arguments git log or similar find commit changed permissions on file? i can use git log -p <file> , grep "new mode", doesn't seem satisfying. my solution use git log --summary , grep list commits permission of given file modified git log --summary {file} |grep -e ^commit -e"=>"|grep '=>' -b1 | grep ^commit if {file} omitted, list commits, file's permission modified.

php - How to remove "index.html/" from Laravel Form Builder open() -

i have form in laravel 4 uses: {{ form::open('login') }} this generates following: <form method="post" action="http://[...]/public/index.php/login" accept-charset="utf-8"> i have .htaccess et al. configured "index.html" hidden uri, hidden these generated urls, too. has run , solved yet? you need edit application/config/application.php , remove index.php. effect form , url's generated route().

Send catched ajax exception back to server to perform logging? -

i have mvc3 application , i'm using elmah store errors in mysql database , send errors email. working perfectly, have javascript code in main layout: $(document).ajaxerror(function (e, xhr, settings, exception) { //send server exception }); now, want catched exception (the ajax exception) , send server method stores exception elmah. possible? if isn't choice have? this following article shows guidance on how log javascript errors elmah: logging errors elmah in asp.net mvc 3 – part 5 – (javascript) i know mechanism report error server specific mvc, should adaptable asp.net web forms if needed.

vb.net - For Each Loop Iteration Count -

can keep track of our iteration in our loop when use for each ? use each loops looping through objects cannot seem find way keep index of i'm @ in loop. unless of course create own ... if want have index, use for -loop instead of for each . that's why exists. for int32 = 0 objects.count - 1 dim obj = objects(i) next of course nothing prevents creating own counter: dim counter int32 = 0 each obj in objects counter += 1 next or can use linq: dim query = objects.select(function(obj, index) "index is:" & index)

Can I display my own HTML in Liferay? -

i trying display own html file inside of liferay portal. possible? if is, how do it? thanks! liferay cms too, need learn web content management system.

jsf - How to use EL with p:panel header? -

i want put dynamic string inside p:panel header using p:inputtext example value="#{object.property}" possible ? just use <f:facet name="header"> facet within <p:panel> : <p:panel> <f:facet name="header"> <p:inputtext value=#{object.property} /> ... </f:facet> ... </p:panel> or, if want output text there, can use <p:panel header="#{object.property}" ... > .

ruby - How to clean up this very simple Rails function? -

is there way pretty rails code? def function if new_record? thing else thing + yet_another_thing end end i don't repetition of thing here, wonder if there's cleaner way. thanks help. this works objects support +, (even strings.) [thing, (yet_another_thing unless new_record?)].compact.inject(:+) it's dry , scary, being trapped in desert without water. you might able away with: thing.dup.tap{|t| t << yet_another_thing unless new_record?} this won't work if thing integer (you can't dup it) , needs support << operator. also dry scary in different way.

python - Sanitizing user input path names -

using python 2.6 on windows have function needs accept path name arg. i'm running issues when specific paths passed. c:\users\bob\something.png #this handled no prob. c:\users\bob\nothing.png #this generates windowserror c:\users\bob\test.png #this generates windowserror what i'm gathering \n in "nothing" path being interpreted new line, , \t in "test" path being interpreted tab. if print out path names, that's appears happening. print os.path.abspath("c:\users\bob\nothing.png") c:\users\bob othing.png same 'test' path, except tab instead of new line. the thing i've come far check see if \n or \t in path name, , handle accordingly, there must assuredly better way. if '\n' in path_name: #escape slash, move on what better way be? print os.path.abspath(r"c:\users\bob\nothing.png") may looking ... although user input should automatically escaping slash ... >

c++ - Output wrong. Possible strncpy issue? -

so, i'm trying code parse each line inputted file individual tokens, add each 1 in turn tklist array. main prints out each token. it's printing blanks though, , when step code looks strncpy isn't working. ideas issue is? no errors. here's main function: #include <iostream> #include <fstream> using namespace std; #include "definitions.h" #include "system_utilities.h" int main() { ifstream infile; char line[max_cmd_line_length]; char* token[max_tokens_on_a_line]; int numtokens; system("pwd"); infile.open("p4input.txt", ios::in); if(infile.fail()) { cout << "could not open input file. program terminating.\n\n"; return 0; } while (!infile.eof()) { infile.getline(line, 255); line[strlen(line)+1] = '\0'; numtokens = parsecommandline(line, token); int t; (t=1; t <= numtokens; t++) { cout